Programming Interface for NVM
- Supports:
- creationix/nvm for Linux and OS X
https://github.com/creationix/nvm
- coreybutler/nvm-windows for Windows
https://github.com/coreybutler/nvm-windows

@method NvmApi
8955
function NvmApi () {
	var self = this;

	Object.defineProperty(this, "initialized", {
		"value": false,
		"enumerable": false,
		"writable": true
	});

	Object.defineProperty(this, "__data", {
		"value": {},
		"enumerable": false,
		"writable": true
	});

	// Get data for NVM wrapper
	Async.parallel([
		function (cb) {
			COMMANDS.current(function (err, version) {
				if (err) {
					return cb(err);
				}

				self.__data.current = version;
				cb();
			});
		},

		function (cb) {
			COMMANDS.nvmVersion(function (err, version) {
				if (err) {
					return cb(err);
				}

				self.__data.version = version;
				cb();
			});
		},

		function (cb) {
			COMMANDS.nodePath(function (err, path) {
				if (err) {
					return cb(err);
				}

				self.__data.which = path;
				cb();
			});
		},

		function (cb) {
			COMMANDS.list(function (err, versions) {
				if (err) {
					return cb(err);
				}

				if (versions.hasOwnProperty("current")) {
					delete versions.current;
				}

				self.__data.installed = versions;
				cb();
			});
		}
	], function (err) {
		if (err) {
			console.warn(
				"Error Calling NVM. Make sure it's properly installed and sourced."
			);

			console.error(err.stack || err.message || err);
			return;
		}

		self.initialized = true;

		if (self.__data.hasOwnProperty("callbacks")) {
			self.__data.callbacks.forEach(function (func) {
				func.call(self, self);
			});
		}
	});

	return this;
}
1339513
def _run_with_kvm(self, qemu_path, options):
        

        if sys.platform.startswith("linux") and self.manager.config.get_section_config("Qemu").getboolean("enable_kvm", True) \
                and "-no-kvm" not in options:

            # Turn OFF kvm for non x86 architectures
            if os.path.basename(qemu_path) not in ["qemu-system-x86_64", "qemu-system-i386", "qemu-kvm"]:
                return False

            if not os.path.exists("/dev/kvm"):
                if self.manager.config.get_section_config("Qemu").getboolean("require_kvm", True):
                    raise QemuError("KVM acceleration cannot be used (/dev/kvm doesn't exist). You can turn off KVM support in the gns3_server.conf by adding enable_kvm = false to the [Qemu] section.")
                else:
                    return False
            return True
        return False
17627
function _newGraphSONMapper() {
        return Tinkerpop.GraphSONMapper.buildP()
            .then(function (builder) {
            return builder.embedTypesP(true);
        })
            .then(function (builder) {
            return builder.createP();
        });
    }
