Print user's setup information
358088
def show_install(show_nvidia_smi:bool=False):
    ""

    import platform, fastai.version

    rep = []
    opt_mods = []

    rep.append(["=== Software ===", None])
    rep.append(["python", platform.python_version()])
    rep.append(["fastai", fastai.__version__])
    rep.append(["fastprogress", fastprogress.__version__])
    rep.append(["torch",  torch.__version__])

    # nvidia-smi
    cmd = "nvidia-smi"
    have_nvidia_smi = False
    try: result = subprocess.run(cmd.split(), shell=False, check=False, stdout=subprocess.PIPE)
    except: pass
    else:
        if result.returncode == 0 and result.stdout: have_nvidia_smi = True

    # XXX: if nvidia-smi is not available, another check could be:
    # /proc/driver/nvidia/version on most systems, since it's the
    # currently active version

    if have_nvidia_smi:
        smi = result.stdout.decode('utf-8')
        # matching: "Driver Version: 396.44"
        match = re.findall(r'Driver Version: +(\d+\.\d+)', smi)
        if match: rep.append(["nvidia driver", match[0]])

    available = "available" if torch.cuda.is_available() else "**Not available** "
    rep.append(["torch cuda", f"{torch.version.cuda} / is {available}"])

    # no point reporting on cudnn if cuda is not available, as it
    # seems to be enabled at times even on cpu-only setups
    if torch.cuda.is_available():
        enabled = "enabled" if torch.backends.cudnn.enabled else "**Not enabled** "
        rep.append(["torch cudnn", f"{torch.backends.cudnn.version()} / is {enabled}"])

    rep.append(["\n=== Hardware ===", None])

    # it's possible that torch might not see what nvidia-smi sees?
    gpu_total_mem = []
    nvidia_gpu_cnt = 0
    if have_nvidia_smi:
        try:
            cmd = "nvidia-smi --query-gpu=memory.total --format=csv,nounits,noheader"
            result = subprocess.run(cmd.split(), shell=False, check=False, stdout=subprocess.PIPE)
        except:
            print("have nvidia-smi, but failed to query it")
        else:
            if result.returncode == 0 and result.stdout:
                output = result.stdout.decode('utf-8')
                gpu_total_mem = [int(x) for x in output.strip().split('\n')]
                nvidia_gpu_cnt = len(gpu_total_mem)


    if nvidia_gpu_cnt: rep.append(["nvidia gpus", nvidia_gpu_cnt])

    torch_gpu_cnt = torch.cuda.device_count()
    if torch_gpu_cnt:
        rep.append(["torch devices", torch_gpu_cnt])
        # information for each gpu
        for i in range(torch_gpu_cnt):
            rep.append([f"  - gpu{i}", (f"{gpu_total_mem[i]}MB | " if gpu_total_mem else "") + torch.cuda.get_device_name(i)])
    else:
        if nvidia_gpu_cnt:
            rep.append([f"Have {nvidia_gpu_cnt} GPU(s), but torch can't use them (check nvidia driver)", None])
        else:
            rep.append([f"No GPUs available", None])


    rep.append(["\n=== Environment ===", None])

    rep.append(["platform", platform.platform()])

    if platform.system() == 'Linux':
        distro = try_import('distro')
        if distro:
            # full distro info
            rep.append(["distro", ' '.join(distro.linux_distribution())])
        else:
            opt_mods.append('distro');
            # partial distro info
            rep.append(["distro", platform.uname().version])

    rep.append(["conda env", get_env('CONDA_DEFAULT_ENV')])
    rep.append(["python", sys.executable])
    rep.append(["sys.path", "\n".join(sys.path)])

    print("\n\n```text")

    keylen = max([len(e[0]) for e in rep if e[1] is not None])
    for e in rep:
        print(f"{e[0]:{keylen}}", (f": {e[1]}" if e[1] is not None else ""))

    if have_nvidia_smi:
        if show_nvidia_smi: print(f"\n{smi}")
    else:
        if torch_gpu_cnt: print("no nvidia-smi is found")
        else: print("no supported gpus found on this system")

    print("```\n")

    print("Please make sure to include opening/closing ``` when you paste into forums/github to make the reports appear formatted as code sections.\n")

    if opt_mods:
        print("Optional package(s) to enhance the diagnostics can be installed with:")
        print(f"pip install {' '.join(opt_mods)}")
        print("Once installed, re-run this utility to get the additional information")
