예제 #1
0
파일: help.py 프로젝트: TimexStudio/pipenv
def _implementation():
    """Return a dict with the Python implementation and version.

    Provide both the name and the version of the Python implementation
    currently running. For example, on CPython 2.7.5 it will return
    {'name': 'CPython', 'version': '2.7.5'}.

    This function works best on CPython and PyPy: in particular, it probably
    doesn't work for Jython or IronPython. Future investigation should be done
    to work out the correct shape of the code for those platforms.
    """
    implementation = platform.python_implementation()

    if implementation == 'CPython':
        implementation_version = platform.python_version()
    elif implementation == 'PyPy':
        implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
                                               sys.pypy_version_info.minor,
                                               sys.pypy_version_info.micro)
        if sys.pypy_version_info.releaselevel != 'final':
            implementation_version = ''.join([
                implementation_version, sys.pypy_version_info.releaselevel
            ])
    elif implementation == 'Jython':
        implementation_version = platform.python_version()  # Complete Guess
    elif implementation == 'IronPython':
        implementation_version = platform.python_version()  # Complete Guess
    else:
        implementation_version = 'Unknown'

    return {'name': implementation, 'version': implementation_version}
예제 #2
0
def Main(Options=None):
    ContentZipFile, DistFile = None, None
    ReturnCode = 0

    try:
        DataBase = GlobalData.gDB
        WorkspaceDir = GlobalData.gWORKSPACE
        if not Options.DistFiles:
            Logger.Error("TestInstallPkg", TE.OPTION_MISSING, ExtraData=ST.ERR_SPECIFY_PACKAGE)

        DistPkgList = []
        for DistFile in Options.DistFiles:
            DistPkg, ContentZipFile, __, DistFile = UnZipDp(WorkspaceDir, DistFile)
            DistPkgList.append(DistPkg)

        #
        # check dependency
        #
        Dep = DependencyRules(DataBase)
        Result = True
        DpObj = None
        try:
            Result, DpObj = Dep.CheckTestInstallPdDepexSatisfied(DistPkgList)
        except:
            Result = False

        if Result:
            Logger.Quiet(ST.MSG_TEST_INSTALL_PASS)
        else:
            Logger.Quiet(ST.MSG_TEST_INSTALL_FAIL)

    except TE.FatalError as XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())

    except Exception as x:
        ReturnCode = TE.CODE_ERROR
        Logger.Error(
                    "\nTestInstallPkg",
                    TE.CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_INSTALL_ERR % Options.DistFiles,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())

    finally:
        Logger.Quiet(ST.MSG_REMOVE_TEMP_FILE_STARTED)
        if DistFile:
            DistFile.Close()
        if ContentZipFile:
            ContentZipFile.Close()
        for TempDir in GlobalData.gUNPACK_DIR:
            shutil.rmtree(TempDir)
        GlobalData.gUNPACK_DIR = []
        Logger.Quiet(ST.MSG_REMOVE_TEMP_FILE_DONE)
    if ReturnCode == 0:
        Logger.Quiet(ST.MSG_FINISH)
    return ReturnCode
예제 #3
0
 def configure_pjsip(self):
     log.info("Configuring PJSIP")
     cflags = "-O3 -fPIC"
     if sys.platform == "darwin":
         if platform.mac_ver()[0].startswith('10.6') and not platform.python_version().startswith('2.5'):
             cflags += " -arch i386 -arch x86_64"
         else:
             cflags += " -arch i386 -mmacosx-version-min=10.5 -isysroot /Developer/SDKs/MacOSX10.5.sdk"
     if self.pjsip_disable_assertions:
         cflags += " -DNDEBUG"
     env = os.environ.copy()
     env['CFLAGS'] = ' '.join(x for x in (cflags, env.get('CFLAGS', None)) if x)
     if sys.platform == "darwin" and platform.python_version().startswith('2.5'):
         env['LDFLAGS'] = "-arch i386 -L/Developer/SDKs/MacOSX10.5.sdk/usr/lib"
         with open(os.path.join(self.svn_dir, "user.mak"), "w") as f:
             f.write("export CC=gcc-4.0 -c\n")
             f.write("export LD=gcc-4.0\n")
         distutils_exec_process(["./configure"], True, cwd=self.svn_dir, env=env)
     elif sys.platform == "win32":
         # TODO: add support for building with other compilers like Visual Studio. -Saul
         env['CFLAGS'] += " -Ic:/openssl/include"
         env['LDFLAGS'] = "-Lc:/openssl/lib/MinGW"
         distutils_exec_process(["bash", "configure"], True, cwd=self.svn_dir, env=env)
     else:
         distutils_exec_process(["./configure"], True, cwd=self.svn_dir, env=env)
     if "#define PJSIP_HAS_TLS_TRANSPORT 1\n" not in open(os.path.join(self.svn_dir, "pjsip", "include", "pjsip", "sip_autoconf.h")).readlines():
         os.remove(os.path.join(self.svn_dir, "build.mak"))
         raise DistutilsError("PJSIP TLS support was disabled, OpenSSL development files probably not present on this system")
예제 #4
0
파일: WurmCommon.py 프로젝트: hamaw/WUU
def setUserAgent(wuuversion):
    """ Sets the user agent to use for web requests.
    Also sets the socket timeout, in lieu of a better place. """
    tracer.debug("setUserAgent")
    
    global useragent
    
    wuuplatform = "Unknown"
    if sys.platform[:5] == 'linux':
        wuuplatform = 'X11; U; Linux %s; Python %s' % (platform.machine(), platform.python_version())
    elif sys.platform == 'darwin':
        maccpu = 'PPC'
        if platform.machine() == 'i386':
            maccpu = 'Intel'
        wuuplatform = 'Macintosh; U; %s Mac OS X' % (maccpu)
    elif sys.platform == 'win32':
        winver = platform.version()[:3] # should grab only the major.minor of the OS version
        wuuplatform = 'Windows; U; Windows NT %s; Python %s' % (winver, platform.python_version())
    
    useragent = "WUU/%s (%s)" % (wuuversion, wuuplatform) # sets the user agent used for web requests
    logger.log(DEBUG5, 'User agent set to %s' % (useragent))
    
    # Try to set global socket timeout - if unparseable as an integer, use blocking mode
    try:
        timeout = int(getGlobalSetting(":SocketTimeout"))
        if timeout > 0:
            socket.setdefaulttimeout(timeout)
            outDebug("Socket timeout set to %d seconds" % (timeout))
    except:
        pass # blocking mode (the all-round default)
예제 #5
0
    def user_agent(): # pragma: no cover
        """Returns string representation of user-agent"""
        implementation = platform.python_implementation()

        if implementation == 'CPython':
            version = platform.python_version()
        elif implementation == 'PyPy':
            version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro)
        elif implementation == 'Jython':
            version = platform.python_version()
        elif implementation == 'IronPython':
            version = platform.python_version()
        else:
            version = 'Unknown'

        try:
            system = platform.system()
            release = platform.release()
        except IOError:
            system = 'Unknown'
            release = 'Unknown'

        return " ".join([
            'appurify-client/%s' % constants.__version__,
            'python-requests/%s' % requests.__version__,
            '%s/%s' % (implementation, version),
            '%s/%s' % (system, release)
        ])
예제 #6
0
def get_machine_details():

    if _debug:
        print 'Getting machine details...'
    buildno, builddate = platform.python_build()
    python = platform.python_version()
    try:
        unichr(100000)
    except ValueError:
        # UCS2 build (standard)
        unicode = 'UCS2'
    except NameError:
        unicode = None
    else:
        # UCS4 build (most recent Linux distros)
        unicode = 'UCS4'
    bits, linkage = platform.architecture()
    return {
        'platform': platform.platform(),
        'processor': platform.processor(),
        'executable': sys.executable,
        'implementation': getattr(platform, 'python_implementation',
                                  lambda:'n/a')(),
        'python': platform.python_version(),
        'compiler': platform.python_compiler(),
        'buildno': buildno,
        'builddate': builddate,
        'unicode': unicode,
        'bits': bits,
        }
예제 #7
0
파일: cpt.py 프로젝트: manasij7479/cling
def check_win(pkg):
    # Check for Microsoft Visual Studio 11.0
    if pkg == "msvc":
        if exec_subprocess_check_output('REG QUERY HKEY_CLASSES_ROOT\VisualStudio.DTE.11.0', 'C:\\').find('ERROR') == -1:
            print pkg.ljust(20) + '[OK]'.ljust(30)
        else:
            print pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30)

    elif pkg == "python":
        if platform.python_version()[0] == '3':
            print pkg.ljust(20) + '[UNSUPPORTED VERSION (Python 3)]'.ljust(30)
        elif float(platform.python_version()[:3]) < 2.7:
            print pkg.ljust(20) + '[OUTDATED VERSION (<2.7)]'.ljust(30)
        else:
            print pkg.ljust(20) + '[OK]'.ljust(30)
    elif pkg == 'SSL':
        import socket
        import httplib
        if hasattr(httplib, 'HTTPS') == True and hasattr(socket, 'ssl') == True:
            print pkg.ljust(20) + '[SUPPORTED]'.ljust(30)
        else:
            print pkg.ljust(20) + '[NOT SUPPORTED]'.ljust(30)

  # Check for other tools
    else:
        if exec_subprocess_check_output('where %s'%(pkg), 'C:\\').find('ERROR') != -1:
            print pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30)
        else:
            print pkg.ljust(20) + '[OK]'.ljust(30)
예제 #8
0
def get_machine_details():

    if _debug:
        print("Getting machine details...")
    buildno, builddate = platform.python_build()
    python = platform.python_version()
    if sys.maxunicode == 65535:
        # UCS2 build (standard)
        unitype = "UCS2"
    else:
        # UCS4 build (most recent Linux distros)
        unitype = "UCS4"
    bits, linkage = platform.architecture()
    return {
        "platform": platform.platform(),
        "processor": platform.processor(),
        "executable": sys.executable,
        "implementation": getattr(platform, "python_implementation", lambda: "n/a")(),
        "python": platform.python_version(),
        "compiler": platform.python_compiler(),
        "buildno": buildno,
        "builddate": builddate,
        "unicode": unitype,
        "bits": bits,
    }
예제 #9
0
파일: cpt.py 프로젝트: manasij7479/cling
def check_ubuntu(pkg):
    if pkg == "gnupg":
        SIGNING_USER = exec_subprocess_check_output('gpg --fingerprint | grep uid | sed s/"uid *"//g', CLING_SRC_DIR).strip()
        if SIGNING_USER == '':
            print pkg.ljust(20) + '[INSTALLED - NOT SETUP]'.ljust(30)
        else:
            print pkg.ljust(20) + '[OK]'.ljust(30)
    elif pkg == "python":
        if platform.python_version()[0] == '3':
            print pkg.ljust(20) + '[UNSUPPORTED VERSION (Python 3)]'.ljust(30)
        elif float(platform.python_version()[:3]) < 2.7:
            print pkg.ljust(20) + '[OUTDATED VERSION (<2.7)]'.ljust(30)
        else:
            print pkg.ljust(20) + '[OK]'.ljust(30)
    elif pkg == "SSL":
        import socket
        import httplib
        if hasattr(httplib, 'HTTPS') == True and hasattr(socket, 'ssl') == True:
            print pkg.ljust(20) + '[SUPPORTED]'.ljust(30)
        else:
            print pkg.ljust(20) + '[NOT SUPPORTED]'.ljust(30)
    elif exec_subprocess_check_output("dpkg-query -W -f='${Status}' %s 2>/dev/null | grep -c 'ok installed'"%(pkg), CLING_SRC_DIR).strip() == '0':
        print pkg.ljust(20) + '[NOT INSTALLED]'.ljust(30)
    else:
        if pkg == "g++":
            if float(exec_subprocess_check_output('g++ -dumpversion', CLING_SRC_DIR).strip()) <= 4.7:
                print pkg.ljust(20) + '[UNSUPPORTED VERSION (<4.7)]'.ljust(30)
            else:
                print pkg.ljust(20) + '[OK]'.ljust(30)
        else:
            print pkg.ljust(20) + '[OK]'.ljust(30)