1240222
function attachMosaic() {
		// Check for form errors
		if(undefined === $("#mosaicAmount").val() || !nem.utils.helpers.isTextAmountValid($("#mosaicAmount").val())) return alert('Invalid amount !');
		if(!$("#namespaceId").val() || !$("#mosaicName").val()) return alert('Missing parameter !');

		// If not XEM, fetch the mosaic definition from network
		if($("#mosaicName").val() !== 'xem') {
			nem.com.requests.namespace.mosaicDefinitions(endpoint, $("#namespaceId").val()).then(function(res) {

				// Look for the mosaic definition(s) we want in the request response (Could use ["eur", "usd"] to return eur and usd mosaicDefinitionMetaDataPairs)
				var neededDefinition = nem.utils.helpers.searchMosaicDefinitionArray(res.data, [$("#mosaicName").val()]);

				// Get full name of mosaic to use as object key
				var fullMosaicName  = $("#namespaceId").val() + ':' + $("#mosaicName").val();

				// Check if the mosaic was found
				if(undefined === neededDefinition[fullMosaicName]) return alert("Mosaic not found !");
				
				// Set mosaic definition into mosaicDefinitionMetaDataPair
				mosaicDefinitionMetaDataPair[fullMosaicName] = {};
				mosaicDefinitionMetaDataPair[fullMosaicName].mosaicDefinition = neededDefinition[fullMosaicName];

				// Now we have the definition we can calculate quantity out of user input
				var quantity = nem.utils.helpers.cleanTextAmount($("#mosaicAmount").val()) * Math.pow(10, neededDefinition[fullMosaicName].properties[0].value);

				// Create a mosaic attachment
				var mosaicAttachment = nem.model.objects.create("mosaicAttachment")($("#namespaceId").val(), $("#mosaicName").val(), quantity);

				// Push attachment into transaction mosaics
				transferTransaction.mosaics.push(mosaicAttachment);

				// Calculate back the quantity to an amount to show in the view. It should be the same as user input but we double check to see if quantity is correct.
				var totalToShow = nem.utils.format.supply(quantity, {"namespaceId": $("#namespaceId").val(), "name": $("#mosaicName").val()}, mosaicDefinitionMetaDataPair)[0] + '.' + nem.utils.format.supply(quantity, {"namespaceId": $("#namespaceId").val(), "name": $("#mosaicName").val()}, mosaicDefinitionMetaDataPair)[1];

				// Push mosaic to the list in view
				$("#mosaicList").prepend('<li>'+ totalToShow +' <small><b>'+  $("#namespaceId").val() + ':' + $("#mosaicName").val() +'</b></small> </li>');

				// Update the transaction fees in view
				updateFee();
			}, 
			function(err) {
				alert(err);
			});
		} else {
			// Calculate quantity from user input, XEM divisibility is 6
			var quantity = nem.utils.helpers.cleanTextAmount($("#mosaicAmount").val()) * Math.pow(10, 6);

			// Create a mosaic attachment
			var mosaicAttachment = nem.model.objects.create("mosaicAttachment")($("#namespaceId").val(), $("#mosaicName").val(), quantity);

			// Push attachment into transaction mosaics
			transferTransaction.mosaics.push(mosaicAttachment);

			// Calculate back the quantity to an amount to show in the view. It should be the same as user input but we double check to see if quantity is correct.
			var totalToShow = nem.utils.format.supply(quantity, {"namespaceId": $("#namespaceId").val(), "name": $("#mosaicName").val()}, mosaicDefinitionMetaDataPair)[0] + '.' + nem.utils.format.supply(quantity, {"namespaceId": $("#namespaceId").val(), "name": $("#mosaicName").val()}, mosaicDefinitionMetaDataPair)[1];

			// Push mosaic to the list in view
			$("#mosaicList").prepend('<li>'+ totalToShow +' <small><b>'+  $("#namespaceId").val() + ':' + $("#mosaicName").val() +'</b></small> </li>');

			// Update the transaction fees in view
				updateFee();
		}
	}