540129
def print_details(self):
		""""""
		print("Title:", self.title)
		print("Category:", self.category)
		print("Page: ", self.page)
		print("Size: ", self.size)
		print("Files: ", self.files)
		print("Age: ", self.age)
		print("Seeds:", self.seeders)
		print("Leechers: ", self.leechers)
		print("Magnet: ", self.magnet)
		print("Download: ", self.download)
		print("Verified:", self.isVerified)
871505
def main(output):
    

    client = SubscriptionClient(Session().get_credentials())
    subs = [sub.serialize(True) for sub in client.subscriptions.list()]
    results = []
    for sub in subs:
        sub_info = {
            'subscription_id': sub['subscriptionId'],
            'name': sub['displayName']
        }
        results.append(sub_info)

    print(
        yaml.safe_dump(
            {'subscriptions': results},
            default_flow_style=False),
        file=output)
617641
def print_entitlements(opts, data, page_info=None, show_list_info=True):
    """"""
    if utils.maybe_print_as_json(opts, data, page_info):
        return

    headers = ["Name", "Token", "Created / Updated", "Identifier"]

    rows = []
    for entitlement in sorted(data, key=itemgetter("name")):
        rows.append(
            [
                click.style(
                    "%(name)s (%(type)s)"
                    % {
                        "name": click.style(entitlement["name"], fg="cyan"),
                        "type": "user" if entitlement["user"] else "token",
                    }
                ),
                click.style(entitlement["token"], fg="yellow"),
                click.style(entitlement["updated_at"], fg="blue"),
                click.style(entitlement["slug_perm"], fg="green"),
            ]
        )

    if data:
        click.echo()
        utils.pretty_print_table(headers, rows)

    if not show_list_info:
        return

    click.echo()

    num_results = len(data)
    list_suffix = "entitlement%s" % ("s" if num_results != 1 else "")
    utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
631646
def print_config():  # pragma: no cover
    """"""
    description = """\
        Print the deployment settings for a Pyramid application.  Example:
        'psettings deployment.ini'
    """
    parser = argparse.ArgumentParser(
        description=textwrap.dedent(description)
    )
    parser.add_argument(
        'config_uri', type=str, help='an integer for the accumulator'
    )
    parser.add_argument(
        '-k', '--key',
        dest='key',
        metavar='PREFIX',
        type=str,
        action='store',
        help=(
            "Tells script to print only specified"
            " config tree provided by dotted name"
        )
    )
    args = parser.parse_args(sys.argv[1:])

    config_uri = args.config_uri
    env = bootstrap(config_uri)
    config, closer = env['registry']['config'], env['closer']

    try:
        print(printer(slice_config(config, args.key)))
    except KeyError:
        print(
            'Sorry, but the key path {0}, does not exists in Your config!'
            .format(args.key)
        )
    finally:
        closer()
335589
def add_basic_info(self, run_id, timestamp):
    """"""
    datetime = time.strftime('%A %b %d, %Y %H:%M:%S', time.localtime(timestamp))
    user = getpass.getuser()
    machine = socket.gethostname()
    buildroot = get_buildroot()
    # TODO: Get rid of the redundant 'path' key once everyone is off it.
    self.add_infos(('id', run_id), ('timestamp', timestamp), ('datetime', datetime),
                   ('user', user), ('machine', machine), ('path', buildroot),
                   ('buildroot', buildroot), ('version', version.VERSION))
815443
def info():
    """"""
    rc = texinfo()
    print('Running Texinfo files through makeinfo...')
    builddir = os.path.join(BUILDDIR, 'texinfo')
    subprocess.call(['make', '-C', builddir, 'info'])
    print('makeinfo finished; the Info files are in {}.'.format(builddir))
76719
def print_ec2_info(region,
                   instance_id,
                   access_key_id,
                   secret_access_key,
                   username):
    
    data = get_ec2_info(instance_id=instance_id,
                        region=region,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        username=username)

    log_green("region: %s" % data['region'])
    log_green("Instance_type: %s" % data['instance_type'])
    log_green("Instance state: %s" % data['state'])
    log_green("Public dns: %s" % data['public_dns_name'])
    log_green("Ip address: %s" % data['ip_address'])
    log_green("volume: %s" % data['volume'])
    log_green("user: %s" % data['username'])
    log_green("ssh -i %s %s@%s" % (env.key_filename,
                                   username,
                                   data['ip_address']))