예제 #10
0
def _implementation_string():
    """
    Returns a string that provides both the name and the version of the Python
    implementation currently running. For example, on CPython 2.7.5 it will
    return "CPython/2.7.5".

    This function works best on CPython and PyPy: in particular, it probably
    doesn't work for Jython or IronPython. Future investigation should be done
    to work out the correct shape of the code for those platforms.
    """
    implementation = platform.python_implementation()

    if implementation == "CPython":
        implementation_version = platform.python_version()
    elif implementation == "PyPy":
        implementation_version = "%s.%s.%s" % (
            sys.pypy_version_info.major,
            sys.pypy_version_info.minor,
            sys.pypy_version_info.micro,
        )
        if sys.pypy_version_info.releaselevel != "final":
            implementation_version = "".join([implementation_version, sys.pypy_version_info.releaselevel])
    elif implementation == "Jython":
        implementation_version = platform.python_version()  # Complete Guess
    elif implementation == "IronPython":
        implementation_version = platform.python_version()  # Complete Guess
    else:
        implementation_version = "Unknown"

    return "%s/%s" % (implementation, implementation_version)
예제 #11
0
def detect_platform():
    _implementation = None
    _implementation_version = None

    if "SERVER_SOFTWARE" in os.environ:
        v = os.environ["SERVER_SOFTWARE"]
        if v.startswith("Google App Engine/") or v.startswith("Development/"):
            _implementation = "Google App Engine"
        else:
            _implementation = platform.python_implementation()
    else:
        _implementation = platform.python_implementation()

    if _implementation == "CPython":
        _implementation_version = platform.python_version()
    elif _implementation == "PyPy":
        _implementation_version = "%s.%s.%s" % (
            sys.pypy_version_info.major,
            sys.pypy_version_info.minor,
            sys.pypy_version_info.micro,
        )
        if sys.pypy_version_info.releaselevel != "final":
            _implementation_version = "".join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == "Jython":
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == "IronPython":
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == "Google App Engine":
        v = os.environ["SERVER_SOFTWARE"]
        _implementation_version = v.split("/")[1]
    else:
        _implementation_version = "Unknown"

    return {"implementation": _implementation, "version": _implementation_version}
def TestPlatForm():
    print "--------------Operation System------------"

    print platform.architecture()
    print platform.platform()
    print platform.system()
    print platform.python_version()
예제 #13
0
def default_context():
    def format_full_version(info):
        version = '%s.%s.%s' % (info.major, info.minor, info.micro)
        kind = info.releaselevel
        if kind != 'final':
            version += kind[0] + str(info.serial)
        return version

    if hasattr(sys, 'implementation'):
        implementation_version = format_full_version(sys.implementation.version)
        implementation_name = sys.implementation.name
    else:
        implementation_version = '0'
        implementation_name = ''

    result = {
        'implementation_name': implementation_name,
        'implementation_version': implementation_version,
        'os_name': os.name,
        'platform_machine': platform.machine(),
        'platform_python_implementation': platform.python_implementation(),
        'platform_release': platform.release(),
        'platform_system': platform.system(),
        'platform_version': platform.version(),
        'platform_in_venv': str(in_venv()),
        'python_full_version': platform.python_version(),
        'python_version': platform.python_version()[:3],
        'sys_platform': sys.platform,
    }
    return result
예제 #14
0
    def turn(self, gameState):
        brains = '' # number of brains rolled this turn
        shotguns = '' # number of shotguns rolled this turn
        print('Scores:')
        for zombieName, zombieScore in gameState[SCORES].items():
            print('\t%s - %s' % (zombieScore, zombieName))
        print()

        while True:
            results = roll()
            brains   += ''.join([x[COLOR][0].upper() for x in results if x[ICON] == BRAINS])
            shotguns += ''.join([x[COLOR][0].upper() for x in results if x[ICON] == SHOTGUN])

            print('Roll:')
            for i in range(3):
                print(results[i][COLOR], '\t', results[i][ICON])
            print()
            print('Brains  : %s\t\tShotguns: %s' % (brains, shotguns))
            if len(shotguns) < 3:
                print('Press Enter to roll again, or enter "S" to stop.')
                if platform.python_version().startswith('2.'):
                    response = raw_input() # python 2 code
                else:
                    response = input() # python 3 code
                if response.upper().startswith('S'):
                    return
            else:
                print('Shotgunned! Press Enter to continue.')
                if platform.python_version().startswith('2.'):
                    raw_input() # python 2 code
                else:
                    input() # python 3 code
                return
예제 #15
0
파일: test.py 프로젝트: pauljensen/metdraw
def test_metdraw():
    print "Platform information:"
    print "   Operating System:", platform.system()
    print "   Operating Platform:", platform.platform()

    print ""
    print "Python information:"
    print "   Version:", platform.python_version()
    version = LooseVersion(platform.python_version())
    if version < LooseVersion("2.7"):
        make_error("Python 2.7 is required.")

    print ""
    print "Path setup"
    print "   Looking for metdraw.py"
    if run_quietly("python", "metdraw.py", "--test", "-") != 0:
        make_error("Your path does not include metdraw.py")
    print "   Looking for metcolor.py"
    if run_quietly("python", "metcolor.py", "--test", "-", "-") != 0:
        make_error("Your path does not include metcolor.py")

    print ""
    print "Graphviz"
    dot_cmd = ['dot','-V']
    if run_quietly(*dot_cmd) == 0:
        print "   Graphviz is installed."
        print "   Checking Graphviz version:"
        stderr,stdout = get_output('dot', '-V')
        if 'version 2.28' in stdout:
            print "      Your version [{0}] is compatible with MetDraw.".format(stdout.rstrip())
        else:
            make_error("MetDraw requires Graphviz version 2.28.")
    else:
        make_error("Graphviz is not installed on your path.")
예제 #16
0
def default_user_agent(name="python-requests"):
    """Return a string representing the default user agent."""
    _implementation = platform.python_implementation()

    if _implementation == 'CPython':
        _implementation_version = platform.python_version()
    elif _implementation == 'PyPy':
        _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
                                                sys.pypy_version_info.minor,
                                                sys.pypy_version_info.micro)
        if sys.pypy_version_info.releaselevel != 'final':
            _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == 'Jython':
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == 'IronPython':
        _implementation_version = platform.python_version()  # Complete Guess
    else:
        _implementation_version = 'Unknown'

    try:
        p_system = platform.system()
        p_release = platform.release()
    except IOError:
        p_system = 'Unknown'
        p_release = 'Unknown'

    return " ".join(['%s/%s' % (name, __version__),
                     '%s/%s' % (_implementation, _implementation_version),
                     '%s/%s' % (p_system, p_release)])
예제 #17
0
def default_user_agent(name="crawlit"):
    """Return a string representing the default user agent."""
    #https://github.com/kennethreitz/requests/blob/master/requests/utils.py#L440
    _implementation = platform.python_implementation()

    if _implementation == 'CPython':
        _implementation_version = platform.python_version()
    elif _implementation == 'PyPy':
        _implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
                                                sys.pypy_version_info.minor,
                                                sys.pypy_version_info.micro)
        if sys.pypy_version_info.releaselevel != 'final':
            _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == 'Jython':
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == 'IronPython':
        _implementation_version = platform.python_version()  # Complete Guess
    else:
        _implementation_version = 'Unknown'

    try:
        p_system = platform.system()
        p_release = platform.release()
    except IOError:
        p_system = 'Unknown'
        p_release = 'Unknown'

    return u" ".join(['{0}/{1}'.format(name, get_version()),
                     '%s/%s' % (_implementation, _implementation_version),
                     '%s/%s' % (p_system, p_release)])
예제 #18
0
def getUHID():
    import sys
    currentOS = sys.platform
    uhid = ""
    if (currentOS == "win32") or (currentOS == "cygwin"):
        import platform
        if platform.python_version()[0] == "3":
           import winreg as wreg
        elif platform.python_version()[0] == "2":
           import _winreg as wreg
        try:
            key = wreg.OpenKey(
                                wreg.HKEY_LOCAL_MACHINE,
                                 "SOFTWARE\\Microsoft\\Cryptography",
                                 0,
                                 wreg.KEY_READ | wreg.KEY_WOW64_64KEY
                                )

            uhid = stringTosha512(wreg.QueryValueEx(key, "MachineGuid")[0])
        except ():
            exit("Unable to generate secret cryptographyc key" )
    elif currentOS == "darwin":
        import commands
        uhid = stringTosha512(commands.getstatusoutput(
            "ioreg -l | awk '/IOPlatformSerialNumber/ { print $4 }' | sed s/\\"+'"//g'
            )[1].decode('ascii'))
    else:
        import subprocess
        uhid = stringTosha512(subprocess.check_output(
                'hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid'
                .split()).decode('ascii'))
    return uhid
예제 #19
0
def Main(Options = None):
    if Options:
        pass

    try:
        DataBase = GlobalData.gDB
        InventoryDistInstalled(DataBase)
        ReturnCode = 0
    except FatalError as XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + format_exc())
    except:
        ReturnCode = CODE_ERROR
        Logger.Error("\nInventoryWs",
                    CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_INVENTORYWS_ERR,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(),
            platform) + format_exc())

    if ReturnCode == 0:
        Logger.Quiet(ST.MSG_FINISH)

    return ReturnCode
예제 #20
0
파일: util.py 프로젝트: kraziant/pyvisa
def get_system_details():
    """Return a dictionary with information about the system
    """
    buildno, builddate = platform.python_build()
    python = platform.python_version()
    if sys.maxunicode == 65535:
        # UCS2 build (standard)
        unitype = 'UCS2'
    else:
        # UCS4 build (most recent Linux distros)
        unitype = 'UCS4'
    bits, linkage = platform.architecture()

    from . import ctwrapper

    return {
        'platform': platform.platform(),
        'processor': platform.processor(),
        'executable': sys.executable,
        'implementation': getattr(platform, 'python_implementation',
                                  lambda:'n/a')(),
        'python': platform.python_version(),
        'compiler': platform.python_compiler(),
        'buildno': buildno,
        'builddate': builddate,
        'unicode': unitype,
        'bits': bits,
        'visa': get_library_paths(ctwrapper)
        }
예제 #21
0
    def test_matches_expected(self):
        environment = default_environment()

        iver = "{0.major}.{0.minor}.{0.micro}".format(
            sys.implementation.version
        )
        if sys.implementation.version.releaselevel != "final":
            iver = "{0}{1}[0]{2}".format(
                iver,
                sys.implementation.version.releaselevel,
                sys.implementation.version.serial,
            )

        assert environment == {
            "implementation_name": sys.implementation.name,
            "implementation_version": iver,
            "os_name": os.name,
            "platform_machine": platform.machine(),
            "platform_release": platform.release(),
            "platform_system": platform.system(),
            "platform_version": platform.version(),
            "python_full_version": platform.python_version(),
            "platform_python_implementation": platform.python_implementation(),
            "python_version": platform.python_version()[:3],
            "sys_platform": sys.platform,
        }
예제 #22
0
파일: utils.py 프로젝트: AshishNamdev/remo
def default_user_agent():
    """Return a string representing the default user agent."""
    _implementation = platform.python_implementation()

    if _implementation == 'CPython':
        _implementation_version = platform.python_version()
    elif _implementation == 'PyPy':
        _implementation_version = '%s.%s.%s' % (
                                                sys.pypy_version_info.major,
                                                sys.pypy_version_info.minor,
                                                sys.pypy_version_info.micro
                                            )
        if sys.pypy_version_info.releaselevel != 'final':
            _implementation_version = ''.join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == 'Jython':
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == 'IronPython':
        _implementation_version = platform.python_version()  # Complete Guess
    else:
        _implementation_version = 'Unknown'

    return " ".join([
            'python-requests/%s' % __version__,
            '%s/%s' % (_implementation, _implementation_version),
            '%s/%s' % (platform.system(), platform.release()),
        ])
