Пример #1
0
Файл: node.py Проект: lynshi/CCF
 def version_after(self, version):
     rc, _ = version_rc(version)
     if rc is None or self.version is None:
         return True
     self_rc, self_num_rc_tkns = version_rc(self.version)
     ver = Version(strip_version(version))
     self_ver = Version(strip_version(self.version))
     return self_ver > ver or (self_ver == ver and
                               (not self_rc or self_rc > rc or
                                (self_rc == rc and self_num_rc_tkns > 3)))
Пример #2
0
    def _parse_version(self, value):
        """Parses `version` option value.

        :param value:
        :rtype: str

        """
        version = self._parse_file(value, self.root_dir)

        if version != value:
            version = version.strip()
            # Be strict about versions loaded from file because it's easy to
            # accidentally include newlines and other unintended content
            try:
                Version(version)
            except InvalidVersion:
                tmpl = (
                    'Version loaded from {value} does not '
                    'comply with PEP 440: {version}'
                )
                raise DistutilsOptionError(tmpl.format(**locals()))

            return version

        return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))
Пример #3
0
    def _parse_version(self, value):
        """Parses `version` option value.

        :param value:
        :rtype: str

        """
        version = self._parse_file(value)

        if version != value:
            version = version.strip()
            # Be strict about versions loaded from file because it's easy to
            # accidentally include newlines and other unintended content
            try:
                Version(version)
            except InvalidVersion:
                tmpl = ('Version loaded from {value} does not '
                        'comply with PEP 440: {version}')
                raise DistutilsOptionError(tmpl.format(**locals()))

            return version

        version = self._parse_attr(value, self.package_dir)

        if callable(version):
            version = version()

        if not isinstance(version, str):
            if hasattr(version, '__iter__'):
                version = '.'.join(map(str, version))
            else:
                version = '%s' % version

        return version
Пример #4
0
def resolve(req: Requirement) -> metadata.Distribution:
    """
    Resolve the requirement to its distribution.

    Ignore exception detail for Python 3.9 compatibility.

    >>> resolve(Requirement('pytest<3'))  # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    importlib.metadata.PackageNotFoundError: No package metadata was found for pytest<3
    """
    dist = metadata.distribution(req.name)
    if not req.specifier.contains(Version(dist.version), prereleases=True):
        raise metadata.PackageNotFoundError(str(req))
    dist.extras = req.extras  # type: ignore
    return dist
Пример #5
0
 def run(self):
     if self.args:
         version = self.args[0]
         # Ensure it's valid.
         Version(version)
     else:
         version = get_version()
         if version is None:
             sys.exit(1)
     log.info('patching version to %s', version)
     version_file = os.path.join('plover', '__init__.py')
     with open(version_file, 'r') as fp:
         contents = fp.read().split('\n')
     contents = [re.sub(r'^__version__ = .*$', "__version__ = '%s'" % version, line)
                 for line in contents]
     with open(version_file, 'w') as fp:
         fp.write('\n'.join(contents))
Пример #6
0
def to_python_version(original):
    unprefixed = remove_prefix(original, "ccf-")

    # Try to parse this as a Version (with automatic normalisation).
    # If it fails, try making part of the suffix a local version specifier (+foo).
    # Keep expanding this suffix until you get a valid version, or run out of attempts.
    next_attempt = unprefixed
    next_replace = len(next_attempt)
    while True:
        try:
            version = Version(next_attempt)
            return version
        except InvalidVersion:
            next_replace = unprefixed.rfind("-", 0, next_replace)
            if next_replace == -1:
                break
            next_attempt = replace_char(unprefixed, next_replace, "+")

    raise ValueError(f"Cannot convert '{original}' to a Version")
Пример #7
0
def gen_ver_build(rawversion,
                  branch,
                  build,
                  masterlabel='main',
                  masterbuild=0):
    """Returns <version>, <buildnum>, <channel>"""
    def calc():
        if not VALIDVER.match(rawversion):
            return rawversion, build, ''
        if not branch:
            return rawversion + 'a0', DYNBUILDNUM, ''
        if branch == 'develop':
            return "{}a{}".format(
                rawversion, btype2index(branch)), build or DYNBUILDNUM, branch
        try:
            if branch.startswith('develop_'):
                btype = FORKED
                bname = branch.split('_', 1)[1]
            else:
                btype, bname = branch.split("/")
        except ValueError:
            btype, bname = '', ''
        assert bname not in RESERVED
        if branch == 'master' or btype == 'support':
            return rawversion, masterbuild, masterlabel
        if build and btype in ('release', 'hotfix'):
            return '{}rc{}'.format(rawversion, build), masterbuild, btype
        bindex = btype2index(btype)
        if btype == FORKED:
            return ('{}a{}+{}'.format(rawversion, bindex, bname), build
                    or DYNBUILDNUM, bname)
        return ('{}a{}'.format(rawversion, bindex), build
                or DYNBUILDNUM, btype if bindex else '')

    tver, tbuild, tlab = calc()
    # Version normalization
    try:
        parsedver = Version(tver)
        tver = str(parsedver)
    except InvalidVersion:
        warnings.warn("Invalid version %s" % tver)
    return tver, tbuild, tlab