979222
def init_user():
    
    if not os.path.exists(USER_CONFIG_DIR):
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Create user directory {0}".format(USER_CONFIG_DIR))
        os.makedirs(USER_CONFIG_DIR)
    for subdir in ["plugins", "reports", "templates/plugin", "templates/email", "templates/web"]:
        user_conf_subdir = os.path.join(USER_CONFIG_DIR, subdir)
        if not os.path.exists(user_conf_subdir):
            if rapport.config.get_int("rapport", "verbosity") >= 1:
                print("Create user directory {0}".format(user_conf_subdir))
            os.makedirs(user_conf_subdir)
        if subdir == "reports" and not (os.stat(user_conf_subdir).st_mode & 0o777) == 0o700:
            if rapport.config.get_int("rapport", "verbosity") >= 1:
                print("Set secure directory permissions for {0}".format(user_conf_subdir))
            os.chmod(user_conf_subdir, 0o700)
    if not os.path.exists(USER_CONFIG_FILE):
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Create user configuration {0}".format(USER_CONFIG_FILE))
        default_config = os.path.abspath(os.path.join(os.path.splitext(__file__)[0], "rapport.conf"))
        shutil.copyfile(default_config, USER_CONFIG_FILE)

    if not (os.stat(USER_CONFIG_FILE).st_mode & 0o777) == 0o600:
        if rapport.config.get_int("rapport", "verbosity") >= 1:
            print("Set secure file permissions for {0}".format(USER_CONFIG_FILE))
        os.chmod(USER_CONFIG_FILE, 0o600)
172053
def print_info(self):
        ""
        "           pts/34       2013-06-12 15:04             26396 id=s/34  term=0 exit=0"
#        if self.ut_type not in [6,7]:
#            return
        print("%-10s %-12s %15s %15s %-8s" % (
                    str_from_c(self.ut_user),
                    str_from_c(self.ut_line),
                    time.strftime("%Y-%m-%d %H:%M", time.gmtime(self.ut_tv.tv_sec)),
                    self.ut_pid,
                    str_from_c(self.ut_host) and "(%s)" % str_from_c(self.ut_host) or str_from_c(self.ut_id) and "id=%s" % str_from_c(self.ut_id) or ""))
447838
def info(name):
    '''
    
    '''
    try:
        data = pwd.getpwnam(name)
        return {'name': data.pw_name,
                'passwd': data.pw_passwd,
                'account_created': get_account_created(name),
                'login_failed_count': get_login_failed_count(name),
                'login_failed_last': get_login_failed_last(name),
                'lstchg': get_last_change(name),
                'max': get_maxdays(name),
                'expire': get_expire(name),
                'change': get_change(name),
                'min': 'Unavailable',
                'warn': 'Unavailable',
                'inact': 'Unavailable'}

    except KeyError:
        log.debug('User not found: %s', name)
        return {'name': '',
                'passwd': '',
                'account_created': '',
                'login_failed_count': '',
                'login_failed_last': '',
                'lstchg': '',
                'max': '',
                'expire': '',
                'change': '',
                'min': '',
                'warn': '',
                'inact': ''}
1036115
def get_print_setup(self, print_data):
        """"""

        psd = wx.PageSetupDialogData(print_data)
        # psd.EnablePrinter(False)
        psd.CalculatePaperSizeFromId()
        dlg = wx.PageSetupDialog(self.main_window, psd)
        dlg.ShowModal()

        # this makes a copy of the wx.PrintData instead of just saving
        # a reference to the one inside the PrintDialogData that will
        # be destroyed when the dialog is destroyed
        data = dlg.GetPageSetupData()
        new_print_data = wx.PrintData(data.GetPrintData())
        new_print_data.PaperId = data.PaperId
        new_print_data.PaperSize = data.PaperSize

        dlg.Destroy()

        return new_print_data
1116378
def do_account_info(self):
        """"""
        s, metadata = self.n.getRegisterUserInfo()
        pprint.PrettyPrinter(indent=2).pprint(metadata)