예제 #23
0
def default_user_agent():
    """Return a string representing the default user agent."""
    _implementation = platform.python_implementation()

    if _implementation == "CPython":
        _implementation_version = platform.python_version()
    elif _implementation == "PyPy":
        _implementation_version = "%s.%s.%s" % (
            sys.pypy_version_info.major,
            sys.pypy_version_info.minor,
            sys.pypy_version_info.micro,
        )
        if sys.pypy_version_info.releaselevel != "final":
            _implementation_version = "".join([_implementation_version, sys.pypy_version_info.releaselevel])
    elif _implementation == "Jython":
        _implementation_version = platform.python_version()  # Complete Guess
    elif _implementation == "IronPython":
        _implementation_version = platform.python_version()  # Complete Guess
    else:
        _implementation_version = "Unknown"

    try:
        p_system = platform.system()
        p_release = platform.release()
    except IOError:
        p_system = "Unknown"
        p_release = "Unknown"

    return " ".join(
        [
            "python-requests/%s" % __version__,
            "%s/%s" % (_implementation, _implementation_version),
            "%s/%s" % (p_system, p_release),
        ]
    )
예제 #24
0
def get_machine_details():

    import platform
    if _debug:
        print 'Getting machine details...'
    buildno, builddate = platform.python_build()
    python = platform.python_version()
    if python > '2.0':
        try:
            unichr(100000)
        except ValueError:
            # UCS2 build (standard)
            unicode = 'UCS2'
        else:
            # UCS4 build (most recent Linux distros)
            unicode = 'UCS4'
    else:
        unicode = None
    bits, linkage = platform.architecture()
    return {
        'platform': platform.platform(),
        'processor': platform.processor(),
        'executable': sys.executable,
        'python': platform.python_version(),
        'compiler': platform.python_compiler(),
        'buildno': buildno,
        'builddate': builddate,
        'unicode': unicode,
        'bits': bits,
        }
예제 #25
0
파일: pybench.py 프로젝트: 10sr/cpython
def get_machine_details():

    if _debug:
        print('Getting machine details...')
    buildno, builddate = platform.python_build()
    python = platform.python_version()
    # XXX this is now always UCS4, maybe replace it with 'PEP393' in 3.3+?
    if sys.maxunicode == 65535:
        # UCS2 build (standard)
        unitype = 'UCS2'
    else:
        # UCS4 build (most recent Linux distros)
        unitype = 'UCS4'
    bits, linkage = platform.architecture()
    return {
        'platform': platform.platform(),
        'processor': platform.processor(),
        'executable': sys.executable,
        'implementation': getattr(platform, 'python_implementation',
                                  lambda:'n/a')(),
        'python': platform.python_version(),
        'compiler': platform.python_compiler(),
        'buildno': buildno,
        'builddate': builddate,
        'unicode': unitype,
        'bits': bits,
        }
예제 #26
0
def user_agent():
    """
    Return a string representing the user agent.
    """
    data = {
        "installer": {"name": "pip", "version": pip.__version__},
        "python": platform.python_version(),
        "implementation": {
            "name": platform.python_implementation(),
        },
    }

    if data["implementation"]["name"] == 'CPython':
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'PyPy':
        if sys.pypy_version_info.releaselevel == 'final':
            pypy_version_info = sys.pypy_version_info[:3]
        else:
            pypy_version_info = sys.pypy_version_info
        data["implementation"]["version"] = ".".join(
            [str(x) for x in pypy_version_info]
        )
    elif data["implementation"]["name"] == 'Jython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'IronPython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()

    if sys.platform.startswith("linux"):
        distro = dict(filter(
            lambda x: x[1],
            zip(["name", "version", "id"], platform.linux_distribution()),
        ))
        libc = dict(filter(
            lambda x: x[1],
            zip(["lib", "version"], platform.libc_ver()),
        ))
        if libc:
            distro["libc"] = libc
        if distro:
            data["distro"] = distro

    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
        data["distro"] = {"name": "OS X", "version": platform.mac_ver()[0]}

    if platform.system():
        data.setdefault("system", {})["name"] = platform.system()

    if platform.release():
        data.setdefault("system", {})["release"] = platform.release()

    if platform.machine():
        data["cpu"] = platform.machine()

    return "{data[installer][name]}/{data[installer][version]} {json}".format(
        data=data,
        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
    )
예제 #27
0
	def __init__(self, texte):

		# Texte qui sera affiché
		self.texte = texte.encode(EkdConfig.coding)
		
		# Affichage selon les versions de Python
		if platform.python_version()[0] == '2': print self.texte
		elif platform.python_version()[0] == '3': print(self.texte)
예제 #28
0
def geisysteminfo():
    """"""
    print platform.system()
    print platform.version()
    print platform.architecture()
    print platform.node()
    print platform.java_ver()
    print platform.dist()
    print platform.python_version()
    print platform.win32_ver()
예제 #29
0
파일: RmPkg.py 프로젝트: shijunjing/edk2
def Main(Options = None):

    try:
        DataBase = GlobalData.gDB
        if not Options.DistributionFile:
            Logger.Error("RmPkg",
                         OPTION_MISSING,
                         ExtraData=ST.ERR_SPECIFY_PACKAGE)
        WorkspaceDir = GlobalData.gWORKSPACE
        #
        # Prepare check dependency
        #
        Dep = DependencyRules(DataBase)

        #
        # Get the Dp information
        #
        StoredDistFile, Guid, Version = GetInstalledDpInfo(Options.DistributionFile, Dep, DataBase, WorkspaceDir)

        #
        # Check Dp depex
        #
        CheckDpDepex(Dep, Guid, Version, WorkspaceDir)

        #
        # remove distribution
        #
        RemoveDist(Guid, Version, StoredDistFile, DataBase, WorkspaceDir, Options.Yes)

        Logger.Quiet(ST.MSG_FINISH)

        ReturnCode = 0

    except FatalError as XExcept:
        ReturnCode = XExcept.args[0]
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except KeyboardInterrupt:
        ReturnCode = ABORT_ERROR
        if Logger.GetLevel() <= Logger.DEBUG_9:
            Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                         format_exc())
    except:
        Logger.Error(
                    "\nRmPkg",
                    CODE_ERROR,
                    ST.ERR_UNKNOWN_FATAL_REMOVING_ERR,
                    ExtraData=ST.MSG_SEARCH_FOR_HELP,
                    RaiseError=False
                    )
        Logger.Quiet(ST.MSG_PYTHON_ON % (python_version(), platform) + \
                     format_exc())
        ReturnCode = CODE_ERROR
    return ReturnCode
예제 #30
0
파일: version.py 프로젝트: sopel-irc/sopel
def version(bot, trigger):
    """Display the latest commit version, if Sopel is running in a git repo."""
    sha = git_info()
    if not sha:
        msg = 'Sopel v. ' + release + ' (Python {})'.format(platform.python_version())
        if release[-4:] == '-git':
            msg += ' at unknown commit.'
        bot.reply(msg)
        return

    bot.reply("Sopel v. {} (Python {}) at commit: {}".format(release, platform.python_version(), sha))
예제 #31
0
print("* 文件内容加密与解密")
print("* 向服务器传送文件")
#--------------------------------------------------
print(StrLine, LineNum, "-零散知识点")
LineNum += 1
print("* 类似C语言中的sprintf: 直接用%即可,例如:str1='%02x %02d' % (i,j)")
print("* 临时增加系统环境变量,sys.path.append(dir e.g C:\...)")
#--------------------------------------------------
print(StrLine, LineNum, "-查看系统信息")
LineNum += 1
print(sys.version)
print("platform.architecture():   ", platform.architecture())
print("platform.system():         ", platform.system())
print("platform.version():        ", platform.version())
print("platform.machine():        ", platform.machine())
print("platform.python_version(): ", platform.python_version())
#--------------------------------------------------