54246
def _virtual(osdata):
    '''
    
    '''
    # This is going to be a monster, if you are running a vm you can test this
    # grain with please submit patches!
    # Provides:
    #   virtual
    #   virtual_subtype
    grains = {'virtual': 'physical'}

    # Skip the below loop on platforms which have none of the desired cmds
    # This is a temporary measure until we can write proper virtual hardware
    # detection.
    skip_cmds = ('AIX',)

    # list of commands to be executed to determine the 'virtual' grain
    _cmds = ['systemd-detect-virt', 'virt-what', 'dmidecode']
    # test first for virt-what, which covers most of the desired functionality
    # on most platforms
    if not salt.utils.platform.is_windows() and osdata['kernel'] not in skip_cmds:
        if salt.utils.path.which('virt-what'):
            _cmds = ['virt-what']

    # Check if enable_lspci is True or False
    if __opts__.get('enable_lspci', True) is True:
        # /proc/bus/pci does not exists, lspci will fail
        if os.path.exists('/proc/bus/pci'):
            _cmds += ['lspci']

    # Add additional last resort commands
    if osdata['kernel'] in skip_cmds:
        _cmds = ()

    # Quick backout for BrandZ (Solaris LX Branded zones)
    # Don't waste time trying other commands to detect the virtual grain
    if HAS_UNAME and osdata['kernel'] == 'Linux' and 'BrandZ virtual linux' in os.uname():
        grains['virtual'] = 'zone'
        return grains

    failed_commands = set()
    for command in _cmds:
        args = []
        if osdata['kernel'] == 'Darwin':
            command = 'system_profiler'
            args = ['SPDisplaysDataType']
        elif osdata['kernel'] == 'SunOS':
            virtinfo = salt.utils.path.which('virtinfo')
            if virtinfo:
                try:
                    ret = __salt__['cmd.run_all']('{0} -a'.format(virtinfo))
                except salt.exceptions.CommandExecutionError:
                    if salt.log.is_logging_configured():
                        failed_commands.add(virtinfo)
                else:
                    if ret['stdout'].endswith('not supported'):
                        command = 'prtdiag'
                    else:
                        command = 'virtinfo'
            else:
                command = 'prtdiag'

        cmd = salt.utils.path.which(command)

        if not cmd:
            continue

        cmd = '{0} {1}'.format(cmd, ' '.join(args))

        try:
            ret = __salt__['cmd.run_all'](cmd)

            if ret['retcode'] > 0:
                if salt.log.is_logging_configured():
                    # systemd-detect-virt always returns > 0 on non-virtualized
                    # systems
                    # prtdiag only works in the global zone, skip if it fails
                    if salt.utils.platform.is_windows() or 'systemd-detect-virt' in cmd or 'prtdiag' in cmd:
                        continue
                    failed_commands.add(command)
                continue
        except salt.exceptions.CommandExecutionError:
            if salt.log.is_logging_configured():
                if salt.utils.platform.is_windows():
                    continue
                failed_commands.add(command)
            continue

        output = ret['stdout']
        if command == "system_profiler":
            macoutput = output.lower()
            if '0x1ab8' in macoutput:
                grains['virtual'] = 'Parallels'
            if 'parallels' in macoutput:
                grains['virtual'] = 'Parallels'
            if 'vmware' in macoutput:
                grains['virtual'] = 'VMware'
            if '0x15ad' in macoutput:
                grains['virtual'] = 'VMware'
            if 'virtualbox' in macoutput:
                grains['virtual'] = 'VirtualBox'
            # Break out of the loop so the next log message is not issued
            break
        elif command == 'systemd-detect-virt':
            if output in ('qemu', 'kvm', 'oracle', 'xen', 'bochs', 'chroot', 'uml', 'systemd-nspawn'):
                grains['virtual'] = output
                break
            elif 'vmware' in output:
                grains['virtual'] = 'VMware'
                break
            elif 'microsoft' in output:
                grains['virtual'] = 'VirtualPC'
                break
            elif 'lxc' in output:
                grains['virtual'] = 'LXC'
                break
            elif 'systemd-nspawn' in output:
                grains['virtual'] = 'LXC'
                break
        elif command == 'virt-what':
            try:
                output = output.splitlines()[-1]
            except IndexError:
                pass
            if output in ('kvm', 'qemu', 'uml', 'xen', 'lxc'):
                grains['virtual'] = output
                break
            elif 'vmware' in output:
                grains['virtual'] = 'VMware'
                break
            elif 'parallels' in output:
                grains['virtual'] = 'Parallels'
                break
            elif 'hyperv' in output:
                grains['virtual'] = 'HyperV'
                break
        elif command == 'dmidecode':
            # Product Name: VirtualBox
            if 'Vendor: QEMU' in output:
                # FIXME: Make this detect between kvm or qemu
                grains['virtual'] = 'kvm'
            if 'Manufacturer: QEMU' in output:
                grains['virtual'] = 'kvm'
            if 'Vendor: Bochs' in output:
                grains['virtual'] = 'kvm'
            if 'Manufacturer: Bochs' in output:
                grains['virtual'] = 'kvm'
            if 'BHYVE' in output:
                grains['virtual'] = 'bhyve'
            # Product Name: (oVirt) www.ovirt.org
            # Red Hat Community virtualization Project based on kvm
            elif 'Manufacturer: oVirt' in output:
                grains['virtual'] = 'kvm'
                grains['virtual_subtype'] = 'ovirt'
            # Red Hat Enterprise Virtualization
            elif 'Product Name: RHEV Hypervisor' in output:
                grains['virtual'] = 'kvm'
                grains['virtual_subtype'] = 'rhev'
            elif 'VirtualBox' in output:
                grains['virtual'] = 'VirtualBox'
            # Product Name: VMware Virtual Platform
            elif 'VMware' in output:
                grains['virtual'] = 'VMware'
            # Manufacturer: Microsoft Corporation
            # Product Name: Virtual Machine
            elif ': Microsoft' in output and 'Virtual Machine' in output:
                grains['virtual'] = 'VirtualPC'
            # Manufacturer: Parallels Software International Inc.
            elif 'Parallels Software' in output:
                grains['virtual'] = 'Parallels'
            elif 'Manufacturer: Google' in output:
                grains['virtual'] = 'kvm'
            # Proxmox KVM
            elif 'Vendor: SeaBIOS' in output:
                grains['virtual'] = 'kvm'
            # Break out of the loop, lspci parsing is not necessary
            break
        elif command == 'lspci':
            # dmidecode not available or the user does not have the necessary
            # permissions
            model = output.lower()
            if 'vmware' in model:
                grains['virtual'] = 'VMware'
            # 00:04.0 System peripheral: InnoTek Systemberatung GmbH
            #         VirtualBox Guest Service
            elif 'virtualbox' in model:
                grains['virtual'] = 'VirtualBox'
            elif 'qemu' in model:
                grains['virtual'] = 'kvm'
            elif 'virtio' in model:
                grains['virtual'] = 'kvm'
            # Break out of the loop so the next log message is not issued
            break
        elif command == 'prtdiag':
            model = output.lower().split("\n")[0]
            if 'vmware' in model:
                grains['virtual'] = 'VMware'
            elif 'virtualbox' in model:
                grains['virtual'] = 'VirtualBox'
            elif 'qemu' in model:
                grains['virtual'] = 'kvm'
            elif 'joyent smartdc hvm' in model:
                grains['virtual'] = 'kvm'
            break
        elif command == 'virtinfo':
            grains['virtual'] = 'LDOM'
            break

    choices = ('Linux', 'HP-UX')
    isdir = os.path.isdir
    sysctl = salt.utils.path.which('sysctl')
    if osdata['kernel'] in choices:
        if os.path.isdir('/proc'):
            try:
                self_root = os.stat('/')
                init_root = os.stat('/proc/1/root/.')
                if self_root != init_root:
                    grains['virtual_subtype'] = 'chroot'
            except (IOError, OSError):
                pass
        if isdir('/proc/vz'):
            if os.path.isfile('/proc/vz/version'):
                grains['virtual'] = 'openvzhn'
            elif os.path.isfile('/proc/vz/veinfo'):
                grains['virtual'] = 'openvzve'
                # a posteriori, it's expected for these to have failed:
                failed_commands.discard('lspci')
                failed_commands.discard('dmidecode')
        # Provide additional detection for OpenVZ
        if os.path.isfile('/proc/self/status'):
            with salt.utils.files.fopen('/proc/self/status') as status_file:
                vz_re = re.compile(r'^envID:\s+(\d+)$')
                for line in status_file:
                    vz_match = vz_re.match(line.rstrip('\n'))
                    if vz_match and int(vz_match.groups()[0]) != 0:
                        grains['virtual'] = 'openvzve'
                    elif vz_match and int(vz_match.groups()[0]) == 0:
                        grains['virtual'] = 'openvzhn'
        if isdir('/proc/sys/xen') or \
                isdir('/sys/bus/xen') or isdir('/proc/xen'):
            if os.path.isfile('/proc/xen/xsd_kva'):
                # Tested on CentOS 5.3 / 2.6.18-194.26.1.el5xen
                # Tested on CentOS 5.4 / 2.6.18-164.15.1.el5xen
                grains['virtual_subtype'] = 'Xen Dom0'
            else:
                if osdata.get('productname', '') == 'HVM domU':
                    # Requires dmidecode!
                    grains['virtual_subtype'] = 'Xen HVM DomU'
                elif os.path.isfile('/proc/xen/capabilities') and \
                        os.access('/proc/xen/capabilities', os.R_OK):
                    with salt.utils.files.fopen('/proc/xen/capabilities') as fhr:
                        if 'control_d' not in fhr.read():
                            # Tested on CentOS 5.5 / 2.6.18-194.3.1.el5xen
                            grains['virtual_subtype'] = 'Xen PV DomU'
                        else:
                            # Shouldn't get to this, but just in case
                            grains['virtual_subtype'] = 'Xen Dom0'
                # Tested on Fedora 10 / 2.6.27.30-170.2.82 with xen
                # Tested on Fedora 15 / 2.6.41.4-1 without running xen
                elif isdir('/sys/bus/xen'):
                    if 'xen:' in __salt__['cmd.run']('dmesg').lower():
                        grains['virtual_subtype'] = 'Xen PV DomU'
                    elif os.path.isfile('/sys/bus/xen/drivers/xenconsole'):
                        # An actual DomU will have the xenconsole driver
                        grains['virtual_subtype'] = 'Xen PV DomU'
            # If a Dom0 or DomU was detected, obviously this is xen
            if 'dom' in grains.get('virtual_subtype', '').lower():
                grains['virtual'] = 'xen'
        # Check container type after hypervisors, to avoid variable overwrite on containers running in virtual environment.
        if os.path.isfile('/proc/1/cgroup'):
            try:
                with salt.utils.files.fopen('/proc/1/cgroup', 'r') as fhr:
                    fhr_contents = fhr.read()
                if ':/lxc/' in fhr_contents:
                    grains['virtual_subtype'] = 'LXC'
                elif ':/kubepods/' in fhr_contents:
                    grains['virtual_subtype'] = 'kubernetes'
                elif ':/libpod_parent/' in fhr_contents:
                    grains['virtual_subtype'] = 'libpod'
                else:
                    if any(x in fhr_contents
                           for x in (':/system.slice/docker', ':/docker/',
                                     ':/docker-ce/')):
                        grains['virtual_subtype'] = 'Docker'
            except IOError:
                pass
        if os.path.isfile('/proc/cpuinfo'):
            with salt.utils.files.fopen('/proc/cpuinfo', 'r') as fhr:
                if 'QEMU Virtual CPU' in fhr.read():
                    grains['virtual'] = 'kvm'
        if os.path.isfile('/sys/devices/virtual/dmi/id/product_name'):
            try:
                with salt.utils.files.fopen('/sys/devices/virtual/dmi/id/product_name', 'r') as fhr:
                    output = salt.utils.stringutils.to_unicode(fhr.read(), errors='replace')
                    if 'VirtualBox' in output:
                        grains['virtual'] = 'VirtualBox'
                    elif 'RHEV Hypervisor' in output:
                        grains['virtual'] = 'kvm'
                        grains['virtual_subtype'] = 'rhev'
                    elif 'oVirt Node' in output:
                        grains['virtual'] = 'kvm'
                        grains['virtual_subtype'] = 'ovirt'
                    elif 'Google' in output:
                        grains['virtual'] = 'gce'
                    elif 'BHYVE' in output:
                        grains['virtual'] = 'bhyve'
            except IOError:
                pass
    elif osdata['kernel'] == 'FreeBSD':
        kenv = salt.utils.path.which('kenv')
        if kenv:
            product = __salt__['cmd.run'](
                '{0} smbios.system.product'.format(kenv)
            )
            maker = __salt__['cmd.run'](
                '{0} smbios.system.maker'.format(kenv)
            )
            if product.startswith('VMware'):
                grains['virtual'] = 'VMware'
            if product.startswith('VirtualBox'):
                grains['virtual'] = 'VirtualBox'
            if maker.startswith('Xen'):
                grains['virtual_subtype'] = '{0} {1}'.format(maker, product)
                grains['virtual'] = 'xen'
            if maker.startswith('Microsoft') and product.startswith('Virtual'):
                grains['virtual'] = 'VirtualPC'
            if maker.startswith('OpenStack'):
                grains['virtual'] = 'OpenStack'
            if maker.startswith('Bochs'):
                grains['virtual'] = 'kvm'
        if sysctl:
            hv_vendor = __salt__['cmd.run']('{0} hw.hv_vendor'.format(sysctl))
            model = __salt__['cmd.run']('{0} hw.model'.format(sysctl))
            jail = __salt__['cmd.run'](
                '{0} -n security.jail.jailed'.format(sysctl)
            )
            if 'bhyve' in hv_vendor:
                grains['virtual'] = 'bhyve'
            if jail == '1':
                grains['virtual_subtype'] = 'jail'
            if 'QEMU Virtual CPU' in model:
                grains['virtual'] = 'kvm'
    elif osdata['kernel'] == 'OpenBSD':
        if 'manufacturer' in osdata:
            if osdata['manufacturer'] in ['QEMU', 'Red Hat', 'Joyent']:
                grains['virtual'] = 'kvm'
            if osdata['manufacturer'] == 'OpenBSD':
                grains['virtual'] = 'vmm'
    elif osdata['kernel'] == 'SunOS':
        if grains['virtual'] == 'LDOM':
            roles = []
            for role in ('control', 'io', 'root', 'service'):
                subtype_cmd = '{0} -c current get -H -o value {1}-role'.format(cmd, role)
                ret = __salt__['cmd.run_all']('{0}'.format(subtype_cmd))
                if ret['stdout'] == 'true':
                    roles.append(role)
            if roles:
                grains['virtual_subtype'] = roles
        else:
            # Check if it's a "regular" zone. (i.e. Solaris 10/11 zone)
            zonename = salt.utils.path.which('zonename')
            if zonename:
                zone = __salt__['cmd.run']('{0}'.format(zonename))
                if zone != 'global':
                    grains['virtual'] = 'zone'
            # Check if it's a branded zone (i.e. Solaris 8/9 zone)
            if isdir('/.SUNWnative'):
                grains['virtual'] = 'zone'
    elif osdata['kernel'] == 'NetBSD':
        if sysctl:
            if 'QEMU Virtual CPU' in __salt__['cmd.run'](
                    '{0} -n machdep.cpu_brand'.format(sysctl)):
                grains['virtual'] = 'kvm'
            elif 'invalid' not in __salt__['cmd.run'](
                    '{0} -n machdep.xen.suspend'.format(sysctl)):
                grains['virtual'] = 'Xen PV DomU'
            elif 'VMware' in __salt__['cmd.run'](
                    '{0} -n machdep.dmi.system-vendor'.format(sysctl)):
                grains['virtual'] = 'VMware'
            # NetBSD has Xen dom0 support
            elif __salt__['cmd.run'](
                    '{0} -n machdep.idle-mechanism'.format(sysctl)) == 'xen':
                if os.path.isfile('/var/run/xenconsoled.pid'):
                    grains['virtual_subtype'] = 'Xen Dom0'

    for command in failed_commands:
        log.info(
            "Although '%s' was found in path, the current user "
            'cannot execute it. Grains output might not be '
            'accurate.', command
        )
    return grains
