Collect information about the system and installation.
183636
def get_system_spec() -> Dict[str, str]:
    
    import pkg_resources
    import platform

    if sys.platform == 'darwin':
        system_info = 'macOS {} {}'.format(
            platform.mac_ver()[0],
            platform.architecture()[0],
        )
    else:
        system_info = '{} {} {}'.format(
            platform.system(),
            '_'.join(part for part in platform.architecture() if part),
            platform.release(),
        )

    try:
        version = pkg_resources.require(raiden.__name__)[0].version
    except (pkg_resources.VersionConflict, pkg_resources.DistributionNotFound):
        raise RuntimeError(
            'Cannot detect Raiden version. Did you do python setup.py?  '
            'Refer to https://raiden-network.readthedocs.io/en/latest/'
            'overview_and_guide.html#for-developers',
        )

    system_spec = {
        'raiden': version,
        'python_implementation': platform.python_implementation(),
        'python_version': platform.python_version(),
        'system': system_info,
        'architecture': platform.machine(),
        'distribution': 'bundled' if getattr(sys, 'frozen', False) else 'source',
    }
    return system_spec
743173
def do_info(self, subcmd, opts, *args):
        
        print "'svn %s' opts: %s" % (subcmd, opts)
        print "'svn %s' args: %s" % (subcmd, args)