#--------------------------------------------------
# 基本操作: 数据类型类型(数字,字符串,列表,元组,字典)
"""
数字
                int		有符号整数
                long		长整形
                float	        浮点型
                complex	        复数
字符串          string
                1,单行可以用单引号'-',也可以用双引号"-".
                2,多行要用'''-'''
                3,支持转义字符'\',
                4,支持乘法,常用于打印一定数量(但不能用减法与除法)
예제 #32
0
def bootstrap(topdir):
    _ensure_case_insensitive_if_windows()

    topdir = os.path.abspath(topdir)

    len(sys.argv) > 1 and sys.argv[1] == "bootstrap"

    # We don't support paths with Unicode characters for now
    # https://github.com/servo/servo/issues/10002
    try:
        # Trick to support both python2 and python3
        topdir.encode().decode('ascii')
    except UnicodeDecodeError:
        print('Cannot run mach in a path with Unicode characters.')
        print('Current path:', topdir)
        sys.exit(1)

    # We don't support paths with spaces for now
    # https://github.com/servo/servo/issues/9442
    if ' ' in topdir:
        print('Cannot run mach in a path with spaces.')
        print('Current path:', topdir)
        sys.exit(1)

    # Ensure we are running Python 3.5+. We put this check here so we generate a
    # user-friendly error message rather than a cryptic stack trace on module import.
    if sys.version_info < (3, 5):
        print('Python3 (>=3.5) is required to run mach.')
        print('You are running Python', platform.python_version())
        sys.exit(1)

    is_firefox = is_firefox_checkout(topdir)

    _activate_virtualenv(topdir, is_firefox)

    def populate_context(context, key=None):
        if key is None:
            return
        if key == 'topdir':
            return topdir
        raise AttributeError(key)

    sys.path[0:0] = [os.path.join(topdir, path) for path in SEARCH_PATHS]

    sys.path[0:0] = [
        wpt_path(is_firefox, topdir),
        wptrunner_path(is_firefox, topdir),
        wptserve_path(is_firefox, topdir)
    ]

    import mach.main
    mach = mach.main.Mach(os.getcwd())
    mach.populate_context_handler = populate_context

    for category, meta in CATEGORIES.items():
        mach.define_category(category, meta['short'], meta['long'],
                             meta['priority'])

    for path in MACH_MODULES:
        # explicitly provide a module name
        # workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1549636
        file = os.path.basename(path)
        module_name = os.path.splitext(file)[0]
        mach.load_commands_from_file(os.path.join(topdir, path), module_name)

    return mach
예제 #33
0
# # Image Segmentation : Shelter Map Identification

import platform

print('Running on python version:', platform.python_version())
import os

from train import train
from predict import predict
from preprocessing.data import create_train_data, create_test_data
from preprocessing.ew_data import create_ew_data
from resources.plot_results import plot_loss_epoch

#AWS path
data_path = '../shelterdata/180505_v1'

create_train_data(data_path)  #,showSample=True,showNumSample=4)
create_test_data(data_path)
create_ew_data(data_path)

# ### Available models: 'unet','flatunet', 'unet64filters', or 'unet64batchnorm'

# #### Mod U-Net  3
# train(data_path,'unet64filters',number_of_epochs=30,batch_size=32,test_data_fraction=0.2,checkpoint_period=1,load_prev_weights=False,early_stop_patience=1)
# train(data_path,'unet64filters',number_of_epochs=80,batch_size=32,test_data_fraction=0.2,checkpoint_period=10,load_prev_weights=True,early_stop_patience=5)
# plot_loss_epoch(data_path+'/internal/checkpoints/','unet64filters')
# predict(data_path,'unet64filters')

#### Mod U-Net  3.5
modelname = "unet64filters_weighted"
train(data_path,
예제 #34
0
    def test_sys_version(self):
        # Old test.
        for input, output in (
            ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
             ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21',
              'GCC 3.3.4 (pre 3.3.5 20040809)')),
            ('IronPython 1.0.60816 on .NET 2.0.50727.42',
             ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
            ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
             ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
            ('2.4.3 (truncation, date, t) \n[GCC]',
             ('CPython', '2.4.3', '', '', 'truncation', 'date t', 'GCC')),
            ('2.4.3 (truncation, date, ) \n[GCC]',
             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
            ('2.4.3 (truncation, date,) \n[GCC]',
             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
            ('2.4.3 (truncation, date) \n[GCC]',
             ('CPython', '2.4.3', '', '', 'truncation', 'date', 'GCC')),
            ('2.4.3 (truncation, d) \n[GCC]', ('CPython', '2.4.3', '', '',
                                               'truncation', 'd', 'GCC')),
            ('2.4.3 (truncation, ) \n[GCC]', ('CPython', '2.4.3', '', '',
                                              'truncation', '', 'GCC')),
            ('2.4.3 (truncation,) \n[GCC]', ('CPython', '2.4.3', '', '',
                                             'truncation', '', 'GCC')),
            ('2.4.3 (truncation) \n[GCC]', ('CPython', '2.4.3', '', '',
                                            'truncation', '', 'GCC')),
        ):
            # branch and revision are not "parsed", but fetched
            # from sys._git.  Ignore them
            (name, version, branch, revision, buildno, builddate, compiler) \
                   = platform._sys_version(input)
            self.assertEqual(
                (name, version, '', '', buildno, builddate, compiler), output)

        # Tests for python_implementation(), python_version(), python_branch(),
        # python_revision(), python_build(), and python_compiler().
        sys_versions = {
            ("2.6.1 (r261:67515, Dec  6 2008, 15:26:00) \n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]", ('CPython', 'tags/r261', '67515'), self.save_platform):
            ("CPython", "2.6.1", "tags/r261", "67515",
             ('r261:67515', 'Dec  6 2008 15:26:00'),
             'GCC 4.0.1 (Apple Computer, Inc. build 5370)'),
            ("IronPython 2.0 (2.0.0.0) on .NET 2.0.50727.3053", None, "cli"):
            ("IronPython", "2.0.0", "", "", ("", ""), ".NET 2.0.50727.3053"),
            ("2.6.1 (IronPython 2.6.1 (2.6.10920.0) on .NET 2.0.50727.1433)", None, "cli"):
            ("IronPython", "2.6.1", "", "", ("", ""), ".NET 2.0.50727.1433"),
            ("2.7.4 (IronPython 2.7.4 (2.7.0.40) on Mono 4.0.30319.1 (32-bit))", None, "cli"):
            ("IronPython", "2.7.4", "", "", ("", ""),
             "Mono 4.0.30319.1 (32-bit)"),
            ("2.5 (trunk:6107, Mar 26 2009, 13:02:18) \n[Java HotSpot(TM) Client VM (\"Apple Computer, Inc.\")]", ('Jython', 'trunk', '6107'), "java1.5.0_16"):
            ("Jython", "2.5.0", "trunk", "6107", ('trunk:6107', 'Mar 26 2009'),
             "java1.5.0_16"),
            ("2.5.2 (63378, Mar 26 2009, 18:03:29)\n[PyPy 1.0.0]", ('PyPy', 'trunk', '63378'), self.save_platform):
            ("PyPy", "2.5.2", "trunk", "63378", ('63378', 'Mar 26 2009'), "")
        }
        for (version_tag, scm, sys_platform), info in \
                sys_versions.items():
            sys.version = version_tag
            if scm is None:
                if hasattr(sys, "_git"):
                    del sys._git
            else:
                sys._git = scm
            if sys_platform is not None:
                sys.platform = sys_platform
            self.assertEqual(platform.python_implementation(), info[0])
            self.assertEqual(platform.python_version(), info[1])
            self.assertEqual(platform.python_branch(), info[2])
            self.assertEqual(platform.python_revision(), info[3])
            self.assertEqual(platform.python_build(), info[4])
            self.assertEqual(platform.python_compiler(), info[5])
예제 #35
0
from logbook.compat import LoggingHandler
import platform
import forge
import shakedown
from shakedown.conf import config
if platform.python_version() < "2.7":
    import unittest2 as unittest
else:
    import unittest

class TestCase(unittest.TestCase):
    def setUp(self):
        super(TestCase, self).setUp()
        self._handler = LoggingHandler()
        self._handler.push_application()
        self.override_config("hooks.swallow_exceptions", False)
        self.override_config("log.console_level", 10000) # silence console in tests
    def override_config(self, path, value):
        self.addCleanup(config.assign_path, path, config.get_path(path))
        config.assign_path(path, value)
    _forge = None
    @property
    def forge(self):
        if self._forge is None:
            self._forge = forge.Forge()
        return self._forge
    _events = None
    @property
    def events(self):
        if self._events is None:
            self._events = self.forge.create_wildcard_mock()
예제 #36
0
# check version of packages
# import the neccessary packages
import numpy as np
import urllib.request
import matplotlib.pyplot as plt
import cv2
import tensorflow as tf
import keras

# show version of packages

# python version
from platform import python_version
print('Python version: {}'.format(python_version()))

# opencv version
print('OpenCV version: {}'.format(cv2.__version__))

# tensorflow version
print('Tensorflow version: {}'.format(tf.__version__))

# keras version
print('Keras version: {}'.format(keras.__version__))


# Convert URL to image with Python and OpenCV
# METHOD #1: OpenCV, NumPy, and urllib
def url_to_image(url):
    # download the image, convert it to a Numpy array, and then read
    # it into OpenCV format
    resp = urllib.request.urlopen(url)
예제 #37
0
def collect_python_metadata(metadata):
    # Implementation
    impl = perf.python_implementation()
    metadata['python_implementation'] = impl

    # Version
    version = platform.python_version()

    match = re.search(r'\[(PyPy [^ ]+)', sys.version)
    if match:
        version = '%s (Python %s)' % (match.group(1), version)

    bits = platform.architecture()[0]
    if bits:
        if bits == '64bit':
            bits = '64-bit'
        elif bits == '32bit':
            bits = '32-bit'
        version = '%s (%s)' % (version, bits)

    # '74667320778e' in 'Python 2.7.12+ (2.7:74667320778e,'
    match = re.search(r'^[^(]+\([^:]+:([a-f0-9]{6,}\+?),', sys.version)
    if match:
        revision = match.group(1)
    else:
        # 'bbd45126bc691f669c4ebdfbd74456cd274c6b92'
        # in 'Python 2.7.10 (bbd45126bc691f669c4ebdfbd74456cd274c6b92,'
        match = re.search(r'^[^(]+\(([a-f0-9]{6,}\+?),', sys.version)
        if match:
            revision = match.group(1)
        else:
            revision = None
    if revision:
        version = '%s revision %s' % (version, revision)
    metadata['python_version'] = version

    if sys.executable:
        metadata['python_executable'] = sys.executable

    # Before PEP 393 (Python 3.3)
    if sys.version_info < (3, 3):
        if sys.maxunicode == 0xffff:
            unicode_impl = 'UTF-16'
        else:
            unicode_impl = 'UCS-4'
        metadata['python_unicode'] = unicode_impl

    # timer
    if (hasattr(time, 'perf_counter')
            and perf.perf_counter == time.perf_counter):

        info = time.get_clock_info('perf_counter')
        metadata['timer'] = (
            '%s, resolution: %s' %
            (info.implementation, format_timedelta(info.resolution)))
    elif perf.perf_counter == time.clock:
        metadata['timer'] = 'time.clock()'
    elif perf.perf_counter == time.time:
        metadata['timer'] = 'time.time()'

    # PYTHONHASHSEED
    if os.environ.get('PYTHONHASHSEED'):
        hash_seed = os.environ['PYTHONHASHSEED']
        try:
            if hash_seed != "random":
                hash_seed = int(hash_seed)
        except ValueError:
            pass
        else:
            metadata['python_hash_seed'] = hash_seed

    # CFLAGS
    try:
        import sysconfig
    except ImportError:
        pass
    else:
        cflags = sysconfig.get_config_var('CFLAGS')
        if cflags:
            cflags = normalize_text(cflags)
            metadata['python_cflags'] = cflags

    # GC disabled?
    try:
        import gc
    except ImportError:
        pass
    else:
        if not gc.isenabled():
            metadata['python_gc'] = 'disabled'
예제 #38
0
df = pd.DataFrame(vals)

X = df.drop('Class', axis=1)
y = df.loc[:, 'Class']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=420)

#:# preprocessing

#:# model
model = KNeighborsClassifier(n_neighbors=9, algorithm='kd_tree')
model.fit(X_train, y_train)

#:# hash
#:# e37d46e1a5c0065376d1471f564f3ac7
md5 = hashlib.md5(str(model).encode('utf-8')).hexdigest()
print(f'md5: {md5}')

#:# audit
y_pred = model.predict(X_test)
y_pred_proba = model.predict_proba(X_test)[:, 1]
print(f'Accuracy: {model.score(X_test, y_test)}')
print(f'Area under ROC: {roc_auc_score(y_test, y_pred_proba)}')

#:# session info
sessionInfo = {
    "python_version": python_version(),
    "library_versions":[str(d) for d in pkg_resources.working_set]
}
with open('sessionInfo.txt', 'w') as f:
    json.dump(sessionInfo, f, indent=4)
예제 #39
0
# -*- coding: utf-8 -*-

from riak.mapreduce import RiakMapReduce
from riak import key_filter, RiakError
from riak.tests.test_yokozuna import wait_for_yz_index
from riak.tests import RUN_SECURITY
import platform
if platform.python_version() < '2.7':
    unittest = __import__('unittest2')
else:
    import unittest

from . import RUN_YZ


class LinkTests(object):
    def test_store_and_get_links(self):
        # Create the object...
        bucket = self.client.bucket(self.bucket_name)
        bucket.new(key=self.key_name, encoded_data='2',
                   content_type='application/octet-stream') \
            .add_link(bucket.new("foo1")) \
            .add_link(bucket.new("foo2"), "tag") \
            .add_link(bucket.new("foo3"), "tag2!@#%^&*)") \
            .store()
        obj = bucket.get(self.key_name)
        links = obj.links
        self.assertEqual(len(links), 3)
        for bucket, key, tag in links:
            if (key == "foo1"):
                self.assertEqual(bucket, self.bucket_name)
 def run(self):
     # type: () -> List[nodes.Node]
     # use ordinary docutils nodes for test code: they get special attributes
     # so that our builder recognizes them, and the other builders are happy.
     code = '\n'.join(self.content)
     test = None
     if self.name == 'doctest':
         if '<BLANKLINE>' in code:
             # convert <BLANKLINE>s to ordinary blank lines for presentation
             test = code
             code = blankline_re.sub('', code)
         if doctestopt_re.search(code):
             if not test:
                 test = code
             code = doctestopt_re.sub('', code)
     nodetype = nodes.literal_block
     if self.name in ('testsetup', 'testcleanup') or 'hide' in self.options:
         nodetype = nodes.comment
     if self.arguments:
         groups = [x.strip() for x in self.arguments[0].split(',')]
     else:
         groups = ['default']
     node = nodetype(code, code, testnodetype=self.name, groups=groups)
     set_source_info(self, node)
     if test is not None:
         # only save if it differs from code
         node['test'] = test
     if self.name == 'testoutput':
         # don't try to highlight output
         node['language'] = 'none'
     node['options'] = {}
     if self.name in ('doctest', 'testoutput') and 'options' in self.options:
         # parse doctest-like output comparison flags
         option_strings = self.options['options'].replace(',', ' ').split()
         for option in option_strings:
             prefix, option_name = option[0], option[1:]
             if prefix not in '+-':
                 self.state.document.reporter.warning(
                     _("missing '+' or '-' in '%s' option.") % option,
                     line=self.lineno)
                 continue
             if option_name not in doctest.OPTIONFLAGS_BY_NAME:
                 self.state.document.reporter.warning(
                     _("'%s' is not a valid option.") % option_name,
                     line=self.lineno)
                 continue
             flag = doctest.OPTIONFLAGS_BY_NAME[option[1:]]
             node['options'][flag] = (option[0] == '+')
     if self.name == 'doctest' and 'pyversion' in self.options:
         try:
             option = self.options['pyversion']
             # :pyversion: >= 3.6   -->   operand='>=', option_version='3.6'
             operand, option_version = [item.strip() for item in option.split()]
             running_version = platform.python_version()
             if not compare_version(running_version, option_version, operand):
                 flag = doctest.OPTIONFLAGS_BY_NAME['SKIP']
                 node['options'][flag] = True  # Skip the test
         except ValueError:
             self.state.document.reporter.warning(
                 _("'%s' is not a valid pyversion option") % option,
                 line=self.lineno)
     return [node]
예제 #41
0
import numpy as np
import os
import tensorflow as tf
import tqdm
import pdb
import glob
import time
import sys
import re
import argparse
import fastBPE
import platform

use_py3 = platform.python_version()[0] == '3'

parser = argparse.ArgumentParser(
    description='TensorFlow code for creating TFRecords data')
parser.add_argument('--text_file',
                    type=str,
                    required=False,
                    help='location of text file to convert to TFRecords')
parser.add_argument(
    '--control_code',
    type=str,
    required=False,
    help=
    'control code to use for this file. must be in the vocabulary, else it will error out.'
)
parser.add_argument(
    '--sequence_len',
    type=int,
예제 #42
0
class BaseClient:
    class StopTransmission(StopIteration):
        pass

    APP_VERSION = "Pyrogram {}".format(__version__)

    DEVICE_MODEL = "{} {}".format(platform.python_implementation(),
                                  platform.python_version())

    SYSTEM_VERSION = "{} {}".format(platform.system(), platform.release())

    LANG_CODE = "en"

    INVITE_LINK_RE = re.compile(
        r"^(?:https?://)?(?:www\.)?(?:t(?:elegram)?\.(?:org|me|dog)/joinchat/)([\w-]+)$"
    )
    BOT_TOKEN_RE = re.compile(r"^\d+:[\w-]+$")
    DIALOGS_AT_ONCE = 100
    UPDATES_WORKERS = 1
    DOWNLOAD_WORKERS = 1
    OFFLINE_SLEEP = 900
    WORKERS = 4
    WORKDIR = "."
    CONFIG_FILE = "./config.ini"

    MEDIA_TYPE_ID = {
        0: "photo_thumbnail",
        1: "chat_photo",
        2: "photo",
        3: "voice",
        4: "video",
        5: "document",
        8: "sticker",
        9: "audio",
        10: "animation",
        13: "video_note",
        14: "document_thumbnail"
    }

    mime_types_to_extensions = {}
    extensions_to_mime_types = {}

    with open("{}/mime.types".format(os.path.dirname(__file__)),
              "r",
              encoding="UTF-8") as f:
        for match in re.finditer(r"^([^#\s]+)\s+(.+)$", f.read(), flags=re.M):
            mime_type, extensions = match.groups()

            extensions = [".{}".format(ext) for ext in extensions.split(" ")]

            for ext in extensions:
                extensions_to_mime_types[ext] = mime_type

            mime_types_to_extensions[mime_type] = " ".join(extensions)

    def __init__(self):
        self.is_bot = None
        self.dc_id = None
        self.auth_key = None
        self.user_id = None
        self.date = None

        self.rnd_id = MsgId

        self.peers_by_id = {}
        self.peers_by_username = {}
        self.peers_by_phone = {}

        self.markdown = Markdown(self)
        self.html = HTML(self)

        self.session = None
        self.media_sessions = {}
        self.media_sessions_lock = Lock()

        self.is_started = None
        self.is_idle = None

        self.takeout_id = None

        self.updates_queue = Queue()
        self.updates_workers_list = []
        self.download_queue = Queue()
        self.download_workers_list = []

        self.disconnect_handler = None

    def send(self, *args, **kwargs):
        pass

    def resolve_peer(self, *args, **kwargs):
        pass

    def fetch_peers(self, *args, **kwargs):
        pass

    def add_handler(self, *args, **kwargs):
        pass

    def save_file(self, *args, **kwargs):
        pass

    def get_messages(self, *args, **kwargs):
        pass

    def get_history(self, *args, **kwargs):
        pass

    def get_dialogs(self, *args, **kwargs):
        pass

    def get_chat_members(self, *args, **kwargs):
        pass

    def get_chat_members_count(self, *args, **kwargs):
        pass

    def answer_inline_query(self, *args, **kwargs):
        pass

    def guess_mime_type(self, *args, **kwargs):
        pass

    def guess_extension(self, *args, **kwargs):
        pass

    def get_profile_photos(self, *args, **kwargs):
        pass
예제 #43
0
        buffers = []
        if data:
            buffers.append(data)
        self._rbuf = ""
        while True:
            left = size - buf_len
            recv_size = min(self._rbufsize, left)  # the actual fix
            data = self._sock.recv(recv_size)
            if not data:
                break
            buffers.append(data)
            n = len(data)
            if n >= left:
                self._rbuf = data[left:]
                buffers[-1] = data[:left]
                break
            buf_len += n
        return "".join(buffers)


# Platform detection to enable socket patch
if 'Darwin' in platform.platform() and '2.3.5' == platform.python_version():
    socket._fileobject.read = _fixed_socket_read
# 20181212: Windows 10 + Python 2.7 doesn't need this fix (fix leads to error: object of type 'cStringIO.StringO' has no len())
if 'Windows' in platform.platform() and '2.3.5' == platform.python_version():
    socket._fileobject.read = _fixed_socket_read

if __name__ == '__main__':
    gc.enable()
    main()
예제 #44
0
def get_sys_info():
    # Get CPU name and RAM
    system = platform.system()
    cpu = ""
    cpu_ram = ""
    if system == "Windows":
        cpu = subprocess.check_output(
            ["wmic", "cpu", "get",
             "name"]).decode("utf-8").strip().split("\n")[1]
        cpu_ram = "{:.2f}".format(
            int(
                subprocess.check_output([
                    "wmic", "computersystem", "get", "totalphysicalmemory"
                ]).decode("utf-8").strip().split("\n")[1]) /
            (1 << 30)) + " GiB"
    elif system == "Darwin":
        cpu = subprocess.check_output(
            ["/usr/sbin/sysctl", "-n",
             "machdep.cpu.brand_string"]).decode("utf-8").strip()
        cpu_ram = "{:.2f}".format(
            int(
                subprocess.check_output([
                    "/usr/sbin/sysctl", "-n", "hw.memsize"
                ]).decode("utf-8").strip()) / (1 << 30)) + " GiB"
    elif system == "Linux":
        all_info = subprocess.check_output(["cat", "/proc/cpuinfo"
                                            ]).decode("utf-8").strip()
        for line in all_info.split("\n"):
            if line.startswith("model name"):
                cpu = line.split(": ")[1]
                break
        all_info = subprocess.check_output(["cat", "/proc/meminfo"
                                            ]).decode("utf-8").strip()
        for line in all_info.split("\n"):
            if line.startswith("MemTotal"):
                cpu_ram = "{:.2f}".format(
                    int(line.split(": ")[1].strip(" kB")) / (1 << 20)) + " GiB"
                break

    # Get GPU name and RAM
    gpu = ""
    gpu_ram = ""
    cuda = ""
    if P.DEVICE != 'cpu':
        gpu = torch.cuda.get_device_name(P.DEVICE)
        gpu_ram = "{:.2f}".format(
            torch.cuda.get_device_properties(P.DEVICE).total_memory /
            (1 << 30)) + " GiB"
        cuda = torch.version.cuda

    # Check if running on Google Colab
    in_colab = True
    try:
        import google.colab
    except:
        in_colab = False

    # Construct string containing system information
    SYS_INFO = ""
    SYS_INFO += "CPU: " + cpu + "\n"
    SYS_INFO += "CPU_RAM: " + cpu_ram + "\n"
    SYS_INFO += "DEVICE: " + P.DEVICE + "\n"
    SYS_INFO += "GPU: " + gpu + "\n"
    SYS_INFO += "GPU_RAM: " + gpu_ram + "\n"
    SYS_INFO += "CUDA: " + cuda + "\n"
    SYS_INFO += "OS: " + platform.platform() + "\n"
    SYS_INFO += "IN_COLAB: " + str(in_colab) + "\n"
    SYS_INFO += "PYTHON_VERSION: " + platform.python_version() + "\n"
    SYS_INFO += "PACKAGE_VERSIONS: " + str(P.ADDITIONAL_INFO) + "\n"
    SYS_INFO += "GLB_PARAMS: " + str(P.GLB_PARAMS)

    return SYS_INFO
# Src path
source_path = os.path.abspath(
    os.path.join('/dcos/volume0/geowave/ntcml-geowave/src/'))
if source_path not in sys.path:
    sys.path.append(source_path)

import MSTAR_7_Dataset
import Classifier_MSTAR7
import eval
import state_utils
from config import USE_GPU, SOFTMAX_LR, SOFTMAX_BATCH_SIZE, SOFTMAX_EPOCHS, DATASET, \
    SOFTMAX_CHECKPOINT, SOFTMAX_MOMENTUM, SOFTMAX_WEIGHT_DECAY, IMAGE_SIZE, \
    TRAIN_DATASET, TEST_DATASET
import platform
print(platform.python_version())

print(SOFTMAX_CHECKPOINT)
print(DATASET)
print(IMAGE_SIZE)
print(USE_GPU)

#configure("../tensorboard_out", flush_secs=5)
#dataset_dir = os.path.join(DATASET, "cnn")
dataset_dir = DATASET
train_dataset = TRAIN_DATASET
test_dataset = TEST_DATASET


######################### CLASSSES AND FUNCTIONS #########################
# denormalize and display image
예제 #46
0
from __future__ import absolute_import, division, print_function, unicode_literals

import functools
import itertools
import logging
import math
import platform

import numpy as np

from enterprise.signals import parameter, selections, signal_base, utils
from enterprise.signals.parameter import function
from enterprise.signals.selections import Selection
from enterprise.signals.utils import KernelMatrix

pyv3 = platform.python_version().split(".")[0] == "3"

logging.basicConfig(format="%(levelname)s: %(name)s: %(message)s", level=logging.INFO)
logger = logging.getLogger(__name__)


def BasisGP(
    priorFunction,
    basisFunction,
    coefficients=False,
    combine=True,
    selection=Selection(selections.no_selection),
    name="",
):
    """Class factory for generic GPs with a basis matrix."""
예제 #47
0
def main():
    colorama.init()
    parser = argparse.ArgumentParser()
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%s v%s' % (parser.prog, __version__))

    if sys.version_info[:2] >= (3, 7):
        subparsers = parser.add_subparsers(dest='command', required=True)
    else:
        subparsers = parser.add_subparsers(dest='command')

    parser_latest = subparsers.add_parser(
        CMD_LATEST,
        help="get the latest price of an asset",
        description="Get the latest [asset] price (in GBP). "
        "If no data source [-ds] is given, "
        "the same data source(s) as "
        "'bittytax' are used.")
    parser_latest.add_argument('asset',
                               type=str,
                               nargs=1,
                               help="symbol of cryptoasset or fiat currency "
                               "(i.e. BTC/LTC/ETH or EUR/USD)")
    parser_latest.add_argument('quantity',
                               type=validate_quantity,
                               nargs='?',
                               help="quantity to price (optional)")
    parser_latest.add_argument(
        '-ds',
        choices=datasource_choices(upper=True) + ['ALL'],
        metavar='{' + ', '.join(datasource_choices()) + '} or ALL',
        dest='datasource',
        type=str.upper,
        help="specify the data source to use, or all")
    parser_latest.add_argument('-d',
                               '--debug',
                               action='store_true',
                               help="enable debug logging")

    parser_history = subparsers.add_parser(
        CMD_HISTORY,
        help="get the historical price of an asset",
        description="Get the historic [asset] price (in GBP) "
        "for the [date] specified. "
        "If no data source [-ds] is given, "
        "the same data source(s) as "
        "'bittytax' are used.")
    parser_history.add_argument('asset',
                                type=str.upper,
                                nargs=1,
                                help="symbol of cryptoasset or fiat currency "
                                "(i.e. BTC/LTC/ETH or EUR/USD)")
    parser_history.add_argument('date',
                                type=validate_date,
                                nargs=1,
                                help="date (YYYY-MM-DD or DD/MM/YYYY)")
    parser_history.add_argument('quantity',
                                type=validate_quantity,
                                nargs='?',
                                help="quantity to price (optional)")
    parser_history.add_argument(
        '-ds',
        choices=datasource_choices(upper=True) + ['ALL'],
        metavar='{' + ', '.join(datasource_choices()) + '} or ALL',
        dest='datasource',
        type=str.upper,
        help="specify the data source to use, or all")
    parser_history.add_argument('-nc',
                                '--nocache',
                                action='store_true',
                                help="bypass data cache")
    parser_history.add_argument('-d',
                                '--debug',
                                action='store_true',
                                help="enable debug logging")

    parser_list = subparsers.add_parser(
        CMD_LIST,
        help="list all assets",
        description='List all assets, or filter by [asset].')
    parser_list.add_argument('asset',
                             type=str,
                             nargs='?',
                             help="symbol of cryptoasset or fiat currency "
                             "(i.e. BTC/LTC/ETH or EUR/USD)")
    parser_list.add_argument('-s',
                             type=str,
                             nargs='+',
                             metavar='STRING',
                             dest='search',
                             help="search assets using STRING")
    parser_list.add_argument('-ds',
                             choices=datasource_choices(upper=True) + ['ALL'],
                             metavar='{' + ', '.join(datasource_choices()) +
                             '} or ALL',
                             dest='datasource',
                             type=str.upper,
                             help="specify the data source to use, or all")
    parser_list.add_argument('-d',
                             '--debug',
                             action='store_true',
                             help="enable debug logging")

    config.args = parser.parse_args()

    if config.args.debug:
        print("%s%s v%s" % (Fore.YELLOW, parser.prog, __version__))
        print("%spython: v%s" % (Fore.GREEN, platform.python_version()))
        print("%ssystem: %s, release: %s" %
              (Fore.GREEN, platform.system(), platform.release()))
        config.output_config()

    if config.args.command in (CMD_LATEST, CMD_HISTORY):
        symbol = config.args.asset[0]
        asset = price = False

        try:
            if config.args.datasource:
                if config.args.command == CMD_HISTORY:
                    assets = AssetData().get_historic_price_ds(
                        symbol, config.args.date[0], config.args.datasource)
                else:
                    assets = AssetData().get_latest_price_ds(
                        symbol, config.args.datasource)
                btc = None
                for asset in assets:
                    if not asset['price']:
                        continue

                    output_ds_price(asset)
                    if asset['quote'] == 'BTC':
                        if btc is None:
                            if config.args.command == CMD_HISTORY:
                                btc = get_historic_btc_price(
                                    config.args.date[0])
                            else:
                                btc = get_latest_btc_price()

                        if btc['price'] is not None:
                            price_ccy = btc['price'] * asset['price']
                            output_ds_price(btc)
                            price = True
                    else:
                        price_ccy = asset['price']
                        price = True

                    output_price(symbol, price_ccy)

                if not assets:
                    asset = False
            else:
                value_asset = ValueAsset(price_tool=True)
                if config.args.command == CMD_HISTORY:
                    price_ccy, name, _ = value_asset.get_historical_price(
                        symbol, config.args.date[0])
                else:
                    price_ccy, name, _ = value_asset.get_latest_price(symbol)

                if price_ccy is not None:
                    output_price(symbol, price_ccy)
                    price = True

                if name is not None:
                    asset = True

        except DataSourceError as e:
            parser.exit("%sERROR%s %s" %
                        (Back.RED + Fore.BLACK, Back.RESET + Fore.RED, e))

        if not asset:
            parser.exit(
                "%sWARNING%s Prices for %s are not supported" %
                (Back.YELLOW + Fore.BLACK, Back.RESET + Fore.YELLOW, symbol))

        if not price:
            if config.args.command == CMD_HISTORY:
                parser.exit(
                    "%sWARNING%s Price for %s on %s is not available" %
                    (Back.YELLOW + Fore.BLACK, Back.RESET + Fore.YELLOW,
                     symbol, config.args.date[0].strftime('%Y-%m-%d')))
            else:
                parser.exit(
                    "%sWARNING%s Current price for %s is not available" %
                    (Back.YELLOW + Fore.BLACK, Back.RESET + Fore.YELLOW,
                     symbol))
    elif config.args.command == CMD_LIST:
        symbol = config.args.asset
        try:
            assets = AssetData().get_assets(symbol, config.args.datasource,
                                            config.args.search)
        except DataSourceError as e:
            parser.exit("%sERROR%s %s" %
                        (Back.RED + Fore.BLACK, Back.RESET + Fore.RED, e))

        if symbol and not assets:
            parser.exit(
                "%sWARNING%s Asset %s not found" %
                (Back.YELLOW + Fore.BLACK, Back.RESET + Fore.YELLOW, symbol))

        if config.args.search and not assets:
            parser.exit("No results found")

        output_assets(assets)
예제 #48
0
 def user_agent(self):
     client_info = '/'.join(('python-yesgraph', __version__))
     language_info = '/'.join(
         (platform.python_implementation(), platform.python_version()))
     platform_info = '/'.join((platform.system(), platform.release()))
     return ' '.join([client_info, language_info, platform_info])
예제 #49
0
    GameClient=ffi.NULL,
    WorldClient=ffi.NULL,
    ClientWorld=ffi.NULL,
    WorldView=ffi.NULL,
    overrideW=0,
    overrideH=0,  # fake values to return from XDL_GetWindowSize
    windowW=0,
    windowH=0,  # current window size
    scaleX=1,
    scaleY=1,  # current window scale
    lastMove=0  # timestamp of last mouse movement
)

refs.VERSION = VERSION
refs.SYSINFO = '{0} v{1} {2} @ {3}'.format(platform.python_implementation(),
                                           platform.python_version(),
                                           platform.architecture()[0],
                                           platform.platform())

refs.config = configparser.ConfigParser()
refs.config.optionxform = str

refs.manager = None

# hooks ######################################################################

ORIGS = {}


@ffi.def_extern()
def hook_DoEvents():
예제 #50
0
 def callback(resp):
     self.assertIn(
         "azsdk-python-ai-textanalytics/{} Python/{} ({})".format(
             VERSION, platform.python_version(), platform.platform()),
         resp.http_request.headers["User-Agent"])
예제 #51
0
        # third level defers computation until the test is called
        # this allows the specific test to fail at test runtime,
        # rather than at decoration time (when the module is imported)
        def inner():
            # fail if the version is too high
            if pvlib_base_version >= parse_version(version):
                pytest.fail('the tested function is scheduled to be '
                            'removed in %s' % version)
            # otherwise return the function to be executed
            else:
                return func()
        return inner
    return wrapper


has_python2 = parse_version(platform.python_version()) < parse_version('3')

platform_is_windows = platform.system() == 'Windows'
skip_windows = pytest.mark.skipif(platform_is_windows,
                                  reason='does not run on windows')

try:
    import scipy
    has_scipy = True
except ImportError:
    has_scipy = False

requires_scipy = pytest.mark.skipif(not has_scipy, reason='requires scipy')


try:
예제 #52
0
    def __init__(self):
        self.logContainers = LogContainers()
        self.logListeners = []
        self.eventListeners = []
        self.NativeLog = True
        self.buffer = ""
        self.data = deque()
        self.maxlength = 5000
        self.ctrl = DummyLogCtrl()
        log = self

        class StdOut:
            def write(self, data):
                log.Write(data, INFO_ICON)
                if eg.debugLevel:
                    try:
                        oldStdOut.write(data)
                    except:
                        oldStdOut.write(data.decode("mbcs"))

        class StdErr:
            def write(self, data):
                log.Write(data, ERROR_ICON)
                if eg.debugLevel:
                    try:
                        oldStdErr.write(data)
                    except:
                        oldStdErr.write(data.decode("mbcs"))

        if eg.startupArguments.isMain:
            sys.stdout = StdOut()
            sys.stderr = StdErr()
        if eg.debugLevel == 2:
            if hasattr(_oldStdErr, "_displayMessage"):
                _oldStdErr._displayMessage = False
        if eg.debugLevel:
            import platform
            import warnings
            warnings.simplefilter('error', UnicodeWarning)
            self.PrintDebugNotice("----------------------------------------")
            self.PrintDebugNotice("        {0} started".format(eg.APP_NAME))
            self.PrintDebugNotice("----------------------------------------")
            self.PrintDebugNotice(eg.APP_NAME, "Version:", eg.Version.string)
            self.PrintDebugNotice("Machine type:", platform.machine())
            self.PrintDebugNotice("Processor:", platform.processor())
            self.PrintDebugNotice("Architecture:", platform.architecture())
            self.PrintDebugNotice("Python:", platform.python_branch(),
                                  platform.python_version(),
                                  platform.python_implementation(),
                                  platform.python_build(),
                                  "[{0}]".format(platform.python_compiler()))
            self.PrintDebugNotice("----------------------------------------")

        # redirect all wxPython error messages to our log
        class MyLog(wx.PyLog):
            def DoLog(self, level, msg, dummyTimestamp):
                if (level >= 6):
                    return
                sys.stderr.write("wxError%d: %s\n" % (level, msg))

        wx.Log.SetActiveTarget(MyLog())
예제 #53
0
def user_agent():
    """
    Return a string representing the user agent.
    """
    data = {
        "installer": {"name": "pip", "version": __version__},
        "python": platform.python_version(),
        "implementation": {
            "name": platform.python_implementation(),
        },
    }

    if data["implementation"]["name"] == 'CPython':
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'PyPy':
        if sys.pypy_version_info.releaselevel == 'final':
            pypy_version_info = sys.pypy_version_info[:3]
        else:
            pypy_version_info = sys.pypy_version_info
        data["implementation"]["version"] = ".".join(
            [str(x) for x in pypy_version_info]
        )
    elif data["implementation"]["name"] == 'Jython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()
    elif data["implementation"]["name"] == 'IronPython':
        # Complete Guess
        data["implementation"]["version"] = platform.python_version()

    if sys.platform.startswith("linux"):
        from pip._vendor import distro
        distro_infos = dict(filter(
            lambda x: x[1],
            zip(["name", "version", "id"], distro.linux_distribution()),
        ))
        libc = dict(filter(
            lambda x: x[1],
            zip(["lib", "version"], libc_ver()),
        ))
        if libc:
            distro_infos["libc"] = libc
        if distro_infos:
            data["distro"] = distro_infos

    if sys.platform.startswith("darwin") and platform.mac_ver()[0]:
        data["distro"] = {"name": "macOS", "version": platform.mac_ver()[0]}

    if platform.system():
        data.setdefault("system", {})["name"] = platform.system()

    if platform.release():
        data.setdefault("system", {})["release"] = platform.release()

    if platform.machine():
        data["cpu"] = platform.machine()

    if has_tls():
        import _ssl as ssl
        data["openssl_version"] = ssl.OPENSSL_VERSION

    setuptools_version = get_installed_version("setuptools")
    if setuptools_version is not None:
        data["setuptools_version"] = setuptools_version

    # Use None rather than False so as not to give the impression that
    # pip knows it is not being run under CI.  Rather, it is a null or
    # inconclusive result.  Also, we include some value rather than no
    # value to make it easier to know that the check has been run.
    data["ci"] = True if looks_like_ci() else None

    user_data = os.environ.get("PIP_USER_AGENT_USER_DATA")
    if user_data is not None:
        data["user_data"] = user_data

    return "{data[installer][name]}/{data[installer][version]} {json}".format(
        data=data,
        json=json.dumps(data, separators=(",", ":"), sort_keys=True),
    )
예제 #54
0
def setup_package():

    # TODO: Require Python 3.8 for PyPy when PyPy3.8 is ready
    # https://github.com/conda-forge/conda-forge-pinning-feedstock/issues/2089
    if platform.python_implementation() == "PyPy":
        python_requires = ">=3.7"
        required_python_version = (3, 7)
    else:
        python_requires = ">=3.8"
        required_python_version = (3, 8)

    metadata = dict(
        name=DISTNAME,
        maintainer=MAINTAINER,
        maintainer_email=MAINTAINER_EMAIL,
        description=DESCRIPTION,
        license=LICENSE,
        url=URL,
        download_url=DOWNLOAD_URL,
        project_urls=PROJECT_URLS,
        version=VERSION,
        long_description=LONG_DESCRIPTION,
        classifiers=[
            "Intended Audience :: Science/Research",
            "Intended Audience :: Developers",
            "License :: OSI Approved",
            "Programming Language :: C",
            "Programming Language :: Python",
            "Topic :: Software Development",
            "Topic :: Scientific/Engineering",
            "Development Status :: 5 - Production/Stable",
            "Operating System :: Microsoft :: Windows",
            "Operating System :: POSIX",
            "Operating System :: Unix",
            "Operating System :: MacOS",
            "Programming Language :: Python :: 3",
            "Programming Language :: Python :: 3.8",
            "Programming Language :: Python :: 3.9",
            "Programming Language :: Python :: 3.10",
            "Programming Language :: Python :: Implementation :: CPython",
            "Programming Language :: Python :: Implementation :: PyPy",
        ],
        cmdclass=cmdclass,
        python_requires=python_requires,
        install_requires=min_deps.tag_to_packages["install"],
        package_data={"": ["*.pxd"]},
        **extra_setuptools_args,
    )

    commands = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
    if all(command in ("egg_info", "dist_info", "clean", "check")
           for command in commands):
        # These actions are required to succeed without Numpy for example when
        # pip is used to install Scikit-learn when Numpy is not yet present in
        # the system.

        # These commands use setup from setuptools
        from setuptools import setup

        metadata["version"] = VERSION
    else:
        if sys.version_info < required_python_version:
            required_version = "%d.%d" % required_python_version
            raise RuntimeError(
                "Scikit-learn requires Python %s or later. The current"
                " Python version is %s installed in %s." %
                (required_version, platform.python_version(), sys.executable))

        check_package_status("numpy", min_deps.NUMPY_MIN_VERSION)

        check_package_status("scipy", min_deps.SCIPY_MIN_VERSION)

        # These commands require the setup from numpy.distutils because they
        # may use numpy.distutils compiler classes.
        from numpy.distutils.core import setup

        # Monkeypatches CCompiler.spawn to prevent random wheel build errors on Windows
        # The build errors on Windows was because msvccompiler spawn was not threadsafe
        # This fixed can be removed when we build with numpy >= 1.22.2 on Windows.
        # https://github.com/pypa/distutils/issues/5
        # https://github.com/scikit-learn/scikit-learn/issues/22310
        # https://github.com/numpy/numpy/pull/20640
        from numpy.distutils.ccompiler import replace_method
        from distutils.ccompiler import CCompiler
        from sklearn.externals._numpy_compiler_patch import CCompiler_spawn

        replace_method(CCompiler, "spawn", CCompiler_spawn)

        metadata["configuration"] = configuration

    setup(**metadata)
예제 #55
0
    def Qui_update(self):
        self.logoapp = QtWidgets.QLabel('')
        self.logoapp.setPixmap(QtGui.QPixmap(self.smallIcon).scaled(64,64))
        self.form = QtWidgets.QFormLayout()
        self.form2 = QtWidgets.QVBoxLayout()
        self.form.addRow(self.logoapp,QtWidgets.QLabel('<h2>{0} {1}-{2}</h2>'.format(self.name, self.version, self.build)))
        self.tabwid = QtWidgets.QTabWidget(self)
        self.TabAbout = QtWidgets.QWidget(self)
        self.TabVersion = QtWidgets.QWidget(self)
        self.TabChangelog = QtWidgets.QWidget(self)
        self.cmdClose = QtWidgets.QPushButton("Close")
        self.cmdClose.setFixedWidth(90)
        self.cmdClose.setIcon(QtGui.QIcon('images/close.png'))
        self.cmdClose.clicked.connect(self.close)

        self.formAbout = QtWidgets.QFormLayout()
        self.formVersion = QtWidgets.QFormLayout()
        self.formChange = QtWidgets.QFormLayout()

        # About section
        self.formAbout.addRow(self.desc)
        self.formAbout.addRow(QtWidgets.QLabel('<br>'))
        self.formAbout.addRow(QtWidgets.QLabel('Last Update:'))
        self.formAbout.addRow(QtWidgets.QLabel(self.update + '<br>'))
        self.formAbout.addRow(QtWidgets.QLabel('Feedback:'))
        for link in self.links:
            self.formAbout.addRow(QtWidgets.QLabel('<a href="{0}">{0}</a>'.format(link)))
        for email in self.emails:
            self.formAbout.addRow(QtWidgets.QLabel(email))
        self.formAbout.addRow(QtWidgets.QLabel('<br>'))
        self.formAbout.addRow(QtWidgets.QLabel(self.copyright + ' ' + self.author))
        self.gnu = QtWidgets.QLabel('<a href="link">License: GNU General Public License Version</a><br>')
        self.gnu.linkActivated.connect(self.link)
        self.formAbout.addRow(self.gnu)
        self.TabAbout.setLayout(self.formAbout)

        # Version Section
        self.formVersion.addRow(QtWidgets.QLabel('<strong>Version: {0}-{1}</strong><br>'.format(self.version, self.build)))
        self.formVersion.addRow(QtWidgets.QLabel('Using:'))
        import platform
        python_version = platform.python_version()
        self.formVersion.addRow(QtWidgets.QLabel('''
        <ul>
          <li>QTVersion: {0}</li>
          <li>Python: {1}</li>
        </ul>'''.format(QtCore.QT_VERSION_STR,python_version)))
        self.TabVersion.setLayout(self.formVersion)

        # Changelog Section
        self.formChange.addRow(ChangeLog(qss = self.qss))
        self.TabChangelog.setLayout(self.formChange)

        self.tabwid.addTab(self.TabAbout,'About')
        self.tabwid.addTab(self.TabVersion,'Version')
        self.tabwid.addTab(self.TabChangelog,'ChangeLog')
        self.form.addRow(self.tabwid)
        self.form2.addWidget(QtWidgets.QLabel('<br>'))
        self.form2.addWidget(self.cmdClose, alignment = Qt.AlignCenter)
        self.form.addRow(self.form2)
        self.Main.addLayout(self.form)
        self.setLayout(self.Main)
예제 #56
0
class CloudkmsV1(base_api.BaseApiClient):
    """Generated client library for service cloudkms version v1."""

    MESSAGES_MODULE = messages
    BASE_URL = u'https://cloudkms.googleapis.com/'

    _PACKAGE = u'cloudkms'
    _SCOPES = [u'https://www.googleapis.com/auth/cloud-platform']
    _VERSION = u'v1'
    _CLIENT_ID = 'nomatter'
    _CLIENT_SECRET = 'nomatter'
    _USER_AGENT = 'apitools gsutil/%s Python/%s (%s)' % (
        gslib.VERSION, platform.python_version(), sys.platform)
    if system_util.InvokedViaCloudSdk():
        _USER_AGENT += ' google-cloud-sdk'
        if system_util.CloudSdkVersion():
            _USER_AGENT += '/%s' % system_util.CloudSdkVersion()
    if MetricsCollector.IsDisabled():
        _USER_AGENT += ' analytics/disabled'
    else:
        _USER_AGENT += ' analytics/enabled'
    _CLIENT_CLASS_NAME = u'CloudkmsV1'
    _URL_VERSION = u'v1'
    _API_KEY = None

    def __init__(self,
                 url='',
                 credentials=None,
                 get_credentials=True,
                 http=None,
                 model=None,
                 log_request=False,
                 log_response=False,
                 credentials_args=None,
                 default_global_params=None,
                 additional_http_headers=None):
        """Create a new cloudkms handle."""
        url = url or self.BASE_URL
        super(CloudkmsV1,
              self).__init__(url,
                             credentials=credentials,
                             get_credentials=get_credentials,
                             http=http,
                             model=model,
                             log_request=log_request,
                             log_response=log_response,
                             credentials_args=credentials_args,
                             default_global_params=default_global_params,
                             additional_http_headers=additional_http_headers)
        self.projects_locations_keyRings_cryptoKeys_cryptoKeyVersions = self.ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService(
            self)
        self.projects_locations_keyRings_cryptoKeys = self.ProjectsLocationsKeyRingsCryptoKeysService(
            self)
        self.projects_locations_keyRings = self.ProjectsLocationsKeyRingsService(
            self)
        self.projects_locations = self.ProjectsLocationsService(self)
        self.projects = self.ProjectsService(self)

    class ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService(
            base_api.BaseApiService):
        """Service class for the projects_locations_keyRings_cryptoKeys_cryptoKeyVersions resource."""

        _NAME = u'projects_locations_keyRings_cryptoKeys_cryptoKeyVersions'

        def __init__(self, client):
            super(
                CloudkmsV1.
                ProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsService,
                self).__init__(client)
            self._upload_configs = {}

        def Create(self, request, global_params=None):
            """Create a new CryptoKeyVersion in a CryptoKey.