96787
def _nxapi_config(commands, methods='cli_conf', bsb_arg=None, **kwargs):
    '''
    
    '''
    api_kwargs = __salt__['config.get']('nxos', {})
    api_kwargs.update(**kwargs)
    if not isinstance(commands, list):
        commands = [commands]
    try:
        ret = _nxapi_request(commands, **kwargs)
        if api_kwargs.get('no_save_config'):
            pass
        else:
            _nxapi_request(COPY_RS, **kwargs)
        for each in ret:
            if 'Failure' in each:
                log.error(each)
    except CommandExecutionError as e:
        log.error(e)
        return [commands, repr(e)]
    return [commands, ret]
106948
protected function _nvme()
    {
        if (CommonFunctions::executeProgram('nvme', 'list', $bufr, PSI_DEBUG) && ($bufr!="")) {
            $bufe = preg_split("/\n/", $bufr, -1, PREG_SPLIT_NO_EMPTY);
            $count = 0;
            $nlocate = array();
            $nsize = array();
            foreach ($bufe as $buf) {
                if ($count == 1) {
                    $locid = 0;
                    $nlocate[0] = 0;
                    $total = strlen($buf);
                    $begin = true;
                    for ($i = 0; $i < $total; $i++) {
                        if ($begin) {
                            if ($buf[$i] !== '-') {
                                $nsize[$locid] = $i - $nlocate[$locid];
                                $locid++;
                                $begin = false;
                            }
                        } else {
                            if ($buf[$i] === '-') {
                                $nlocate[$locid] = $i;
                                $begin = true;
                            }
                        }
                    }
                    if ($begin) {
                        $nsize[$locid] = $i - $nlocate[$locid];
                    }
                } elseif ($count > 1) {
                    if (isset($nlocate[2]) && isset($nsize[2])) {
                        $dev = new HWDevice();
                        $dev->setName(trim(substr($buf, $nlocate[2], $nsize[2])));
                        if (defined('PSI_SHOW_NETWORK_INFOS') && (PSI_SHOW_NETWORK_INFOS)) {
                            if (isset($nlocate[4]) && isset($nsize[4])) {
                                if (preg_match('/\/\s*([0-9\.]+)\s*(B|KB|MB|GB|TB|PB)$/', str_replace(',', '.', trim(substr($buf, $nlocate[4], $nsize[4]))), $tmpbuf)) {
                                    switch ($tmpbuf[2]) {
                                        case 'B':
                                            $dev->setCapacity($tmpbuf[1]);
                                            break;
                                        case 'KB':
                                            $dev->setCapacity(1000*$tmpbuf[1]);
                                            break;
                                        case 'MB':
                                            $dev->setCapacity(1000*1000*$tmpbuf[1]);
                                            break;
                                        case 'GB':
                                            $dev->setCapacity(1000*1000*1000*$tmpbuf[1]);
                                            break;
                                        case 'TB':
                                            $dev->setCapacity(1000*1000*1000*1000*$tmpbuf[1]);
                                            break;
                                        case 'PB':
                                            $dev->setCapacity(1000*1000*1000*1000*1000*$tmpbuf[1]);
                                            break;
                                    }
                                }
                            }
                            if (defined('PSI_SHOW_DEVICES_SERIAL') && PSI_SHOW_DEVICES_SERIAL) {
                                if (isset($nlocate[1]) && isset($nsize[1])) {
                                    $dev->setSerial(trim(substr($buf, $nlocate[1], $nsize[1])));
                                }
                            }
                        }
                        $this->sys->setNvmeDevices($dev);
                    }
                }
                $count++;
            }
        }
    }