308178
def Setup(self, event=None):
        

        if hasattr(self, 'printerData'):
            data = wx.PageSetupDialogData()
            data.SetPrintData(self.printerData)
        else:
            data = wx.PageSetupDialogData()
        data.SetMarginTopLeft( (15, 15) )
        data.SetMarginBottomRight( (15, 15) )

        dlg = wx.PageSetupDialog(None, data)

        if dlg.ShowModal() == wx.ID_OK:
            data = dlg.GetPageSetupData()
            tl = data.GetMarginTopLeft()
            br = data.GetMarginBottomRight()
        self.printerData = wx.PrintData(data.GetPrintData())
        dlg.Destroy()
695584
def _user_input_properties():
    
    global GUEST_USERID
    global GUEST_PROFILE
    global GUEST_VCPUS
    global GUEST_MEMORY
    global GUEST_ROOT_DISK_SIZE
    global DISK_POOL
    global IMAGE_PATH
    global IMAGE_OS_VERSION
    global GUEST_IP_ADDR
    global GATEWAY
    global CIDR
    global VSWITCH_NAME
    global NETWORK_INFO
    global DISKS_LIST
    
    pythonVersion = sys.version[0]
    print("Your python interpreter's version is %s." % pythonVersion)

    if pythonVersion == '2':
        print("Input properties with string type in ''.")
    else:
        print("Input properties without ''.")

    print("Please input guest properties:")

    GUEST_USERID = input("guest_userid = ")
    GUEST_PROFILE = input("guest_profile = ")
    GUEST_VCPUS = int(input("guest_vcpus = "))
    GUEST_MEMORY = int(input("guest_memory (in Megabytes) = "))
    GUEST_ROOT_DISK_SIZE = int(input("guest_root_disk_size (in Gigabytes) = "))
    GUEST_POOL = input("disk_pool = ")
    print("\n")

    IMAGE_PATH = input("image_path = ")
    IMAGE_OS_VERSION = input("image_os_version = ")
    print("\n")

    GUEST_IP_ADDR = input("guest_ip_addr = ")
    GATEWAY = input("gateway = ")
    CIDR = input("cidr = ")
    VSWITCH_NAME = input("vswitch_name = ")

    NETWORK_INFO = [{'ip_addr': GUEST_IP_ADDR, 'gateway_addr': GATEWAY, 'cidr': CIDR}]
    DISKS_LIST = [{'size': '%dg' % GUEST_ROOT_DISK_SIZE, 
                   'is_boot_disk': True, 'disk_pool': GUEST_POOL}]
1163446
def print_user(self, user):
    '''
    ''' 
    status = "active"
    token = user.token

    if token in ['finished', 'revoked']:
        status = token

    if token is None:
        token = ''
  
    subid = "%s\t%s[%s]" %(user.id, token, status)
    print(subid)
    return subid
130150
def generate_user_data(lxd_params, options)
      logger.info("Calling <#{__method__.to_s}>")

      lxd_params[:config] = {}

      if options[:'no-maas']
        lxd_params[:config][:"user.user-data"] = {}
      else
        sshkeys = maas.get_sshkeys
        pkg_repos = maas.get_package_repos

        lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] }

        sshkeys.each do |key|
          lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key'])
        end

        pkg_repos.each do |repo|
          if repo['name'] == 'main_archive'
            lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url']
          end
        end

        lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias]
        lxd_params[:config][:"user.user-data"]['maas'] = true
      end

      if options[:'maas-on-lxc']
        lxd_params[:config][:"security.privileged"] = "true"
      end

      if options[:'lxd-in-lxd']
        lxd_params[:config][:"security.privileged"] = "true"
        lxd_params[:config][:"security.nesting"] = "true"
      end

      if options[:'kvm-in-lxd']
        lxd_params[:config][:"security.nesting"] = "true"
        lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock"
      end

      lxd_params[:config][:"user.user-data"]['gogetit'] = true

      # To disable to update apt database on first boot
      # so chef client can keep doing its job.
      lxd_params[:config][:'user.user-data']['package_update'] = false
      lxd_params[:config][:'user.user-data']['package_upgrade'] = false

      lxd_params[:config][:'user.user-data'] = generate_cloud_init_config(
        options,
        config,
        lxd_params[:config][:'user.user-data']
      )

      lxd_params[:config][:"user.user-data"] = \
        "#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1]

      return lxd_params
    end