The server will assign the next sequential id. If unset,
state will be set to
ENABLED.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsCreateRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKeyVersion) The response message.
      """
            config = self.GetMethodConfig('Create')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Create.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.create',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[],
            relative_path=u'v1/{+parent}/cryptoKeyVersions',
            request_field=u'cryptoKeyVersion',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsCreateRequest',
            response_type_name=u'CryptoKeyVersion',
            supports_download=False,
        )

        def Destroy(self, request, global_params=None):
            """Schedule a CryptoKeyVersion for destruction.

Upon calling this method, CryptoKeyVersion.state will be set to
DESTROY_SCHEDULED
and destroy_time will be set to a time 24
hours in the future, at which point the state
will be changed to
DESTROYED, and the key
material will be irrevocably destroyed.

Before the destroy_time is reached,
RestoreCryptoKeyVersion may be called to reverse the process.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsDestroyRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKeyVersion) The response message.
      """
            config = self.GetMethodConfig('Destroy')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Destroy.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions/{cryptoKeyVersionsId}:destroy',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.destroy',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}:destroy',
            request_field=u'destroyCryptoKeyVersionRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsDestroyRequest',
            response_type_name=u'CryptoKeyVersion',
            supports_download=False,
        )

        def Get(self, request, global_params=None):
            """Returns metadata for a given CryptoKeyVersion.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKeyVersion) The response message.
      """
            config = self.GetMethodConfig('Get')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Get.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions/{cryptoKeyVersionsId}',
            http_method=u'GET',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.get',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsGetRequest',
            response_type_name=u'CryptoKeyVersion',
            supports_download=False,
        )

        def List(self, request, global_params=None):
            """Lists CryptoKeyVersions.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (ListCryptoKeyVersionsResponse) The response message.
      """
            config = self.GetMethodConfig('List')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        List.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions',
            http_method=u'GET',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.list',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[u'pageSize', u'pageToken'],
            relative_path=u'v1/{+parent}/cryptoKeyVersions',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsListRequest',
            response_type_name=u'ListCryptoKeyVersionsResponse',
            supports_download=False,
        )

        def Patch(self, request, global_params=None):
            """Update a CryptoKeyVersion's metadata.