303433
def _mosaic_4d_to_nifti(dicom_input, output_file):
    
    # Get the sorted mosaics
    logger.info('Sorting dicom slices')
    sorted_mosaics = _get_sorted_mosaics(dicom_input)
    common.validate_orientation(sorted_mosaics)

    # Create mosaic block
    logger.info('Creating data block')
    full_block = _mosaic_get_full_block(sorted_mosaics)

    logger.info('Creating affine')
    # Create the nifti header info
    affine = _create_affine_siemens_mosaic(dicom_input)
    logger.info('Creating nifti')
    # Convert to nifti
    nii_image = nibabel.Nifti1Image(full_block, affine)
    common.set_tr_te(nii_image, float(sorted_mosaics[0].RepetitionTime), float(sorted_mosaics[0].EchoTime))
    logger.info('Saving nifti to disk')
    # Save to disk
    if output_file is not None:
        nii_image.to_filename(output_file)

    if _is_diffusion_imaging(dicom_input[0]):
        # Create the bval en bvec files
        logger.info('Creating bval en bvec')
        bval_file = None
        bvec_file = None
        if output_file is not None:
            base_path = os.path.dirname(output_file)
            base_name = os.path.splitext(os.path.splitext(os.path.basename(output_file))[0])[0]
            logger.info('Saving bval en bvec files')
            bval_file = '%s/%s.bval' % (base_path, base_name)
            bvec_file = '%s/%s.bvec' % (base_path, base_name)
        bvals = _create_bvals(sorted_mosaics, bval_file)
        bvecs = _create_bvecs(sorted_mosaics, bvec_file)

        return {'NII_FILE': output_file,
                'BVAL_FILE': bval_file,
                'BVEC_FILE': bvec_file,
                'NII': nii_image,
                'BVAL': bvals,
                'BVEC': bvecs}

    return {'NII_FILE': output_file,
            'NII': nii_image}