632419
def prepare_files(self, finder, force_root_egg_info=False, bundle=False):
        """"""
        unnamed = list(self.unnamed_requirements)
        reqs = list(self.requirements.values())
        while reqs or unnamed:
            if unnamed:
                req_to_install = unnamed.pop(0)
            else:
                req_to_install = reqs.pop(0)
            req_version = None
            install = True
            best_installed = False
            if not self.ignore_installed and not req_to_install.editable:
                req_to_install.check_if_exists()
                if req_to_install.satisfied_by:
                    if self.upgrade:
                        if not self.force_reinstall:
                            try:
                                url, req_version = finder.find_requirement(
                                    req_to_install, self.upgrade)
                            except BestVersionAlreadyInstalled:
                                best_installed = True
                                install = False
                            else:
                                # Avoid the need to call find_requirement again
                                req_to_install.url = url.url

                        if not best_installed:
                            req_to_install.conflicts_with = req_to_install.satisfied_by
                            req_to_install.satisfied_by = None
                    else:
                        install = False
                if req_to_install.satisfied_by:
                    if best_installed:
                        logger.notify('Requirement already up-to-date: %s'
                                      % req_to_install)
                    else:
                        logger.notify('Requirement already satisfied '
                                      '(use --upgrade to upgrade): %s'
                                      % req_to_install)
            if req_to_install.editable:
                logger.notify('Obtaining %s' % req_to_install)
            elif install:
                if req_to_install.url and req_to_install.url.lower().startswith('file:'):
                    logger.notify('Unpacking %s' % display_path(url_to_path(req_to_install.url)))
                else:
                    logger.notify('Downloading/unpacking %s' % req_to_install)
            logger.indent += 2
            try:
                is_bundle = False
                if req_to_install.editable:
                    if req_to_install.source_dir is None:
                        location = req_to_install.build_location(self.src_dir)
                        req_to_install.source_dir = location
                    else:
                        location = req_to_install.source_dir
                    if not os.path.exists(self.build_dir):
                        _make_build_dir(self.build_dir)
                    req_to_install.update_editable(not self.is_download)
                    if self.is_download:
                        req_to_install.run_egg_info()
                        req_to_install.archive(self.download_dir)
                    else:
                        req_to_install.run_egg_info()
                elif install:
                    ##@@ if filesystem packages are not marked
                    ##editable in a req, a non deterministic error
                    ##occurs when the script attempts to unpack the
                    ##build directory

                    location = req_to_install.build_location(self.build_dir, not self.is_download)
                    ## FIXME: is the existance of the checkout good enough to use it?  I don't think so.
                    unpack = True
                    if not os.path.exists(os.path.join(location, 'setup.py')):
                        ## FIXME: this won't upgrade when there's an existing package unpacked in `location`
                        if req_to_install.url is None:
                            url, req_version = finder.find_requirement(req_to_install, upgrade=self.upgrade)
                        else:
                            ## FIXME: should req_to_install.url already be a link?
                            url = Link(req_to_install.url)
                            assert url
                        if url:
                            try:
                                self.unpack_url(req_to_install, req_version, url, location, self.is_download)
                            except HTTPError:
                                e = sys.exc_info()[1]
                                logger.fatal('Could not install requirement %s because of error %s'
                                             % (req_to_install, e))
                                raise InstallationError(
                                    'Could not install requirement %s because of HTTP error %s for URL %s'
                                    % (req_to_install, e, url))
                        else:
                            unpack = False
                    if unpack:
                        is_bundle = req_to_install.is_bundle
                        url = None
                        if is_bundle:
                            req_to_install.move_bundle_files(self.build_dir, self.src_dir)
                            for subreq in req_to_install.bundle_requirements():
                                reqs.append(subreq)
                                self.add_requirement(subreq)
                        elif self.is_download:
                            req_to_install.source_dir = location
                            if url and url.scheme in vcs.all_schemes:
                                req_to_install.run_egg_info()
                                req_to_install.archive(self.download_dir)
                        else:
                            req_to_install.source_dir = location
                            req_to_install.run_egg_info()
                            if force_root_egg_info:
                                # We need to run this to make sure that the .egg-info/
                                # directory is created for packing in the bundle
                                req_to_install.run_egg_info(force_root_egg_info=True)
                            req_to_install.assert_source_matches_version()
                            #@@ sketchy way of identifying packages not grabbed from an index
                            if bundle and req_to_install.url:
                                self.copy_to_build_dir(req_to_install)
                                install = False
                        # req_to_install.req is only avail after unpack for URL pkgs
                        # repeat check_if_exists to uninstall-on-upgrade (#14)
                        req_to_install.check_if_exists()
                        if req_to_install.satisfied_by:
                            if self.upgrade or self.ignore_installed:
                                req_to_install.conflicts_with = req_to_install.satisfied_by
                                req_to_install.satisfied_by = None
                            else:
                                install = False
                if not is_bundle and not self.is_download:
                    ## FIXME: shouldn't be globally added:
                    finder.add_dependency_links(req_to_install.dependency_links)
                    if (req_to_install.extras):
                        logger.notify("Installing extra requirements: %r" % ','.join(req_to_install.extras))
                    if not self.ignore_dependencies:
                        for req in req_to_install.requirements(req_to_install.extras):
                            try:
                                name = pkg_resources.Requirement.parse(req).project_name
                            except ValueError:
                                e = sys.exc_info()[1]
                                ## FIXME: proper warning
                                logger.error('Invalid requirement: %r (%s) in requirement %s' % (req, e, req_to_install))
                                continue
                            if self.has_requirement(name):
                                ## FIXME: check for conflict
                                continue
                            subreq = InstallRequirement(req, req_to_install)
                            reqs.append(subreq)
                            self.add_requirement(subreq)
                    if req_to_install.name not in self.requirements:
                        self.requirements[req_to_install.name] = req_to_install
                else:
                    self.reqs_to_cleanup.append(req_to_install)
                if install:
                    self.successfully_downloaded.append(req_to_install)
                    if bundle and (req_to_install.url and req_to_install.url.startswith('file:///')):
                        self.copy_to_build_dir(req_to_install)
            finally:
                logger.indent -= 2
734605
def list_installed():
    '''
    
    '''
    cmd = 'Get-WindowsFeature ' \
          '-ErrorAction SilentlyContinue ' \
          '-WarningAction SilentlyContinue ' \
          '| Select DisplayName,Name,Installed'
    features = _pshell_json(cmd)

    ret = {}
    for entry in features:
        if entry['Installed']:
            ret[entry['Name']] = entry['DisplayName']

    return ret