state may be changed between
ENABLED and
DISABLED using this
method. See DestroyCryptoKeyVersion and RestoreCryptoKeyVersion to
move between other states.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsPatchRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKeyVersion) The response message.
      """
            config = self.GetMethodConfig('Patch')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Patch.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions/{cryptoKeyVersionsId}',
            http_method=u'PATCH',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.patch',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[u'updateMask'],
            relative_path=u'v1/{+name}',
            request_field=u'cryptoKeyVersion',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsPatchRequest',
            response_type_name=u'CryptoKeyVersion',
            supports_download=False,
        )

        def Restore(self, request, global_params=None):
            """Restore a CryptoKeyVersion in the.
DESTROY_SCHEDULED,
state.

Upon restoration of the CryptoKeyVersion, state
will be set to DISABLED,
and destroy_time will be cleared.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRestoreRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKeyVersion) The response message.
      """
            config = self.GetMethodConfig('Restore')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Restore.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}/cryptoKeyVersions/{cryptoKeyVersionsId}:restore',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.cryptoKeyVersions.restore',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}:restore',
            request_field=u'restoreCryptoKeyVersionRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersionsRestoreRequest',
            response_type_name=u'CryptoKeyVersion',
            supports_download=False,
        )

    class ProjectsLocationsKeyRingsCryptoKeysService(base_api.BaseApiService):
        """Service class for the projects_locations_keyRings_cryptoKeys resource."""

        _NAME = u'projects_locations_keyRings_cryptoKeys'

        def __init__(self, client):
            super(CloudkmsV1.ProjectsLocationsKeyRingsCryptoKeysService,
                  self).__init__(client)
            self._upload_configs = {}

        def Create(self, request, global_params=None):
            """Create a new CryptoKey within a KeyRing.