552321
def etm_supported(self):
        
        res = self._dll.JLINKARM_ETM_IsPresent()
        if (res == 1):
            return True

        # JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices.  This
        # fallback checks if ETM is present by checking the Cortex ROM table
        # for debugging information for ETM.
        info = ctypes.c_uint32(0)
        index = enums.JLinkROMTable.ETM
        res = self._dll.JLINKARM_GetDebugInfo(index, ctypes.byref(info))
        if (res == 1):
            return False

        return True
128336
def get_setup(Cnt = {}):
    ''''''
    
    # the name of the folder for NiftyPET tools
    Cnt['DIRTOOLS'] = DIRTOOLS

    # additional paramteres for compiling tools with cmake
    Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR

    # hardware mu-maps
    Cnt['HMULIST'] = hrdwr_mu
    
    # Microsoft Visual Studio Compiler version
    Cnt['MSVC_VRSN'] = MSVC_VRSN

    # GPU related setup
    Cnt = get_gpu_constants(Cnt)
    
    if 'PATHTOOLS'  in globals() and PATHTOOLS!='':     Cnt['PATHTOOLS'] = PATHTOOLS
    # image processing setup
    if 'RESPATH'    in globals() and RESPATH!='':       Cnt['RESPATH']  = RESPATH
    if 'REGPATH'    in globals() and REGPATH!='':       Cnt['REGPATH']  = REGPATH
    if 'DCM2NIIX'   in globals() and DCM2NIIX!='':      Cnt['DCM2NIIX'] = DCM2NIIX
    # hardware mu-maps
    if 'HMUDIR'     in globals() and HMUDIR!='':        Cnt['HMUDIR']   = HMUDIR
    if 'VINCIPATH'  in globals() and VINCIPATH!='':     Cnt['VINCIPATH'] = VINCIPATH

    Cnt['ENBLXNAT'] = ENBLXNAT
    Cnt['ENBLAGG'] = ENBLAGG
    Cnt['CMPL_DCM2NIIX'] = CMPL_DCM2NIIX

    return Cnt