Пример #8
0
    def create_volume(self):
        if self._actor is None:
            if int(ses.Session().rendering) == 0:
                self._volume_mapper = vtkFixedPointVolumeRayCastMapper()
                #volume_mapper.AutoAdjustSampleDistancesOff()
                self._volume_mapper.IntermixIntersectingGeometryOn()
                pix_diag = 2.0
                self._volume_mapper.SetImageSampleDistance(0.25)
                self._volume_mapper.SetSampleDistance(pix_diag / 5.0)
            else:
                self._volume_mapper = vtkGPUVolumeRayCastMapper()
                self._volume_mapper.UseJitteringOn()

                if Version(vtkVersion().GetVTKVersion()) > Version('8.0'):
                    self._volume_mapper.SetBlendModeToIsoSurface()

            #  else:
            #  isosurfaceFunc = vtk.vtkVolumeRayCastIsosurfaceFunction()
            #  isosurfaceFunc.SetIsoValue(127)

            #  self._volume_mapper = vtk.vtkVolumeRayCastMapper()
            #  self._volume_mapper.SetVolumeRayCastFunction(isosurfaceFunc)

            self._flip = vtkImageFlip()
            self._flip.SetInputData(self.mask.imagedata)
            self._flip.SetFilteredAxis(1)
            self._flip.FlipAboutOriginOn()

            self._volume_mapper.SetInputConnection(self._flip.GetOutputPort())
            self._volume_mapper.Update()

            r, g, b = self.colour

            self._color_transfer = vtkColorTransferFunction()
            self._color_transfer.RemoveAllPoints()
            self._color_transfer.AddRGBPoint(0.0, 0, 0, 0)
            self._color_transfer.AddRGBPoint(254.0, r, g, b)
            self._color_transfer.AddRGBPoint(255.0, r, g, b)

            self._piecewise_function = vtkPiecewiseFunction()
            self._piecewise_function.RemoveAllPoints()
            self._piecewise_function.AddPoint(0.0, 0.0)
            self._piecewise_function.AddPoint(127, 1.0)

            self._volume_property = vtkVolumeProperty()
            self._volume_property.SetColor(self._color_transfer)
            self._volume_property.SetScalarOpacity(self._piecewise_function)
            self._volume_property.ShadeOn()
            self._volume_property.SetInterpolationTypeToLinear()
            self._volume_property.SetSpecular(0.75)
            self._volume_property.SetSpecularPower(2)

            if not self._volume_mapper.IsA("vtkGPUVolumeRayCastMapper"):
                self._volume_property.SetScalarOpacityUnitDistance(pix_diag)
            else:
                if Version(vtkVersion().GetVTKVersion()) > Version('8.0'):
                    self._volume_property.GetIsoSurfaceValues().SetValue(
                        0, 127)

            self._actor = vtkVolume()
            self._actor.SetMapper(self._volume_mapper)
            self._actor.SetProperty(self._volume_property)
            self._actor.Update()
Пример #9
0
def UpdateCheck():
    try:
        from urllib.parse import urlencode
        from urllib.request import urlopen, Request
        from urllib.error import HTTPError
    except ImportError:
        from urllib import urlencode
        from urllib2 import urlopen, Request, HTTPError

    import wx
    import invesalius.session as ses

    def _show_update_info():
        from invesalius.gui import dialogs
        msg = _(
            "A new version of InVesalius is available. Do you want to open the download website now?"
        )
        title = _("Invesalius Update")
        msgdlg = dialogs.UpdateMessageDialog(url)
        #if (msgdlg.Show()==wx.ID_YES):
        #wx.LaunchDefaultBrowser(url)
        msgdlg.Show()
        #msgdlg.Destroy()

    print("Checking updates...")

    # Check if there is a language set
    #import invesalius.i18n as i18n    import invesalius.session as ses
    session = ses.Session()
    install_lang = 0
    lang = session.GetLanguage()
    random_id = session.GetRandomId()
    if lang:
        # Fetch update data from server
        import invesalius.constants as const
        url = "https://www.cti.gov.br/dt3d/invesalius/update/checkupdate.php"
        headers = {
            'User-Agent': 'Mozilla/5.0 (compatible; MSIE 5.5; Windows NT)'
        }
        data = {
            'update_protocol_version': '1',
            'invesalius_version': const.INVESALIUS_VERSION,
            'platform': sys.platform,
            'architecture': platform.architecture()[0],
            'language': lang,
            'random_id': random_id
        }
        data = urlencode(data).encode('utf8')
        req = Request(url, data, headers)
        try:
            response = urlopen(req, timeout=10)
        except:
            return
        last = response.readline().rstrip().decode('utf8')
        url = response.readline().rstrip().decode('utf8')

        try:
            last_ver = Version(last)
            actual_ver = Version(const.INVESALIUS_VERSION)
        except (ValueError, AttributeError):
            return

        if last_ver > actual_ver:
            print("  ...New update found!!! -> version:",
                  last)  #, ", url=",url
            wx.CallAfter(wx.CallLater, 1000, _show_update_info)