203330
def system_information():
    '''
    
    '''
    def system_version():
        '''
        Return host system version.
        '''
        lin_ver = linux_distribution()
        mac_ver = platform.mac_ver()
        win_ver = platform.win32_ver()

        if lin_ver[0]:
            return ' '.join(lin_ver)
        elif mac_ver[0]:
            if isinstance(mac_ver[1], (tuple, list)) and ''.join(mac_ver[1]):
                return ' '.join([mac_ver[0], '.'.join(mac_ver[1]), mac_ver[2]])
            else:
                return ' '.join([mac_ver[0], mac_ver[2]])
        elif win_ver[0]:
            return ' '.join(win_ver)
        else:
            return ''

    if platform.win32_ver()[0]:
        # Get the version and release info based on the Windows Operating
        # System Product Name. As long as Microsoft maintains a similar format
        # this should be future proof
        import win32api  # pylint: disable=3rd-party-module-not-gated
        import win32con  # pylint: disable=3rd-party-module-not-gated

        # Get the product name from the registry
        hkey = win32con.HKEY_LOCAL_MACHINE
        key = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion'
        value_name = 'ProductName'
        reg_handle = win32api.RegOpenKey(hkey, key)

        # Returns a tuple of (product_name, value_type)
        product_name, _ = win32api.RegQueryValueEx(reg_handle, value_name)

        version = 'Unknown'
        release = ''
        if 'Server' in product_name:
            for item in product_name.split(' '):
                # If it's all digits, then it's version
                if re.match(r'\d+', item):
                    version = item
                # If it starts with R and then numbers, it's the release
                # ie: R2
                if re.match(r'^R\d+$', item):
                    release = item
            release = '{0}Server{1}'.format(version, release)
        else:
            for item in product_name.split(' '):
                # If it's a number, decimal number, Thin or Vista, then it's the
                # version
                if re.match(r'^(\d+(\.\d+)?)|Thin|Vista$', item):
                    version = item
            release = version

        _, ver, sp, extra = platform.win32_ver()
        version = ' '.join([release, ver, sp, extra])
    else:
        version = system_version()
        release = platform.release()

    system = [
        ('system', platform.system()),
        ('dist', ' '.join(linux_distribution(full_distribution_name=False))),
        ('release', release),
        ('machine', platform.machine()),
        ('version', version),
        ('locale', __salt_system_encoding__),
    ]

    for name, attr in system:
        yield name, attr
        continue
650232
def _prime_install_map(self):
        """"""
        url = "{}/app/installations".format(self.api_url)
        headers = self._get_app_auth_headers()
        LOGGER.debug("Fetching installations for GitHub app")

        response = requests.get(url, headers=headers)
        response.raise_for_status()

        data = response.json()

        for install in data:
            install_id = install.get("id")
            token = self._get_installation_key(project=None, install_id=install_id)
            headers = {
                "Accept": PREVIEW_JSON_ACCEPT,
                "Authorization": "token {}".format(token),
            }

            url = "{}/installation/repositories?per_page=100".format(self.api_url)
            while url:
                LOGGER.debug("Fetching repos for installation %s", install_id)
                response = requests.get(url, headers=headers)
                response.raise_for_status()
                repos = response.json()

                # Store all projects in the installation map
                for repo in repos.get("repositories", []):
                    # TODO (fschmidt): Store the installation's
                    # permissions (could come in handy for later features)
                    project_name = repo["full_name"]
                    self.installation_map[project_name] = {
                        "installation_id": install_id,
                        "default_branch": repo["default_branch"],
                    }

                # Check if we need to do further page calls
                url = response.links.get("next", {}).get("url")
548842
def installation(self):
        """"""
        self.locations = []

        url = ("https://tccna.honeywell.com/WebAPI/emea/api/v1/location"
               "/installationInfo?userId=%s"
               "&includeTemperatureControlSystems=True"
               % self.account_info['userId'])

        response = requests.get(url, headers=self._headers())
        response.raise_for_status()

        self.installation_info = response.json()
        self.system_id = (self.installation_info[0]['gateways'][0]
                          ['temperatureControlSystems'][0]['systemId'])

        for loc_data in self.installation_info:
            self.locations.append(Location(self, loc_data))

        return self.installation_info
559173
def get_info(self):
        '''
        
        '''
        if not self.info:
            ci = win32pdh.GetCounterInfo(self.handle, 0)
            self.info = {
                'type': ci[0],
                'version': ci[1],
                'scale': ci[2],
                'default_scale': ci[3],
                'user_data': ci[4],
                'query_user_data': ci[5],
                'full_path': ci[6],
                'machine_name': ci[7][0],
                'object_name': ci[7][1],
                'instance_name': ci[7][2],
                'parent_instance': ci[7][3],
                'instance_index': ci[7][4],
                'counter_name': ci[7][5],
                'explain_text': ci[8]
            }
        return self.info