555986
def create_nve_member(self, nexus_host, nve_int_num, vni, mcast_group):
        """"""

        # Do CLI [no] member vni %s mcast-group %s
        # beneath int nve1

        starttime = time.time()

        path = snipp.PATH_VNI_UPDATE % (nve_int_num, vni)
        body = snipp.BODY_VNI_UPDATE % (vni, vni, vni, mcast_group)
        self.send_edit_string(nexus_host, path, body)

        self.capture_and_print_timeshot(
            starttime, "create_nve",
            switch=nexus_host)
1000639
def get_darwin_arches(major, minor, machine):
    
    arches = []

    def _supports_arch(major, minor, arch):
        # Looking at the application support for macOS versions in the chart
        # provided by https://en.wikipedia.org/wiki/OS_X#Versions it appears
        # our timeline looks roughly like:
        #
        # 10.0 - Introduces ppc support.
        # 10.4 - Introduces ppc64, i386, and x86_64 support, however the ppc64
        #        and x86_64 support is CLI only, and cannot be used for GUI
        #        applications.
        # 10.5 - Extends ppc64 and x86_64 support to cover GUI applications.
        # 10.6 - Drops support for ppc64
        # 10.7 - Drops support for ppc
        #
        # Given that we do not know if we're installing a CLI or a GUI
        # application, we must be conservative and assume it might be a GUI
        # application and behave as if ppc64 and x86_64 support did not occur
        # until 10.5.
        #
        # Note: The above information is taken from the "Application support"
        #       column in the chart not the "Processor support" since I believe
        #       that we care about what instruction sets an application can use
        #       not which processors the OS supports.
        if arch == 'ppc':
            return (major, minor) <= (10, 5)
        if arch == 'ppc64':
            return (major, minor) == (10, 5)
        if arch == 'i386':
            return (major, minor) >= (10, 4)
        if arch == 'x86_64':
            return (major, minor) >= (10, 5)
        if arch in groups:
            for garch in groups[arch]:
                if _supports_arch(major, minor, garch):
                    return True
        return False

    groups = OrderedDict([
        ("fat", ("i386", "ppc")),
        ("intel", ("x86_64", "i386")),
        ("fat64", ("x86_64", "ppc64")),
        ("fat32", ("x86_64", "i386", "ppc")),
    ])

    if _supports_arch(major, minor, machine):
        arches.append(machine)

    for garch in groups:
        if machine in groups[garch] and _supports_arch(major, minor, garch):
            arches.append(garch)

    arches.append('universal')

    return arches