CryptoKey.purpose is required.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKey) The response message.
      """
            config = self.GetMethodConfig('Create')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Create.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.create',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[u'cryptoKeyId'],
            relative_path=u'v1/{+parent}/cryptoKeys',
            request_field=u'cryptoKey',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysCreateRequest',
            response_type_name=u'CryptoKey',
            supports_download=False,
        )

        def Decrypt(self, request, global_params=None):
            """Decrypts data that was protected by Encrypt.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (DecryptResponse) The response message.
      """
            config = self.GetMethodConfig('Decrypt')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Decrypt.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:decrypt',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.decrypt',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}:decrypt',
            request_field=u'decryptRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysDecryptRequest',
            response_type_name=u'DecryptResponse',
            supports_download=False,
        )

        def Encrypt(self, request, global_params=None):
            """Encrypts data, so that it can only be recovered by a call to Decrypt.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (EncryptResponse) The response message.
      """
            config = self.GetMethodConfig('Encrypt')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Encrypt.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:encrypt',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.encrypt',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}:encrypt',
            request_field=u'encryptRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysEncryptRequest',
            response_type_name=u'EncryptResponse',
            supports_download=False,
        )

        def Get(self, request, global_params=None):
            """Returns metadata for a given CryptoKey, as well as its.