254145
protected function processInstall()
    {
        $result = $this->install->process($this->getSubmitted());
        $this->redirect($result['redirect'], $result['message'], $result['severity']);
    }
445588
def gather_details():
    """"""
    try:
        data = {
            'kernel': platform.uname(),
            'distribution': platform.linux_distribution(),
            'libc': platform.libc_ver(),
            'arch': platform.machine(),
            'python_version': platform.python_version(),
            'os_name': platform.system(),
            'static_hostname': platform.node(),
            'cpu': platform.processor(),
            'fqdn': socket.getfqdn(),
        }
    except AttributeError:
        return {}

    return data
1119937
def save_device_info(self):
        """"""
        if self._workdir is not None:
            devices = []
            for addr in self._devices:
                device = self._devices.get(addr)
                if not device.address.is_x10:
                    aldb = {}
                    for mem in device.aldb:
                        rec = device.aldb[mem]
                        if rec:
                            aldbRec = {'memory': mem,
                                       'control_flags': rec.control_flags.byte,
                                       'group': rec.group,
                                       'address': rec.address.id,
                                       'data1': rec.data1,
                                       'data2': rec.data2,
                                       'data3': rec.data3}
                            aldb[mem] = aldbRec
                    deviceInfo = {'address': device.address.id,
                                  'cat': device.cat,
                                  'subcat': device.subcat,
                                  'product_key': device.product_key,
                                  'aldb_status': device.aldb.status.value,
                                  'aldb': aldb}
                    devices.append(deviceInfo)
            asyncio.ensure_future(self._write_saved_device_info(devices),
                                  loop=self._loop)
641693
public function onInstallCommandCompletedOutputReport()
    {
        $report = new InstallReport($this->eventDataCollector, $this->dataCollectors);
        $report->generate($this->logger);
    }
1053683
def get(self):
        """"""
        new = self.manager.get(self)
        if new:
            self._add_details(new._info)
827431
def system_info(self):
        """"""
        res = self.client.service.SystemInfo()
        res = {ustr(x[0]): x[1] for x in res[0]}

        to_str = lambda arr: '.'.join([ustr(x) for x in arr[0]])
        res['OSVersion'] = to_str(res['OSVersion'])
        res['RuntimeVersion'] = to_str(res['RuntimeVersion'])
        res['Version'] = to_str(res['Version'])

        res['Name'] = ustr(res['Name'])
        res['Server'] = ustr(res['Server'])
        res['LocalNameCheck'] = ustr(res['LocalNameCheck'])
        res['UserHostAddress'] = ustr(res['UserHostAddress'])

        return res
58244
def store(self, installed_stuff, metadata, interpreter, options):
        """"""
        new_content = {
            'timestamp': int(time.mktime(time.localtime())),
            'installed': installed_stuff,
            'metadata': metadata,
            'interpreter': interpreter,
            'options': options
        }
        logger.debug("Storing installed=%s metadata=%s interpreter=%s options=%s",
                     installed_stuff, metadata, interpreter, options)
        with filelock(self.lockpath):
            self._write_cache([json.dumps(new_content)], append=True)