207339
def add_snmp(data, interfaces):
    
    snmp_interface = []
    if interfaces: # Not providing interfaces will enable SNMP on all NDIs
        interfaces = map(str, interfaces)
        for interface in data:
            interface_id = str(interface.get('interface_id'))
            for if_def in interface.get('interfaces', []):
                _interface_id = None
                if 'vlan_id' in if_def:
                    _interface_id = '{}.{}'.format(
                        interface_id, if_def['vlan_id'])
                else:
                    _interface_id = interface_id
                if _interface_id in interfaces and 'type' not in interface:
                    for node in if_def.get('nodes', []):
                        snmp_interface.append(
                            {'address': node.get('address'),
                             'nicid': _interface_id})
    return snmp_interface
586542
@Override
  @GwtIncompatible("MapMakerInternalMap")
  <K, V> MapMakerInternalMap<K, V> makeCustomMap() {
    return new MapMakerInternalMap<K, V>(this);
  }
1094657
public static void main(String[] args) throws IOException {
		ExampleHelpers.configureLogging();
		WorldMapProcessor.printDocumentation();

		int imageWidth = 8 * 360;
		double brightness = 1.0;
		WorldMapProcessor worldMapProcessor = new WorldMapProcessor(imageWidth,
				brightness);
		// worldMapProcessor.setGlobe(GlobeCoordinatesValue.GLOBE_MOON);
		// using the Moon or anything else but Earth might need some brightness
		// adjustment above, and possibly more frequent reporting below

		worldMapProcessor.addSite(null); // all data, no filter
		// Some other sites, ranked by the number of geolocated items they had
		// as of June 2015:
		worldMapProcessor.addSite("enwiki");
		worldMapProcessor.addSite("dewiki");
		worldMapProcessor.addSite("frwiki");
		worldMapProcessor.addSite("plwiki");
		worldMapProcessor.addSite("nlwiki");
		worldMapProcessor.addSite("ruwiki");
		worldMapProcessor.addSite("eswiki");
		worldMapProcessor.addSite("itwiki");
		worldMapProcessor.addSite("zhwiki");
		worldMapProcessor.addSite("ptwiki");
		// worldMapProcessor.addSite("ukwiki");
		// worldMapProcessor.addSite("svwiki");
		// worldMapProcessor.addSite("viwiki");
		// worldMapProcessor.addSite("srwiki");
		// worldMapProcessor.addSite("cawiki");
		// worldMapProcessor.addSite("shwiki");
		// worldMapProcessor.addSite("mswiki");
		// worldMapProcessor.addSite("rowiki");
		// worldMapProcessor.addSite("fawiki");
		// worldMapProcessor.addSite("jawiki");
		// worldMapProcessor.addSite("vowiki");
		// worldMapProcessor.addSite("warwiki");
		// worldMapProcessor.addSite("commonswiki");
		// worldMapProcessor.addSite("arwiki");

		ExampleHelpers.processEntitiesFromWikidataDump(worldMapProcessor);

		worldMapProcessor.writeFinalData();

	}
1045642
def _LoadNvmlLibrary():
    
    global nvmlLib

    if (nvmlLib is None):
        # lock to ensure only one caller loads the library
        libLoadLock.acquire()

        try:
            # ensure the library still isn't loaded
            if (nvmlLib is None):
                try:
                    if (sys.platform[:3] == "win"):
                        searchPaths = [
                            os.path.join(os.getenv("ProgramFiles", r"C:\Program Files"), r"NVIDIA Corporation\NVSMI\nvml.dll"),
                            os.path.join(os.getenv("WinDir", r"C:\Windows"), r"System32\nvml.dll"),
                        ]
                        nvmlPath = next((x for x in searchPaths if os.path.isfile(x)), None)
                        if (nvmlPath == None):
                            _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
                        else:
                            # cdecl calling convention
                            nvmlLib = CDLL(nvmlPath)
                    else:
                        # assume linux
                        nvmlLib = CDLL("libnvidia-ml.so.1")
                except OSError as ose:
                    _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
                if (nvmlLib == None):
                    _nvmlCheckReturn(NVML_ERROR_LIBRARY_NOT_FOUND)
        finally:
            # lock is always freed
            libLoadLock.release()
94199
def is_ansi_capable():
    ''' 
    '''
    BUILD_ANSI_AVAIL = 10586  # Win10 TH2
    CURRENT_VERS = sys.getwindowsversion()[:3]

    if CURRENT_VERS[2] > BUILD_ANSI_AVAIL:
        result = True
    else:
        result = False
    log.debug('version %s %s', CURRENT_VERS, result)
    return result