Пример #10
0
def get_version_from_tag_name(tag_name):
    assert is_release_tag(tag_name), tag_name
    return Version(strip_release_tag_name(tag_name))
Пример #11
0
Файл: node.py Проект: lynshi/CCF
    def __init__(
        self,
        local_node_id,
        host,
        binary_dir=".",
        library_dir=".",
        debug=False,
        perf=False,
        node_port=0,
        version=None,
        node_data_json_file=None,
    ):
        self.local_node_id = local_node_id
        self.binary_dir = binary_dir
        self.library_dir = library_dir
        self.debug = debug
        self.perf = perf
        self.remote = None
        self.network_state = NodeNetworkState.stopped
        self.common_dir = None
        self.suspended = False
        self.node_id = None
        self.node_client_host = None
        # Note: Do not modify host argument as it may be passed to multiple
        # nodes or networks
        self.host = copy.deepcopy(host)
        self.version = version
        self.major_version = (Version(strip_version(self.version)).release[0]
                              if self.version is not None else None)
        self.consensus = None
        self.certificate_valid_from = None
        self.certificate_validity_days = None
        self.initial_node_data_json_file = node_data_json_file

        if os.getenv("CONTAINER_NODES"):
            self.remote_shim = infra.remote_shim.DockerShim
        else:
            self.remote_shim = infra.remote_shim.PassThroughShim

        if isinstance(self.host, str):
            self.host = infra.interfaces.HostSpec.from_str(self.host)

        for interface_name, rpc_interface in self.host.rpc_interfaces.items():
            # Main RPC interface determines remote implementation
            if interface_name == infra.interfaces.PRIMARY_RPC_INTERFACE:
                if rpc_interface.protocol == "local":
                    self.remote_impl = infra.remote.LocalRemote
                    # Node client address does not currently work with DockerShim
                    if self.remote_shim != infra.remote_shim.DockerShim:
                        if not self.major_version or self.major_version > 1:
                            self.node_client_host = str(
                                ipaddress.ip_address(BASE_NODE_CLIENT_HOST) +
                                self.local_node_id)
                elif rpc_interface.protocol == "ssh":
                    self.remote_impl = infra.remote.SSHRemote
                else:
                    assert (
                        False
                    ), f"{rpc_interface.protocol} is not 'local://' or 'ssh://'"

            if rpc_interface.host == "localhost":
                rpc_interface.host = infra.net.expand_localhost()

            if rpc_interface.public_host is None:
                rpc_interface.public_host = rpc_interface.host
                rpc_interface.public_port = rpc_interface.port

            # Default node address host to same host as main RPC interface
            if interface_name == infra.interfaces.PRIMARY_RPC_INTERFACE:
                self.n2n_interface = infra.interfaces.Interface(
                    host=rpc_interface.host, port=node_port)
Пример #12
0
    def __init__(
        self,
        local_node_id,
        host,
        binary_dir=".",
        library_dir=".",
        debug=False,
        perf=False,
        node_port=None,
        version=None,
    ):
        self.local_node_id = local_node_id
        self.binary_dir = binary_dir
        self.library_dir = library_dir
        self.debug = debug
        self.perf = perf
        self.remote = None
        self.network_state = NodeNetworkState.stopped
        self.common_dir = None
        self.suspended = False
        self.node_id = None
        self.node_client_host = None
        self.interfaces = []
        self.version = version
        self.major_version = (Version(strip_version(self.version)).release[0]
                              if self.version is not None else None)
        self.consensus = None
        self.certificate_valid_from = None
        self.certificate_validity_days = None

        if os.getenv("CONTAINER_NODES"):
            self.remote_shim = infra.remote_shim.DockerShim
        else:
            self.remote_shim = infra.remote_shim.PassThroughShim

        if isinstance(host, str):
            host = infra.e2e_args.HostSpec.from_str(host)

        if host.protocol == "local":
            self.remote_impl = infra.remote.LocalRemote
            # Node client address does not currently work with DockerShim
            if self.remote_shim != infra.remote_shim.DockerShim:
                if not self.major_version or self.major_version > 1:
                    self.node_client_host = str(
                        ipaddress.ip_address(BASE_NODE_CLIENT_HOST) +
                        self.local_node_id)
        elif host.protocol == "ssh":
            self.remote_impl = infra.remote.SSHRemote
        else:
            assert False, f"{host} does not start with 'local://' or 'ssh://'"

        host_ = host.rpchost
        self.rpc_host, *port = host_.split(":")
        self.rpc_port = int(port[0]) if port else None
        if self.rpc_host == "localhost":
            self.rpc_host = infra.net.expand_localhost()

        pubhost_ = host.public_rpchost
        if pubhost_:
            self.pubhost, *pubport = pubhost_.split(":")
            self.pubport = int(pubport[0]) if pubport else self.rpc_port
        else:
            self.pubhost = self.rpc_host
            self.pubport = self.rpc_port

        self.node_host = self.rpc_host
        self.node_port = node_port

        self.max_open_sessions = host.max_open_sessions
        self.max_open_sessions_hard = host.max_open_sessions_hard
        self.additional_raw_node_args = host.additional_raw_node_args