1203758
def get_system_info():
    '''
    
    '''
    def byte_calc(val):
        val = float(val)
        if val < 2**10:
            return '{0:.3f}B'.format(val)
        elif val < 2**20:
            return '{0:.3f}KB'.format(val / 2**10)
        elif val < 2**30:
            return '{0:.3f}MB'.format(val / 2**20)
        elif val < 2**40:
            return '{0:.3f}GB'.format(val / 2**30)
        else:
            return '{0:.3f}TB'.format(val / 2**40)

    # Lookup dicts for Win32_OperatingSystem
    os_type = {1: 'Work Station',
               2: 'Domain Controller',
               3: 'Server'}

    # lookup dicts for Win32_ComputerSystem
    domain_role = {0: 'Standalone Workstation',
                   1: 'Member Workstation',
                   2: 'Standalone Server',
                   3: 'Member Server',
                   4: 'Backup Domain Controller',
                   5: 'Primary Domain Controller'}
    warning_states = {1: 'Other',
                      2: 'Unknown',
                      3: 'Safe',
                      4: 'Warning',
                      5: 'Critical',
                      6: 'Non-recoverable'}
    pc_system_types = {0: 'Unspecified',
                       1: 'Desktop',
                       2: 'Mobile',
                       3: 'Workstation',
                       4: 'Enterprise Server',
                       5: 'SOHO Server',
                       6: 'Appliance PC',
                       7: 'Performance Server',
                       8: 'Maximum'}

    # Connect to WMI
    with salt.utils.winapi.Com():
        conn = wmi.WMI()

        system = conn.Win32_OperatingSystem()[0]
        ret = {'name': get_computer_name(),
               'description': system.Description,
               'install_date': system.InstallDate,
               'last_boot': system.LastBootUpTime,
               'os_manufacturer': system.Manufacturer,
               'os_name': system.Caption,
               'users': system.NumberOfUsers,
               'organization': system.Organization,
               'os_architecture': system.OSArchitecture,
               'primary': system.Primary,
               'os_type': os_type[system.ProductType],
               'registered_user': system.RegisteredUser,
               'system_directory': system.SystemDirectory,
               'system_drive': system.SystemDrive,
               'os_version': system.Version,
               'windows_directory': system.WindowsDirectory}

        system = conn.Win32_ComputerSystem()[0]
        # Get pc_system_type depending on Windows version
        if platform.release() in ['Vista', '7', '8']:
            # Types for Vista, 7, and 8
            pc_system_type = pc_system_types[system.PCSystemType]
        else:
            # New types were added with 8.1 and newer
            pc_system_types.update({8: 'Slate', 9: 'Maximum'})
            pc_system_type = pc_system_types[system.PCSystemType]
        ret.update({
            'bootup_state': system.BootupState,
            'caption': system.Caption,
            'chassis_bootup_state': warning_states[system.ChassisBootupState],
            'chassis_sku_number': system.ChassisSKUNumber,
            'dns_hostname': system.DNSHostname,
            'domain': system.Domain,
            'domain_role': domain_role[system.DomainRole],
            'hardware_manufacturer': system.Manufacturer,
            'hardware_model': system.Model,
            'network_server_mode_enabled': system.NetworkServerModeEnabled,
            'part_of_domain': system.PartOfDomain,
            'pc_system_type': pc_system_type,
            'power_state': system.PowerState,
            'status': system.Status,
            'system_type': system.SystemType,
            'total_physical_memory': byte_calc(system.TotalPhysicalMemory),
            'total_physical_memory_raw': system.TotalPhysicalMemory,
            'thermal_state': warning_states[system.ThermalState],
            'workgroup': system.Workgroup
        })
        # Get processor information
        processors = conn.Win32_Processor()
        ret['processors'] = 0
        ret['processors_logical'] = 0
        ret['processor_cores'] = 0
        ret['processor_cores_enabled'] = 0
        ret['processor_manufacturer'] = processors[0].Manufacturer
        ret['processor_max_clock_speed'] = six.text_type(processors[0].MaxClockSpeed) + 'MHz'
        for processor in processors:
            ret['processors'] += 1
            ret['processors_logical'] += processor.NumberOfLogicalProcessors
            ret['processor_cores'] += processor.NumberOfCores
            ret['processor_cores_enabled'] += processor.NumberOfEnabledCore

        bios = conn.Win32_BIOS()[0]
        ret.update({'hardware_serial': bios.SerialNumber,
                    'bios_manufacturer': bios.Manufacturer,
                    'bios_version': bios.Version,
                    'bios_details': bios.BIOSVersion,
                    'bios_caption': bios.Caption,
                    'bios_description': bios.Description})
        ret['install_date'] = _convert_date_time_string(ret['install_date'])
        ret['last_boot'] = _convert_date_time_string(ret['last_boot'])
    return ret
925776
def _save_installed(self):
        """"""
        import json
        from utility import json_serial, get_json
        #This is a little tricky because the data file doesn't just have a list
        #of installed servers. It also manages the script's database that tracks
        #the user's interactions with it.
        fulldata = get_json(self.instpath, {})
        fulldata["installed"] = self.installed
        with open(self.instpath, 'w') as f:
            json.dump(fulldata, f, default=json_serial)