primary CryptoKeyVersion.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKey) The response message.
      """
            config = self.GetMethodConfig('Get')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Get.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.keyRings.cryptoKeys.get',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysGetRequest',
            response_type_name=u'CryptoKey',
            supports_download=False,
        )

        def GetIamPolicy(self, request, global_params=None):
            """Gets the access control policy for a resource.
Returns an empty policy if the resource exists and does not have a policy
set.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (Policy) The response message.
      """
            config = self.GetMethodConfig('GetIamPolicy')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:getIamPolicy',
            http_method=u'GET',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.getIamPolicy',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:getIamPolicy',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysGetIamPolicyRequest',
            response_type_name=u'Policy',
            supports_download=False,
        )

        def List(self, request, global_params=None):
            """Lists CryptoKeys.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysListRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (ListCryptoKeysResponse) The response message.
      """
            config = self.GetMethodConfig('List')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        List.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.keyRings.cryptoKeys.list',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[u'pageSize', u'pageToken'],
            relative_path=u'v1/{+parent}/cryptoKeys',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysListRequest',
            response_type_name=u'ListCryptoKeysResponse',
            supports_download=False,
        )

        def Patch(self, request, global_params=None):
            """Update a CryptoKey.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKey) The response message.
      """
            config = self.GetMethodConfig('Patch')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Patch.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}',
            http_method=u'PATCH',
            method_id=u'cloudkms.projects.locations.keyRings.cryptoKeys.patch',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[u'updateMask'],
            relative_path=u'v1/{+name}',
            request_field=u'cryptoKey',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysPatchRequest',
            response_type_name=u'CryptoKey',
            supports_download=False,
        )

        def SetIamPolicy(self, request, global_params=None):
            """Sets the access control policy on the specified resource. Replaces any.
existing policy.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (Policy) The response message.
      """
            config = self.GetMethodConfig('SetIamPolicy')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:setIamPolicy',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.setIamPolicy',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:setIamPolicy',
            request_field=u'setIamPolicyRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysSetIamPolicyRequest',
            response_type_name=u'Policy',
            supports_download=False,
        )

        def TestIamPermissions(self, request, global_params=None):
            """Returns permissions that a caller has on the specified resource.
If the resource does not exist, this will return an empty set of
permissions, not a NOT_FOUND error.

Note: This operation is designed to be used for building permission-aware
UIs and command-line tools, not for authorization checking. This operation
may "fail open" without warning.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysTestIamPermissionsRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (TestIamPermissionsResponse) The response message.
      """
            config = self.GetMethodConfig('TestIamPermissions')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:testIamPermissions',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.testIamPermissions',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:testIamPermissions',
            request_field=u'testIamPermissionsRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysTestIamPermissionsRequest',
            response_type_name=u'TestIamPermissionsResponse',
            supports_download=False,
        )

        def UpdatePrimaryVersion(self, request, global_params=None):
            """Update the version of a CryptoKey that will be used in Encrypt.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (CryptoKey) The response message.
      """
            config = self.GetMethodConfig('UpdatePrimaryVersion')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        UpdatePrimaryVersion.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}/cryptoKeys/{cryptoKeysId}:updatePrimaryVersion',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.cryptoKeys.updatePrimaryVersion',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}:updatePrimaryVersion',
            request_field=u'updateCryptoKeyPrimaryVersionRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCryptoKeysUpdatePrimaryVersionRequest',
            response_type_name=u'CryptoKey',
            supports_download=False,
        )

    class ProjectsLocationsKeyRingsService(base_api.BaseApiService):
        """Service class for the projects_locations_keyRings resource."""

        _NAME = u'projects_locations_keyRings'

        def __init__(self, client):
            super(CloudkmsV1.ProjectsLocationsKeyRingsService,
                  self).__init__(client)
            self._upload_configs = {}

        def Create(self, request, global_params=None):
            """Create a new KeyRing in a given Project and Location.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsCreateRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (KeyRing) The response message.
      """
            config = self.GetMethodConfig('Create')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Create.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings',
            http_method=u'POST',
            method_id=u'cloudkms.projects.locations.keyRings.create',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[u'keyRingId'],
            relative_path=u'v1/{+parent}/keyRings',
            request_field=u'keyRing',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsCreateRequest',
            response_type_name=u'KeyRing',
            supports_download=False,
        )

        def Get(self, request, global_params=None):
            """Returns metadata for a given KeyRing.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsGetRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (KeyRing) The response message.
      """
            config = self.GetMethodConfig('Get')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Get.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.keyRings.get',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}',
            request_field='',
            request_type_name=u'CloudkmsProjectsLocationsKeyRingsGetRequest',
            response_type_name=u'KeyRing',
            supports_download=False,
        )

        def GetIamPolicy(self, request, global_params=None):
            """Gets the access control policy for a resource.
Returns an empty policy if the resource exists and does not have a policy
set.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsGetIamPolicyRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (Policy) The response message.
      """
            config = self.GetMethodConfig('GetIamPolicy')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}:getIamPolicy',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.keyRings.getIamPolicy',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:getIamPolicy',
            request_field='',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsGetIamPolicyRequest',
            response_type_name=u'Policy',
            supports_download=False,
        )

        def List(self, request, global_params=None):
            """Lists KeyRings.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsListRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (ListKeyRingsResponse) The response message.
      """
            config = self.GetMethodConfig('List')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        List.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.keyRings.list',
            ordered_params=[u'parent'],
            path_params=[u'parent'],
            query_params=[u'pageSize', u'pageToken'],
            relative_path=u'v1/{+parent}/keyRings',
            request_field='',
            request_type_name=u'CloudkmsProjectsLocationsKeyRingsListRequest',
            response_type_name=u'ListKeyRingsResponse',
            supports_download=False,
        )

        def SetIamPolicy(self, request, global_params=None):
            """Sets the access control policy on the specified resource. Replaces any.
existing policy.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsSetIamPolicyRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (Policy) The response message.
      """
            config = self.GetMethodConfig('SetIamPolicy')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}:setIamPolicy',
            http_method=u'POST',
            method_id=u'cloudkms.projects.locations.keyRings.setIamPolicy',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:setIamPolicy',
            request_field=u'setIamPolicyRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsSetIamPolicyRequest',
            response_type_name=u'Policy',
            supports_download=False,
        )

        def TestIamPermissions(self, request, global_params=None):
            """Returns permissions that a caller has on the specified resource.
If the resource does not exist, this will return an empty set of
permissions, not a NOT_FOUND error.

Note: This operation is designed to be used for building permission-aware
UIs and command-line tools, not for authorization checking. This operation
may "fail open" without warning.

      Args:
        request: (CloudkmsProjectsLocationsKeyRingsTestIamPermissionsRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (TestIamPermissionsResponse) The response message.
      """
            config = self.GetMethodConfig('TestIamPermissions')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=
            u'v1/projects/{projectsId}/locations/{locationsId}/keyRings/{keyRingsId}:testIamPermissions',
            http_method=u'POST',
            method_id=
            u'cloudkms.projects.locations.keyRings.testIamPermissions',
            ordered_params=[u'resource'],
            path_params=[u'resource'],
            query_params=[],
            relative_path=u'v1/{+resource}:testIamPermissions',
            request_field=u'testIamPermissionsRequest',
            request_type_name=
            u'CloudkmsProjectsLocationsKeyRingsTestIamPermissionsRequest',
            response_type_name=u'TestIamPermissionsResponse',
            supports_download=False,
        )

    class ProjectsLocationsService(base_api.BaseApiService):
        """Service class for the projects_locations resource."""

        _NAME = u'projects_locations'

        def __init__(self, client):
            super(CloudkmsV1.ProjectsLocationsService, self).__init__(client)
            self._upload_configs = {}

        def Get(self, request, global_params=None):
            """Get information about a location.

      Args:
        request: (CloudkmsProjectsLocationsGetRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (Location) The response message.
      """
            config = self.GetMethodConfig('Get')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        Get.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=u'v1/projects/{projectsId}/locations/{locationsId}',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.get',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[],
            relative_path=u'v1/{+name}',
            request_field='',
            request_type_name=u'CloudkmsProjectsLocationsGetRequest',
            response_type_name=u'Location',
            supports_download=False,
        )

        def List(self, request, global_params=None):
            """Lists information about the supported locations for this service.

      Args:
        request: (CloudkmsProjectsLocationsListRequest) input message
        global_params: (StandardQueryParameters, default: None) global arguments
      Returns:
        (ListLocationsResponse) The response message.
      """
            config = self.GetMethodConfig('List')
            return self._RunMethod(config,
                                   request,
                                   global_params=global_params)

        List.method_config = lambda: base_api.ApiMethodInfo(
            flat_path=u'v1/projects/{projectsId}/locations',
            http_method=u'GET',
            method_id=u'cloudkms.projects.locations.list',
            ordered_params=[u'name'],
            path_params=[u'name'],
            query_params=[u'filter', u'pageSize', u'pageToken'],
            relative_path=u'v1/{+name}/locations',
            request_field='',
            request_type_name=u'CloudkmsProjectsLocationsListRequest',
            response_type_name=u'ListLocationsResponse',
            supports_download=False,
        )

    class ProjectsService(base_api.BaseApiService):
        """Service class for the projects resource."""

        _NAME = u'projects'

        def __init__(self, client):
            super(CloudkmsV1.ProjectsService, self).__init__(client)
            self._upload_configs = {}
예제 #57
0
def message():
    print('The python version is {}'.format(platform.python_version()))
예제 #58
0
"""
# AutoGator

A software package for camera-assisted motion control of PIC chip interrogation
platforms.
"""

import os
import pathlib
import platform
import sys
from datetime import date

if sys.version_info < (3, 7, 0):
    raise Exception("autogator requires Python 3.7+ (version " +
                    platform.python_version() + " detected).")

__name__ = "AutoGator"
__author__ = "CamachoLab"
__copyright__ = "Copyright 2022, CamachoLab"
__version__ = "0.3.0"
__license__ = "GPLv3+"
__maintainer__ = "Sequoia Ploeg"
__maintainer_email__ = "*****@*****.**"
__status__ = "Development"  # "Production"
__project_url__ = "https://github.com/BYUCamachoLab/autogator"
__forum_url__ = "https://github.com/BYUCamachoLab/autogator/issues"
__website_url__ = "https://camacholab.byu.edu/"

import warnings
warnings.filterwarnings("default", category=DeprecationWarning)
예제 #59
0
 def get_python_version(self) -> str:
     return platform.python_version()
예제 #60
0
파일: console.py 프로젝트: aroberge/ideas
Adaptation of Python's console found in code.py so that it can be
used with import hooks.
"""

import ast
import platform
import os
import sys

from code import InteractiveConsole

from . import __version__

BANNER = "Ideas Console version {}. [Python version: {}]\n".format(
    __version__, platform.python_version())
_CONFIG = {}
CONSOLE_NAME = "IdeasConsole"


def configure(**kwargs):
    """Configures various defaults to be used by the console"""
    _CONFIG.update(kwargs)


class IdeasConsole(InteractiveConsole):
    """An interactive console that works with source transformations,
    AST transformations and Bytecode transformations.

    It should not need to be instantiated directly.
    """