<commit_before># cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os
import shutil
import tempfile

from cerbero.config import Architecture
from cerbero.errors import FatalError, EmptyPackageError
from cerbero.packages import PackagerBase, PackageType
from cerbero.packages.disttarball import DistTarball
from cerbero.packages.package import MetaPackage
from cerbero.utils import shell, _
from cerbero.utils import messages as m

SPEC_TPL = '''
%%define _topdir %(topdir)s
%%define _package_name %(package_name)s

Name:           %(name)s
Version:        %(version)s
Release:        1
Summary:        %(summary)s
Source:         %(source)s
Group:          Applications/Internet
License:        %(license)s
Prefix:         %(prefix)s
Vendor:         %(vendor)s
%(url)s
%(requires)s

%%description
%(description)s

%(devel_package)s

%%prep
%%setup -n %%{_package_name}

%%build

%%install
mkdir -p $RPM_BUILD_ROOT/%%{prefix}
cp -r $RPM_BUILD_DIR/%%{_package_name}/* $RPM_BUILD_ROOT/%%{prefix}

%%clean
rm -rf $RPM_BUILD_ROOT

%%files
%(files)s

%(devel_files)s
'''

DEVEL_PACKAGE_TPL = '''
%%package devel
%(requires)s
Summary: %(summary)s
Provides: %(name)s-devel

%%description devel
%(description)s
'''

META_SPEC_TPL = '''
Name:           %(name)s
Version:        %(version)s
Release:        1
Summary:        %(summary)s
Group:          Applications/Internet
License:	%(license)s
Vendor:         %(vendor)s
%(url)s
%(requires)s

%%description
%(description)s

%%prep

%%build

%%install
rm -rf $RPM_BUILD_ROOT

%%clean
rm -rf $RPM_BUILD_ROOT

%%files
'''

REQUIRE_TPL = 'Requires: %s\n'
DEVEL_TPL = '%%files devel \n%s'
URL_TPL = 'URL: %s\n'

class RPMPackage(PackagerBase):

    def __init__(self, config, package, store):
        PackagerBase.__init__(self, config, package, store)
        self.full_package_name = '%s-%s' % (self.package.name, self.package.version)

    def pack(self, output_dir, devel=True, force=False,
             pack_deps=True, tmpdir=None):
        self.install_dir = self.package.get_install_dir()
        self.devel = devel
        self.force = force
        self._empty_packages = []

        # Create a tmpdir for packages
        tmpdir, rpmdir, srcdir = self._create_rpm_tree(tmpdir)

        # only build each package once
        if pack_deps:
            self._pack_deps(output_dir, tmpdir, force)

        if not isinstance(self.package, MetaPackage):
            # create a tarball with all the package's files
            tarball_packager = DistTarball(self.config, self.package,
                                           self.store)
            tarball = tarball_packager.pack(output_dir, devel, True,
                    split=False, package_prefix=self.full_package_name)[0]
            # move the tarball to SOURCES
            shutil.move(tarball, srcdir)
            tarname = os.path.split(tarball)[1]
        else:
            # metapackages only contains Requires dependencies with other packages
            tarname = None

        m.action(_("Creating RPM package for %s") % self.package.name)
        # fill the spec file
        self._fill_spec(tarname, tmpdir)
        spec_path = os.path.join(tmpdir, '%s.spec' % self.package.name)
        with open(spec_path, 'w') as f:
            f.write(self._spec_str)

        # and build the package with rpmbuild
        self._build_rpm(tmpdir, spec_path)

        # copy the newly created package, which should be in RPMS/$ARCH
        # to the output dir
        paths = []
        for d in os.listdir(rpmdir):
            for f in os.listdir(os.path.join(rpmdir, d)):
                out_path = os.path.join(output_dir, f)
                if os.path.exists(out_path):
                    os.remove(out_path)
                paths.append(out_path)
                shutil.move(os.path.join(rpmdir, d, f), output_dir)
        return paths

    def _pack_deps(self, output_dir, tmpdir, force):
        for p in self.store.get_package_deps(self.package.name):
            stamp_path = os.path.join(tmpdir, p.name + '-stamp')
            if os.path.exists(stamp_path):
                # already built, skipping
                continue

            m.action(_("Packing dependency %s for package %s") % (p.name, self.package.name))
            packager = RPMPackage(self.config, p, self.store)
            try:
                packager.pack(output_dir, self.devel, force, True, tmpdir)
            except EmptyPackageError:
                self._empty_packages.append(p)

    def _build_rpm(self, tmpdir, spec_path):
        if self.config.target_arch == Architecture.X86:
            target = 'i686-redhat-linux'
        elif self.config.target_arch == Architecture.X86_64:
            target = 'x86_64-redhat-linux'
        else:
            raise FatalError(_('Architecture %s not supported') % \
                             self.config.target_arch)
        shell.call('rpmbuild -bb --target %s %s' % (target, spec_path))
        stamp_path = os.path.join(tmpdir, self.package.name + '-stamp')
        open(stamp_path, 'w').close()

    def _create_rpm_tree(self, tmpdir):
        # create a tmp dir to use as topdir
        if tmpdir is None:
            tmpdir = tempfile.mkdtemp()
            for d in ['BUILD', 'SOURCES', 'RPMS', 'SRPMS', 'SPECS']:
                os.mkdir(os.path.join(tmpdir, d))
        return (tmpdir, os.path.join(tmpdir, 'RPMS'),
                os.path.join(tmpdir, 'SOURCES'))

    def _devel_package_and_files(self):
        args = {}
        args['summary'] = 'Development files for %s' % self.package.name
        args['description'] = args['summary']
        args['requires'] =  self._get_requires(PackageType.DEVEL)
        args['name'] = self.package.name
        try:
            devel = DEVEL_TPL % self.files_list(PackageType.DEVEL)
        except EmptyPackageError:
            devel = ''
        return DEVEL_PACKAGE_TPL % args, devel

    def _fill_spec(self, sources, topdir):
        requires = self._get_requires(PackageType.RUNTIME)
        runtime_files  = self.files_list(PackageType.RUNTIME)

        if self.devel:
            devel_package, devel_files = self._devel_package_and_files()
        else:
            devel_package, devel_files = ('', '')

        if isinstance(self.package, MetaPackage):
            template = META_SPEC_TPL
        else:
            template = SPEC_TPL

        self._spec_str = template % {
                'name': self.package.name,
                'version': self.package.version,
                'package_name': self.full_package_name,
                'summary': self.package.shortdesc,
                'description': self.package.longdesc if self.package.longdesc != 'default' else self.package.shortdesc,
                'license': ' '.join(self.package.licenses),
                'vendor': self.package.vendor,
                'url': URL_TPL % self.package.url if self.package.url != 'default' else '',
                'requires': requires,
                'prefix': self.install_dir,
                'source': sources,
                'topdir': topdir,
                'devel_package': devel_package,
                'devel_files': devel_files,
                'files':  runtime_files}

    def _get_requires(self, package_type):
        deps = [p.name for p in self.store.get_package_deps(self.package.name)]
        deps = list(set(deps) - set(self._empty_packages))
        if package_type == PackageType.DEVEL:
            deps = map(lambda x: x+'-devel', deps)
        return reduce(lambda x, y: x + REQUIRE_TPL % y, deps, '')

    def files_list(self, package_type):
        # metapackages only have dependencies in other packages
        if isinstance(self.package, MetaPackage):
            return ''
        files = PackagerBase.files_list(self, package_type, self.force)
        for f in [x for x in files if x.endswith('py')]:
            if f+'c' not in files:
                files.append(f+'c')
            if f+'o' not in files:
                files.append(f+'o')
        return '\n'.join([os.path.join('%{prefix}',  x) for x in files])

class Packager(object):

    def __new__(klass, config, package, store):
        return RPMPackage(config, package, store)

def register():
    from cerbero.packages.packager import register_packager
    from cerbero.config import Distro
    register_packager(Distro.REDHAT, Packager)
<commit_msg>rpm.py: Fix template for meta spec so that rpms end up in the correct place.<commit_after># cerbero - a multi-platform build system for Open Source software
# Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

import os
import shutil
import tempfile

from cerbero.config import Architecture
from cerbero.errors import FatalError, EmptyPackageError
from cerbero.packages import PackagerBase, PackageType
from cerbero.packages.disttarball import DistTarball
from cerbero.packages.package import MetaPackage
from cerbero.utils import shell, _
from cerbero.utils import messages as m

SPEC_TPL = '''
%%define _topdir %(topdir)s
%%define _package_name %(package_name)s

Name:           %(name)s
Version:        %(version)s
Release:        1
Summary:        %(summary)s
Source:         %(source)s
Group:          Applications/Internet
License:        %(license)s
Prefix:         %(prefix)s
Vendor:         %(vendor)s
%(url)s
%(requires)s

%%description
%(description)s

%(devel_package)s

%%prep
%%setup -n %%{_package_name}

%%build

%%install
mkdir -p $RPM_BUILD_ROOT/%%{prefix}
cp -r $RPM_BUILD_DIR/%%{_package_name}/* $RPM_BUILD_ROOT/%%{prefix}

%%clean
rm -rf $RPM_BUILD_ROOT

%%files
%(files)s

%(devel_files)s
'''

DEVEL_PACKAGE_TPL = '''
%%package devel
%(requires)s
Summary: %(summary)s
Provides: %(name)s-devel

%%description devel
%(description)s
'''

META_SPEC_TPL = '''
%%define _topdir %(topdir)s
%%define _package_name %(package_name)s

Name:           %(name)s
Version:        %(version)s
Release:        1
Summary:        %(summary)s
Group:          Applications/Internet
License:	%(license)s
Vendor:         %(vendor)s
%(url)s
%(requires)s

%%description
%(description)s

%%prep

%%build

%%install

%%clean
rm -rf $RPM_BUILD_ROOT

%%files
'''

REQUIRE_TPL = 'Requires: %s\n'
DEVEL_TPL = '%%files devel \n%s'
URL_TPL = 'URL: %s\n'

class RPMPackage(PackagerBase):

    def __init__(self, config, package, store):
        PackagerBase.__init__(self, config, package, store)
        self.full_package_name = '%s-%s' % (self.package.name, self.package.version)

    def pack(self, output_dir, devel=True, force=False,
             pack_deps=True, tmpdir=None):
        self.install_dir = self.package.get_install_dir()
        self.devel = devel
        self.force = force
        self._empty_packages = []

        # Create a tmpdir for packages
        tmpdir, rpmdir, srcdir = self._create_rpm_tree(tmpdir)

        # only build each package once
        if pack_deps:
            self._pack_deps(output_dir, tmpdir, force)

        if not isinstance(self.package, MetaPackage):
            # create a tarball with all the package's files
            tarball_packager = DistTarball(self.config, self.package,
                                           self.store)
            tarball = tarball_packager.pack(output_dir, devel, True,
                    split=False, package_prefix=self.full_package_name)[0]
            # move the tarball to SOURCES
            shutil.move(tarball, srcdir)
            tarname = os.path.split(tarball)[1]
        else:
            # metapackages only contains Requires dependencies with other packages
            tarname = None

        m.action(_("Creating RPM package for %s") % self.package.name)
        # fill the spec file
        self._fill_spec(tarname, tmpdir)
        spec_path = os.path.join(tmpdir, '%s.spec' % self.package.name)
        with open(spec_path, 'w') as f:
            f.write(self._spec_str)

        # and build the package with rpmbuild
        self._build_rpm(tmpdir, spec_path)

        # copy the newly created package, which should be in RPMS/$ARCH
        # to the output dir
        paths = []
        for d in os.listdir(rpmdir):
            for f in os.listdir(os.path.join(rpmdir, d)):
                out_path = os.path.join(output_dir, f)
                if os.path.exists(out_path):
                    os.remove(out_path)
                paths.append(out_path)
                shutil.move(os.path.join(rpmdir, d, f), output_dir)
        return paths

    def _pack_deps(self, output_dir, tmpdir, force):
        for p in self.store.get_package_deps(self.package.name):
            stamp_path = os.path.join(tmpdir, p.name + '-stamp')
            if os.path.exists(stamp_path):
                # already built, skipping
                continue

            m.action(_("Packing dependency %s for package %s") % (p.name, self.package.name))
            packager = RPMPackage(self.config, p, self.store)
            try:
                packager.pack(output_dir, self.devel, force, True, tmpdir)
            except EmptyPackageError:
                self._empty_packages.append(p)

    def _build_rpm(self, tmpdir, spec_path):
        if self.config.target_arch == Architecture.X86:
            target = 'i686-redhat-linux'
        elif self.config.target_arch == Architecture.X86_64:
            target = 'x86_64-redhat-linux'
        else:
            raise FatalError(_('Architecture %s not supported') % \
                             self.config.target_arch)
        shell.call('rpmbuild -bb --target %s %s' % (target, spec_path))
        stamp_path = os.path.join(tmpdir, self.package.name + '-stamp')
        open(stamp_path, 'w').close()

    def _create_rpm_tree(self, tmpdir):
        # create a tmp dir to use as topdir
        if tmpdir is None:
            tmpdir = tempfile.mkdtemp()
            for d in ['BUILD', 'SOURCES', 'RPMS', 'SRPMS', 'SPECS']:
                os.mkdir(os.path.join(tmpdir, d))
        return (tmpdir, os.path.join(tmpdir, 'RPMS'),
                os.path.join(tmpdir, 'SOURCES'))

    def _devel_package_and_files(self):
        args = {}
        args['summary'] = 'Development files for %s' % self.package.name
        args['description'] = args['summary']
        args['requires'] =  self._get_requires(PackageType.DEVEL)
        args['name'] = self.package.name
        try:
            devel = DEVEL_TPL % self.files_list(PackageType.DEVEL)
        except EmptyPackageError:
            devel = ''
        return DEVEL_PACKAGE_TPL % args, devel

    def _fill_spec(self, sources, topdir):
        requires = self._get_requires(PackageType.RUNTIME)
        runtime_files  = self.files_list(PackageType.RUNTIME)

        if self.devel:
            devel_package, devel_files = self._devel_package_and_files()
        else:
            devel_package, devel_files = ('', '')

        if isinstance(self.package, MetaPackage):
            template = META_SPEC_TPL
        else:
            template = SPEC_TPL

        self._spec_str = template % {
                'name': self.package.name,
                'version': self.package.version,
                'package_name': self.full_package_name,
                'summary': self.package.shortdesc,
                'description': self.package.longdesc if self.package.longdesc != 'default' else self.package.shortdesc,
                'license': ' '.join(self.package.licenses),
                'vendor': self.package.vendor,
                'url': URL_TPL % self.package.url if self.package.url != 'default' else '',
                'requires': requires,
                'prefix': self.install_dir,
                'source': sources,
                'topdir': topdir,
                'devel_package': devel_package,
                'devel_files': devel_files,
                'files':  runtime_files}

    def _get_requires(self, package_type):
        deps = [p.name for p in self.store.get_package_deps(self.package.name)]
        deps = list(set(deps) - set(self._empty_packages))
        if package_type == PackageType.DEVEL:
            deps = map(lambda x: x+'-devel', deps)
        return reduce(lambda x, y: x + REQUIRE_TPL % y, deps, '')

    def files_list(self, package_type):
        # metapackages only have dependencies in other packages
        if isinstance(self.package, MetaPackage):
            return ''
        files = PackagerBase.files_list(self, package_type, self.force)
        for f in [x for x in files if x.endswith('py')]:
            if f+'c' not in files:
                files.append(f+'c')
            if f+'o' not in files:
                files.append(f+'o')
        return '\n'.join([os.path.join('%{prefix}',  x) for x in files])

class Packager(object):

    def __new__(klass, config, package, store):
        return RPMPackage(config, package, store)

def register():
    from cerbero.packages.packager import register_packager
    from cerbero.config import Distro
    register_packager(Distro.REDHAT, Packager)
<|endoftext|>


<commit_before>import remosh

import os
import tempfile
import unittest

class RemotedTest(unittest.TestCase):

    def setUp(self):
        self.test_commands = tempfile.NamedTemporaryFile(delete=False)
        self.test_commands.write('secretid: echo "Hello, World!"\n')
        self.test_commands.close()
        self.app = remosh.create_app(self.test_commands.name, 'test.log')
        self.app.debug = True
        self.client = self.app.test_client()

    def tearDown(self):
        os.remove(self.test_commands.name)

    def test_invalid_command(self):
        response = self.client.post('/')
        self.assertEqual(response.status_code, 400)

        response = self.client.post('/?id=foobar')
        self.assertEqual(response.status_code, 400)

    def test_valid_command(self):
        response = self.client.post('/?id=secretid')
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()
<commit_msg>Python 3 str fix<commit_after>import remosh

import os
import tempfile
import unittest

class RemotedTest(unittest.TestCase):

    def setUp(self):
        self.test_commands = tempfile.NamedTemporaryFile(delete=False)
        self.test_commands.write('secretid: echo "Hello, World!"\n'.encode('utf-8'))
        self.test_commands.close()
        self.app = remosh.create_app(self.test_commands.name, 'test.log')
        self.app.debug = True
        self.client = self.app.test_client()

    def tearDown(self):
        os.remove(self.test_commands.name)

    def test_invalid_command(self):
        response = self.client.post('/')
        self.assertEqual(response.status_code, 400)

        response = self.client.post('/?id=foobar')
        self.assertEqual(response.status_code, 400)

    def test_valid_command(self):
        response = self.client.post('/?id=secretid')
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before># This file is part of LiSE, a framework for life simulation games.
# Copyright (c) 2013 Zachary Spector,  zacharyspector@gmail.com
"""Widget to represent :class:`Place`s. :class:`Pawn` moves around on
top of these.

"""
from functools import partial
from kivy.properties import (
    AliasProperty,
    ListProperty,
    ObjectProperty,
    NumericProperty,
    BooleanProperty
)
from kivy.clock import Clock
from kivy.logger import Logger
from ELiDE.kivygarden.collider import CollideEllipse
from .pawnspot import PawnSpot
from ..util import trigger

class Spot(PawnSpot):
    """The icon that represents a :class:`Place`.

    Each :class:`Spot` is located on the Board that represents the
    :class:`Character` that the underlying :class:`Place` is in. Its
    coordinates are relative to its :class:`Board`, not necessarily
    the window the :class:`Board` is in.

    """
    offset = NumericProperty(3)
    collider = ObjectProperty()
    collided = BooleanProperty(False)
    place = AliasProperty(
        lambda self: self.remote,
        lambda self, v: self.remote.setter()(v),
        bind=('remote',)
    )
    default_image_paths = ['orb.png']
    default_pos = (0.5, 0.5)
    _touchpos = ListProperty([])

    def __init__(self, **kwargs):
        """Deal with triggers and bindings, and arrange to take care of
        changes in game-time.

        """
        self._pospawn_partials = {}
        self._pospawn_triggers = {}
        kwargs['size_hint'] = (None, None)
        if 'place' in kwargs:
            kwargs['remote'] = kwargs['place']
            del kwargs['place']
        super().__init__(**kwargs)
        self.bind(pos=self._trigger_upd_pawns_here)

    def _get_pospawn_partial(self, pawn):
        if pawn not in self._pospawn_partials:
            self._pospawn_partials[pawn] = partial(
                self.pospawn, pawn
            )
        return self._pospawn_partials[pawn]

    def _get_pospawn_trigger(self, pawn, *args):
        if pawn not in self._pospawn_triggers:
            self._pospawn_triggers[pawn] = Clock.create_trigger(
                self._get_pospawn_partial(pawn)
            )
        return self._pospawn_triggers[pawn]

    def _bind_trigger_pospawn(self, pawn):
        trigger = self._get_pospawn_trigger(pawn)
        pawn.bind(
            pos=trigger,
            size=trigger
        )
        self.bind(
            pos=trigger,
            size=trigger
        )

    def _unbind_trigger_pospawn(self, pawn):
        trigger = self._get_pospawn_trigger(pawn)
        pawn.unbind(
            pos=trigger,
            size=trigger
        )
        self.unbind(
            pos=trigger,
            size=trigger
        )

    def _upd_pos(self, *args):
        if self.board is None:
            Clock.schedule_once(self._upd_pos, 0)
            return
        self.pos = (
            self.remote.get('_x', self.default_pos[0]) * self.board.width,
            self.remote.get('_y', self.default_pos[1]) * self.board.height
        )

    def listen_pos(self, *args):
        self.remote.listener(
            fun=self._upd_pos,
            stat='pos'
        )

    def unlisten_pos(self, *args):
        self.remote.unlisten(
            fun=self._upd_pos,
            stat='pos'
        )

    def on_remote(self, *args):
        super().on_remote(*args)
        self.listen_pos()
        self._upd_pos()

    def push_pos(self, *args):
        """Set my current position, expressed as proportions of the board's
        width and height, into the ``_x`` and ``_y`` keys of the
        entity in my ``remote`` property, such that it will be
        recorded in the database.

        """
        self.remote['_x'] = self.x / self.board.width
        self.remote['_y'] = self.y / self.board.height
    _trigger_push_pos = trigger(push_pos)

    def add_widget(self, wid, i=0, canvas=None):
        """Put the widget's canvas in my ``board``'s ``pawnlayout`` rather
        than my own canvas.

        The idea is that all my child widgets are to be instances of
        :class:`Pawn`, and should therefore be drawn after every
        non-:class:`Pawn` widget, so that pawns are on top of spots
        and arrows.

        """
        super().add_widget(wid, i, canvas)
        self._bind_trigger_pospawn(wid)
        if not hasattr(wid, 'group'):
            return
        wid._no_use_canvas = True
        mycanvas = (
            self.canvas.after if canvas == 'after' else
            self.canvas.before if canvas == 'before' else
            self.canvas
        )
        pawncanvas = (
            self.board.pawnlayout.canvas.after if canvas == 'after' else
            self.board.pawnlayout.canvas.before if canvas == 'before' else
            self.board.pawnlayout.canvas
        )
        mycanvas.remove(wid.canvas)
        for child in self.children:
            if hasattr(child, 'group'):
                if child.group in pawncanvas.children:
                    pawncanvas.remove(child.group)
                pawncanvas.add(child.group)
            else:
                pawncanvas.add(child.canvas)
        self.pospawn(wid)

    def remove_widget(self, wid):
        try:
            self._unbind_trigger_pospawn(wid)
        except KeyError:
            pass
        return super().remove_widget(wid)

    def pospawn(self, pawn, *args):
        """Given some :class:`Pawn` instance that's to be on top of me, set
        its ``pos`` so that it looks like it's on top of me but
        doesn't cover me so much that you can't select me.

        """
        i = 0
        for child in self.children:
            if child is pawn:
                break
            i += 1
        off = i * self.offset
        (x, y) = self.center
        pawn.pos = (x+off, y+off)

    def _upd_pawns_here(self, *args):
        """Move any :class:`Pawn` atop me so it still *is* on top of me,
        presumably after I've moved.

        """
        for pawn in self.children:
            self.pospawn(pawn)
    _trigger_upd_pawns_here = trigger(_upd_pawns_here)

    def collide_point(self, x, y):
        """Check my collider."""
        if not self.collider:
            self.collider = CollideEllipse(
                x=x, y=y, rx=self.width/2, ry=self.height/2
            )
        return (x, y) in self.collider

    def on_touch_move(self, touch):
        """If I'm being dragged, move to follow the touch."""
        if not self.hit:
            return False
        self._touchpos = touch.pos
        self.center = self._touchpos
        return True

    def on_touch_up(self, touch):
        """Unset ``touchpos``"""
        if self._touchpos:
            self.center = self._touchpos
            self._touchpos = []
            self._trigger_push_pos()
        (x, y) = self.center
        self.collider = CollideEllipse(
            x=x, y=y, rx=self.width/2, ry=self.height/2
        )
        self.collided = False
        self.hit = False

    def __repr__(self):
        """Give my name and position."""
        return "{}@({},{})".format(self.name, self.x, self.y)
<commit_msg>Make the collider where I am, not where you clicked<commit_after># This file is part of LiSE, a framework for life simulation games.
# Copyright (c) 2013 Zachary Spector,  zacharyspector@gmail.com
"""Widget to represent :class:`Place`s. :class:`Pawn` moves around on
top of these.

"""
from functools import partial
from kivy.properties import (
    AliasProperty,
    ListProperty,
    ObjectProperty,
    NumericProperty,
    BooleanProperty
)
from kivy.clock import Clock
from kivy.logger import Logger
from ELiDE.kivygarden.collider import CollideEllipse
from .pawnspot import PawnSpot
from ..util import trigger

class Spot(PawnSpot):
    """The icon that represents a :class:`Place`.

    Each :class:`Spot` is located on the Board that represents the
    :class:`Character` that the underlying :class:`Place` is in. Its
    coordinates are relative to its :class:`Board`, not necessarily
    the window the :class:`Board` is in.

    """
    offset = NumericProperty(3)
    collider = ObjectProperty()
    collided = BooleanProperty(False)
    place = AliasProperty(
        lambda self: self.remote,
        lambda self, v: self.remote.setter()(v),
        bind=('remote',)
    )
    default_image_paths = ['orb.png']
    default_pos = (0.5, 0.5)
    _touchpos = ListProperty([])

    def __init__(self, **kwargs):
        """Deal with triggers and bindings, and arrange to take care of
        changes in game-time.

        """
        self._pospawn_partials = {}
        self._pospawn_triggers = {}
        kwargs['size_hint'] = (None, None)
        if 'place' in kwargs:
            kwargs['remote'] = kwargs['place']
            del kwargs['place']
        super().__init__(**kwargs)
        self.bind(pos=self._trigger_upd_pawns_here)

    def _get_pospawn_partial(self, pawn):
        if pawn not in self._pospawn_partials:
            self._pospawn_partials[pawn] = partial(
                self.pospawn, pawn
            )
        return self._pospawn_partials[pawn]

    def _get_pospawn_trigger(self, pawn, *args):
        if pawn not in self._pospawn_triggers:
            self._pospawn_triggers[pawn] = Clock.create_trigger(
                self._get_pospawn_partial(pawn)
            )
        return self._pospawn_triggers[pawn]

    def _bind_trigger_pospawn(self, pawn):
        trigger = self._get_pospawn_trigger(pawn)
        pawn.bind(
            pos=trigger,
            size=trigger
        )
        self.bind(
            pos=trigger,
            size=trigger
        )

    def _unbind_trigger_pospawn(self, pawn):
        trigger = self._get_pospawn_trigger(pawn)
        pawn.unbind(
            pos=trigger,
            size=trigger
        )
        self.unbind(
            pos=trigger,
            size=trigger
        )

    def _upd_pos(self, *args):
        if self.board is None:
            Clock.schedule_once(self._upd_pos, 0)
            return
        self.pos = (
            self.remote.get('_x', self.default_pos[0]) * self.board.width,
            self.remote.get('_y', self.default_pos[1]) * self.board.height
        )

    def listen_pos(self, *args):
        self.remote.listener(
            fun=self._upd_pos,
            stat='pos'
        )

    def unlisten_pos(self, *args):
        self.remote.unlisten(
            fun=self._upd_pos,
            stat='pos'
        )

    def on_remote(self, *args):
        super().on_remote(*args)
        self.listen_pos()
        self._upd_pos()

    def push_pos(self, *args):
        """Set my current position, expressed as proportions of the board's
        width and height, into the ``_x`` and ``_y`` keys of the
        entity in my ``remote`` property, such that it will be
        recorded in the database.

        """
        self.remote['_x'] = self.x / self.board.width
        self.remote['_y'] = self.y / self.board.height
    _trigger_push_pos = trigger(push_pos)

    def add_widget(self, wid, i=0, canvas=None):
        """Put the widget's canvas in my ``board``'s ``pawnlayout`` rather
        than my own canvas.

        The idea is that all my child widgets are to be instances of
        :class:`Pawn`, and should therefore be drawn after every
        non-:class:`Pawn` widget, so that pawns are on top of spots
        and arrows.

        """
        super().add_widget(wid, i, canvas)
        self._bind_trigger_pospawn(wid)
        if not hasattr(wid, 'group'):
            return
        wid._no_use_canvas = True
        mycanvas = (
            self.canvas.after if canvas == 'after' else
            self.canvas.before if canvas == 'before' else
            self.canvas
        )
        pawncanvas = (
            self.board.pawnlayout.canvas.after if canvas == 'after' else
            self.board.pawnlayout.canvas.before if canvas == 'before' else
            self.board.pawnlayout.canvas
        )
        mycanvas.remove(wid.canvas)
        for child in self.children:
            if hasattr(child, 'group'):
                if child.group in pawncanvas.children:
                    pawncanvas.remove(child.group)
                pawncanvas.add(child.group)
            else:
                pawncanvas.add(child.canvas)
        self.pospawn(wid)

    def remove_widget(self, wid):
        try:
            self._unbind_trigger_pospawn(wid)
        except KeyError:
            pass
        return super().remove_widget(wid)

    def pospawn(self, pawn, *args):
        """Given some :class:`Pawn` instance that's to be on top of me, set
        its ``pos`` so that it looks like it's on top of me but
        doesn't cover me so much that you can't select me.

        """
        i = 0
        for child in self.children:
            if child is pawn:
                break
            i += 1
        off = i * self.offset
        (x, y) = self.center
        pawn.pos = (x+off, y+off)

    def _upd_pawns_here(self, *args):
        """Move any :class:`Pawn` atop me so it still *is* on top of me,
        presumably after I've moved.

        """
        for pawn in self.children:
            self.pospawn(pawn)
    _trigger_upd_pawns_here = trigger(_upd_pawns_here)

    def collide_point(self, x, y):
        """Check my collider."""
        if not self.collider:
            self.collider = CollideEllipse(
                x=self.x, y=self.y, rx=self.width/2, ry=self.height/2
            )
        return (x, y) in self.collider

    def on_touch_move(self, touch):
        """If I'm being dragged, move to follow the touch."""
        if not self.hit:
            return False
        self._touchpos = touch.pos
        self.center = self._touchpos
        return True

    def on_touch_up(self, touch):
        """Unset ``touchpos``"""
        if self._touchpos:
            self.center = self._touchpos
            self._touchpos = []
            self._trigger_push_pos()
        (x, y) = self.center
        self.collider = CollideEllipse(
            x=x, y=y, rx=self.width/2, ry=self.height/2
        )
        self.collided = False
        self.hit = False

    def __repr__(self):
        """Give my name and position."""
        return "{}@({},{})".format(self.name, self.x, self.y)
<|endoftext|>


<commit_before>"""
Managers of ``blog`` application.
"""
from django.db import models

class CategoryOnlineManager(models.Manager):
    """
    Manager that manages online ``Category`` objects.
    """

    def get_query_set(self):
        from blog.models import Entry
        entry_status = Entry.STATUS_ONLINE
        return super(CategoryOnlineManager, self).get_query_set().filter(
            entry__status=entry_status).distinct()

class EntryOnlineManager(models.Manager):
    """
    Manager that manages online ``Entry`` objects.
    """

    def get_query_set(self):
        return super(EntryOnlineManager, self).get_query_set().filter(
            status=self.model.STATUS_ONLINE)

<commit_msg>Change the method get_query_set() to get_queryset() as required by django 1.7<commit_after>"""
Managers of ``blog`` application.
"""
from django.db import models

class CategoryOnlineManager(models.Manager):
    """
    Manager that manages online ``Category`` objects.
    """

    def get_queryset(self):
        from blog.models import Entry
        entry_status = Entry.STATUS_ONLINE
        return super(CategoryOnlineManager, self).get_queryset().filter(
            entry__status=entry_status).distinct()

class EntryOnlineManager(models.Manager):
    """
    Manager that manages online ``Entry`` objects.
    """

    def get_queryset(self):
        return super(EntryOnlineManager, self).get_queryset().filter(
            status=self.model.STATUS_ONLINE)

<|endoftext|>


<commit_before># tests for a simple graph

from graph import SimpleGraph
import pytest

def test_add_nodes():
    """nodes are added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert 'a' in g.nodes()
    assert 'b' in g.nodes()
    assert 'c' in g.nodes()

def test_del_nodes():
    """nodes are deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.del_node('a')
    assert 'a' not in g.nodes()
    assert g.has_node('a') is False

def test_del_error():
    """error raised when non-existant value deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.del_node('p')

def test_del_edge():
    """other edges preserved when one deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.del_edge('a', 'c')
    assert g.neighbors('a') == {'b': 0}

def test_add_edge():
    """edge added, new node added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.add_edge('q', 'a')
    assert g.has_node('q')
    assert g.neighbors('q') == {'a': 0}

def test_edge_error():
    """delete non-existant edge"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.del_edge('a', 'z')

def test_has_node():
    """edge added, new node added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert g.has_node('b')

def test_adjacent():
    """adjacent correctly identify edges, new edge add node"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'd')
    g.add_edge('a', 'f')
    assert 'f' in g.nodes()
    assert g.adjacent('a', 'd')
    assert not g.adjacent('a', 'b')

def test_adjacent_error():
    """error raised when nodes non-existant"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.adjacent('l', 'm')

def test_edges():
    """edges prints correct edges as tuples"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert ('a', 'c') in g.edges()
    assert ('a', 'b') in g.edges()

def test_breadth():
    g = SimpleGraph()
    g.add_edge('a', 'b')
    g.add_edge('a', 'c')
    g.add_edge('b', 'd')
    g.add_edge('b', 'e')
    g.add_edge('e', 'f')
    g.add_edge('f', 'g')
    assert g.breadth_first_traversal('a') == ['a', 'c', 'b', 'e', 'd', 'f', 'g']

def test_depth():
    g = SimpleGraph()
    g.add_edge('a', 'b')
    g.add_edge('a', 'c')
    g.add_edge('b', 'd')
    g.add_edge('b', 'e')
    g.add_edge('e', 'f')
    g.add_edge('f', 'g')
    assert g.depth_first_traversal('a') == ['a', 'c', 'b', 'e', 'f', 'g', 'd']

def test_one_breadth():
    g = SimpleGraph()
    g.add_node('a')
    assert g.breadth_first_traversal('a') == ['a']

def test_one_depth():
    g = SimpleGraph()
    g.add_node('a')
    assert g.depth_first_traversal('a') == ['a']

def test_one_loop_breadth():
    g = SimpleGraph()
    g.add_edge('a', 'a')
    assert g.breadth_first_traversal('a') == ['a']

def test_one_loop_depth():
    g = SimpleGraph()
    g.add_edge('a', 'a')
    assert g.depth_first_traversal('a') == ['a']

def fully_connected_graph(nodes):
    g = SimpleGraph()
    for node in nodes:
        g.add_node(node)
        for other_node in nodes:
            if other_node is not node:
                g.add_edge(node, other_node)
    return g

def test_fully_connected():
    g = fully_connected_graph(['a', 'b', 'c', 'd'])
    assert g.breadth_first_traversal('a') == ['a', 'c', 'b', 'd']

def test_fully_connected_again():
    g = fully_connected_graph(['a', 'b', 'c', 'd'])
    assert g.depth_first_traversal('a') == ['a', 'c', 'b', 'd']

def test_weighted_edges():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.add_edge('b', 'c', 1)
    assert g.dict_graph['a'] == {'b': 5, 'c': 2}

def test_weighted_edges_with_edge_delete():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.del_edge('a', 'c')
    assert g.dict_graph['a'] == {'b': 5}

def test_weighted_edges_with_node_delete():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.del_node('c')
    assert g.dict_graph['a'] == {'b': 5}

def test_dijkstra():
    graph = SimpleGraph([('a', 'b', 6), ('b', 'a', 5),
                         ('a', 'g', 1), ('g', 'b', 1)])
    assert graph.dijkstra('a') == {'a': 0, 'b': 2, 'g': 1}
<commit_msg>added test for bellman ford<commit_after># tests for a simple graph

from graph import SimpleGraph
import pytest

def test_add_nodes():
    """nodes are added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert 'a' in g.nodes()
    assert 'b' in g.nodes()
    assert 'c' in g.nodes()

def test_del_nodes():
    """nodes are deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.del_node('a')
    assert 'a' not in g.nodes()
    assert g.has_node('a') is False

def test_del_error():
    """error raised when non-existant value deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.del_node('p')

def test_del_edge():
    """other edges preserved when one deleted"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.del_edge('a', 'c')
    assert g.neighbors('a') == {'b': 0}

def test_add_edge():
    """edge added, new node added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    g.add_edge('q', 'a')
    assert g.has_node('q')
    assert g.neighbors('q') == {'a': 0}

def test_edge_error():
    """delete non-existant edge"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.del_edge('a', 'z')

def test_has_node():
    """edge added, new node added"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert g.has_node('b')

def test_adjacent():
    """adjacent correctly identify edges, new edge add node"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'd')
    g.add_edge('a', 'f')
    assert 'f' in g.nodes()
    assert g.adjacent('a', 'd')
    assert not g.adjacent('a', 'b')

def test_adjacent_error():
    """error raised when nodes non-existant"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    with pytest.raises(KeyError):
        g.adjacent('l', 'm')

def test_edges():
    """edges prints correct edges as tuples"""
    g = SimpleGraph()
    g.add_node('a')
    g.add_node('b')
    g.add_node('c')
    g.add_edge('a', 'c')
    g.add_edge('a', 'b')
    assert ('a', 'c') in g.edges()
    assert ('a', 'b') in g.edges()

def test_breadth():
    g = SimpleGraph()
    g.add_edge('a', 'b')
    g.add_edge('a', 'c')
    g.add_edge('b', 'd')
    g.add_edge('b', 'e')
    g.add_edge('e', 'f')
    g.add_edge('f', 'g')
    assert g.breadth_first_traversal('a') == ['a', 'c', 'b', 'e', 'd', 'f', 'g']

def test_depth():
    g = SimpleGraph()
    g.add_edge('a', 'b')
    g.add_edge('a', 'c')
    g.add_edge('b', 'd')
    g.add_edge('b', 'e')
    g.add_edge('e', 'f')
    g.add_edge('f', 'g')
    assert g.depth_first_traversal('a') == ['a', 'c', 'b', 'e', 'f', 'g', 'd']

def test_one_breadth():
    g = SimpleGraph()
    g.add_node('a')
    assert g.breadth_first_traversal('a') == ['a']

def test_one_depth():
    g = SimpleGraph()
    g.add_node('a')
    assert g.depth_first_traversal('a') == ['a']

def test_one_loop_breadth():
    g = SimpleGraph()
    g.add_edge('a', 'a')
    assert g.breadth_first_traversal('a') == ['a']

def test_one_loop_depth():
    g = SimpleGraph()
    g.add_edge('a', 'a')
    assert g.depth_first_traversal('a') == ['a']

def fully_connected_graph(nodes):
    g = SimpleGraph()
    for node in nodes:
        g.add_node(node)
        for other_node in nodes:
            if other_node is not node:
                g.add_edge(node, other_node)
    return g

def test_fully_connected():
    g = fully_connected_graph(['a', 'b', 'c', 'd'])
    assert g.breadth_first_traversal('a') == ['a', 'c', 'b', 'd']

def test_fully_connected_again():
    g = fully_connected_graph(['a', 'b', 'c', 'd'])
    assert g.depth_first_traversal('a') == ['a', 'c', 'b', 'd']

def test_weighted_edges():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.add_edge('b', 'c', 1)
    assert g.dict_graph['a'] == {'b': 5, 'c': 2}

def test_weighted_edges_with_edge_delete():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.del_edge('a', 'c')
    assert g.dict_graph['a'] == {'b': 5}

def test_weighted_edges_with_node_delete():
    g = SimpleGraph()
    g.add_edge('a', 'b', 5)
    g.add_edge('a', 'c', 2)
    g.del_node('c')
    assert g.dict_graph['a'] == {'b': 5}

def test_dijkstra():
    graph = SimpleGraph([('a', 'b', 6), ('b', 'a', 5),
                         ('a', 'g', 1), ('g', 'b', 1)])
    assert graph.dijkstra('a') == {'a': 0, 'b': 2, 'g': 1}

def test_bellman_ford():
    """basic Bellman Ford algorithm test"""
    graph = SimpleGraph([('a', 'b', 6), ('b', 'a', 5),
                         ('a', 'g', 1), ('g', 'b', 1)])
    assert graph.bellmanford('a') == {'a': 0, 'b': 2, 'g': 1}
<|endoftext|>


<commit_before>import copy
import shutil
import os
import sys

import click

from inenv import (InenvManager, INENV_ENV_VAR, EVAL_EXIT_CODE, InenvException,
                   autojump_enabled, toggle_autojump)
from utils import override_envars_and_deactivate
import version

def activator_warn(inenv):
    click.echo(click.style("Please add the following to your bash RC for auto switch.", fg='red'))
    click.echo(click.style("source {file}".format(file=inenv.activate_file), fg='green'))

class InenvCliGroup(click.Group):
    sort_later = set()

    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))

    def add_command(self, cmd, name=None, sort_later=False):
        super(InenvCliGroup, self).add_command(cmd, name=name)
        if sort_later:
            self.sort_later.add(name)

    def list_commands(self, ctx):
        core_commands, sort_later_commands = [], []
        for k, v in self.commands.items():
            if k in self.sort_later:
                sort_later_commands.append(k)
            else:
                core_commands.append(k)
        return sorted(core_commands) + sorted(sort_later_commands)

    def format_commands(self, ctx, formatter):
        """Extra format methods for multi methods that adds all the commands
        after the options.
        """
        core_commands, inenv_commands = [], []
        for subcommand in self.list_commands(ctx):
            cmd = self.get_command(ctx, subcommand)
            # What is this, the tool lied about a command.  Ignore it
            if cmd is None:
                continue

            help = cmd.short_help or ''
            if subcommand in self.sort_later:
                inenv_commands.append((subcommand, help))
            else:
                core_commands.append((subcommand, help))

        if core_commands:
            with formatter.section('Commands'):
                formatter.write_dl(core_commands)

        if inenv_commands:
            with formatter.section('Inenvs'):
                formatter.write_dl(inenv_commands)

@click.group(cls=InenvCliGroup, name='inenv')
@click.version_option(version=version.__version__)
def main_cli():
    pass

def _run(venv_name, cmd):
    if len(cmd) == 1:
        cmd = cmd[0].split()
    inenv = InenvManager()
    venv = inenv.get_prepped_venv(venv_name)
    venv.run(cmd, always_exit=True)

@click.argument('cmd', nargs=-1)
@click.option('--venv_name', default=None)
@click.command()
def switch_or_run(cmd, venv_name=None):
    """Switch or run in this env"""
    if cmd:
        return _run(venv_name, cmd)
    inenv = InenvManager()
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
        return
    else:
        venv = inenv.get_prepped_venv(venv_name)
        inenv.clear_extra_source_file()
        inenv.write_extra_source_file("source {}".format(venv.activate_shell_file))
        inenv.write_extra_source_file(override_envars_and_deactivate(inenv.get_envvars(venv_name)))
        if autojump_enabled():
            dir = inenv.guess_contents_dir(venv_name)
            inenv.write_extra_source_file('cd {}'.format(dir))
            click.echo(click.style("Jumping to {}".format(dir), fg='green'))
        sys.exit(EVAL_EXIT_CODE)

@click.argument('venv_name')
@main_cli.command()
def rm(venv_name):
    """ Removes the venv by name """
    inenv = InenvManager()
    venv = inenv.get_venv(venv_name)
    click.confirm("Delete dir {}".format(venv.path))
    shutil.rmtree(venv.path)

@click.argument('venv_name')
@main_cli.command()
def root(venv_name):
    """ Removes the venv by name """
    inenv = InenvManager()
    inenv.get_venv(venv_name)
    venv = inenv.registered_venvs[venv_name]
    click.echo(venv['root'])

@click.argument('venv_name')
@main_cli.command()
def init(venv_name):
    """Initializez a virtualenv"""
    inenv = InenvManager()
    inenv.get_prepped_venv(venv_name, skip_cached=False)
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
    click.echo(click.style("Your venv is ready. Enjoy!", fg='green'))

@main_cli.command()
def autojump():
    """Initializes a virtualenv"""
    currently_enabled = autojump_enabled()
    toggle_autojump()
    if not currently_enabled:
        click.echo(click.style("Autojump enabled", fg='green'))
    else:
        click.echo(click.style("Autojump disabled", fg='red'))

@main_cli.command()
def extra_source():
    """Path to file sourced after an inenv switch"""
    inenv = InenvManager()
    print inenv.extra_source_file

@main_cli.command('version')
def print_version():
    """Print the inenv version"""
    print version.__version__

def run_cli():
    try:
        inenv = InenvManager()
        for venv in inenv.registered_venvs.keys():
            new_switch = copy.deepcopy(switch_or_run)
            for param in new_switch.params:
                if param.name == 'venv_name':
                    param.default = venv
            main_cli.add_command(new_switch, name=venv, sort_later=True)
        main_cli(obj={}, prog_name="inenv")
    except InenvException as e:
        click.echo(click.style("{}".format(e.message), fg='red'))

if __name__ == '__main__':
    run_cli()
<commit_msg>Wrap prints in parens<commit_after>import copy
import shutil
import os
import sys

import click

from inenv import (InenvManager, INENV_ENV_VAR, EVAL_EXIT_CODE, InenvException,
                   autojump_enabled, toggle_autojump)
from utils import override_envars_and_deactivate
import version

def activator_warn(inenv):
    click.echo(click.style("Please add the following to your bash RC for auto switch.", fg='red'))
    click.echo(click.style("source {file}".format(file=inenv.activate_file), fg='green'))

class InenvCliGroup(click.Group):
    sort_later = set()

    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv
        matches = [x for x in self.list_commands(ctx)
                   if x.startswith(cmd_name)]
        if not matches:
            return None
        elif len(matches) == 1:
            return click.Group.get_command(self, ctx, matches[0])
        ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))

    def add_command(self, cmd, name=None, sort_later=False):
        super(InenvCliGroup, self).add_command(cmd, name=name)
        if sort_later:
            self.sort_later.add(name)

    def list_commands(self, ctx):
        core_commands, sort_later_commands = [], []
        for k, v in self.commands.items():
            if k in self.sort_later:
                sort_later_commands.append(k)
            else:
                core_commands.append(k)
        return sorted(core_commands) + sorted(sort_later_commands)

    def format_commands(self, ctx, formatter):
        """Extra format methods for multi methods that adds all the commands
        after the options.
        """
        core_commands, inenv_commands = [], []
        for subcommand in self.list_commands(ctx):
            cmd = self.get_command(ctx, subcommand)
            # What is this, the tool lied about a command.  Ignore it
            if cmd is None:
                continue

            help = cmd.short_help or ''
            if subcommand in self.sort_later:
                inenv_commands.append((subcommand, help))
            else:
                core_commands.append((subcommand, help))

        if core_commands:
            with formatter.section('Commands'):
                formatter.write_dl(core_commands)

        if inenv_commands:
            with formatter.section('Inenvs'):
                formatter.write_dl(inenv_commands)

@click.group(cls=InenvCliGroup, name='inenv')
@click.version_option(version=version.__version__)
def main_cli():
    pass

def _run(venv_name, cmd):
    if len(cmd) == 1:
        cmd = cmd[0].split()
    inenv = InenvManager()
    venv = inenv.get_prepped_venv(venv_name)
    venv.run(cmd, always_exit=True)

@click.argument('cmd', nargs=-1)
@click.option('--venv_name', default=None)
@click.command()
def switch_or_run(cmd, venv_name=None):
    """Switch or run in this env"""
    if cmd:
        return _run(venv_name, cmd)
    inenv = InenvManager()
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
        return
    else:
        venv = inenv.get_prepped_venv(venv_name)
        inenv.clear_extra_source_file()
        inenv.write_extra_source_file("source {}".format(venv.activate_shell_file))
        inenv.write_extra_source_file(override_envars_and_deactivate(inenv.get_envvars(venv_name)))
        if autojump_enabled():
            dir = inenv.guess_contents_dir(venv_name)
            inenv.write_extra_source_file('cd {}'.format(dir))
            click.echo(click.style("Jumping to {}".format(dir), fg='green'))
        sys.exit(EVAL_EXIT_CODE)

@click.argument('venv_name')
@main_cli.command()
def rm(venv_name):
    """ Removes the venv by name """
    inenv = InenvManager()
    venv = inenv.get_venv(venv_name)
    click.confirm("Delete dir {}".format(venv.path))
    shutil.rmtree(venv.path)

@click.argument('venv_name')
@main_cli.command()
def root(venv_name):
    """ Removes the venv by name """
    inenv = InenvManager()
    inenv.get_venv(venv_name)
    venv = inenv.registered_venvs[venv_name]
    click.echo(venv['root'])

@click.argument('venv_name')
@main_cli.command()
def init(venv_name):
    """Initializez a virtualenv"""
    inenv = InenvManager()
    inenv.get_prepped_venv(venv_name, skip_cached=False)
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
    click.echo(click.style("Your venv is ready. Enjoy!", fg='green'))

@main_cli.command()
def autojump():
    """Initializes a virtualenv"""
    currently_enabled = autojump_enabled()
    toggle_autojump()
    if not currently_enabled:
        click.echo(click.style("Autojump enabled", fg='green'))
    else:
        click.echo(click.style("Autojump disabled", fg='red'))

@main_cli.command()
def extra_source():
    """Path to file sourced after an inenv switch"""
    inenv = InenvManager()
    print(inenv.extra_source_file)

@main_cli.command('version')
def print_version():
    """Print the inenv version"""
    print(version.__version__)

def run_cli():
    try:
        inenv = InenvManager()
        for venv in inenv.registered_venvs.keys():
            new_switch = copy.deepcopy(switch_or_run)
            for param in new_switch.params:
                if param.name == 'venv_name':
                    param.default = venv
            main_cli.add_command(new_switch, name=venv, sort_later=True)
        main_cli(obj={}, prog_name="inenv")
    except InenvException as e:
        click.echo(click.style("{}".format(e.message), fg='red'))

if __name__ == '__main__':
    run_cli()
<|endoftext|>


<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
module: bigip_sys_global
short_description: Manage BIG-IP global settings
description:
   - Manage BIG-IP global settings
version_added: "2.2"
options:
  server:
    description:
      - BIG-IP host
    required: true
  server_port:
    description:
      - BIG-IP host port
    required: false
    default: 443
  password:
    description:
      - BIG-IP password
    required: true
  state:
    description:
      - The state of the variable on the system. When C(present), guarantees
        that an existing variable is set to C(value). When C(reset) sets the
        variable back to the default value. At least one of value and state
        C(reset) are required.
    required: false
    default: present
    choices:
      - present
      - reset
  user:
    description:
      - BIG-IP username
    required: true
    aliases:
      - username
  validate_certs:
    description:
      - If C(no), SSL certificates will not be validated. This should only be
        used on personally controlled sites using self-signed certificates.
    required: false
    default: true
notes:
  - Requires the f5-sdk Python package on the host. This is as easy as pip
    install f5-sdk
requirements:
  - f5-sdk
author:
    - Tim Rupp (@caphrim007)
'''

EXAMPLES = '''
'''

RETURN = '''
'''

try:
    from f5.bigip import ManagementRoot
    HAS_F5SDK = True
except ImportError:
    HAS_F5SDK = False

CHOICES = ['enabled', 'disabled']

class BigIpSysDb(object):
    def __init__(self, *args, **kwargs):
        if not HAS_F5SDK:
            raise F5SDKError("The python f5-sdk module is required")

        self.params = kwargs
        self.api = ManagementRoot(kwargs['server'],
                                  kwargs['user'],
                                  kwargs['password'],
                                  port=kwargs['server_port'])

    def flush(self):
        changed = self.update()
        current = self.read()
        result.update(**current)

        result.update(dict(changed=changed))
        return result

    def read(self):
        settings = self.api.tm.sys.global_settings.load()
        return settings

    def update(self):
        changed = False
        current = self.read()

        if self.params['security_banner']:
            if self.params['security_banner'] != current['guiSecurityBanner']:
                changed = True
        else:
            del self.params['security_banner']

        if self.params['banner_text']:
            if self.params['banner_text'] != current['guiSecurityBannerText']:
                changed = True
        else:
            del self.params['banner_text']

        if self.params['gui_setup']:
            if self.params['gui_setup'] != current['guiSetup']:
                changed = True
        else:
            del self.params['guiSetup']

        if self.params['lcd_display']:
            if self.params['lcd_display'] != current['lcdDisplay']:
                changed = True
        else:
            del self.params['lcd_display']

        if self.params['mgmt_dhcp']:
            if self.params['mgmt_dhcp'] != current['mgmtDhcp']:
                changed = True
        else:
            del self.params['mgmt_dhcp']

        if self.params['net_reboot']:
            if self.params['net_reboot'] != current['netReboot']:
                changed = True
        else:
            del self.params['net_reboot']

        if self.params['quiet_boot']:
            if self.params['quiet_boot'] != current['quietBoot']:
                changed = True
        else:
            del self.params['quiet_boot']

        if self.params['console_timeout']:
            if self.params['console_timeout'] != current['consoleInactivityTimeout']:
                changed = True
        else:
            del self.params['console_timeout']

        if self.params['check_mode']:
            return changed

        r = self.api.tm.sys.sshd.load()
        r.update(**self.params)

        return True

def main():
    argument_spec = f5_argument_spec()

    meta_args = dict(
        security_banner=dict(required=False, choices=CHOICES, default=None),
        banner_text=dict(required=False, default=None),
        gui_setup=dict(required=false, choices=CHOICES, default=None),
        lcd_display=dict(required=False, choices=CHOICES, default=None),
        mgmt_dhcp=dict(required=False, choices=CHOICES, default=None),
        net_reboot=dict(required=False, choices=CHOICES, default=None),
        quiet_boot=dict(required=False, choices=CHOICES, default=None),
        console_timeout=dict(required=False, type='int', default=None),
        state=dict(default='present', choices=['present'])
    )
    argument_spec.update(meta_args)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    try:
        obj = BigIpSysGlobal(**module.params)
        result = obj.flush()

        module.exit_json(**result)
    except F5ModuleError as e:
        module.fail_json(msg=str(e))

from ansible.module_utils.basic import *
from ansible.module_utils.f5 import *

if __name__ == '__main__':
    main()
<commit_msg>corrected formatting<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
module: bigip_sys_global
short_description: Manage BIG-IP global settings
description:
  - Manage BIG-IP global settings
version_added: "2.2"
options:
  server:
    description:
      - BIG-IP host
    required: true
  server_port:
    description:
      - BIG-IP host port
    required: false
    default: 443
  password:
    description:
      - BIG-IP password
    required: true
  state:
    description:
      - The state of the variable on the system. When C(present), guarantees
        that an existing variable is set to C(value). When C(reset) sets the
        variable back to the default value. At least one of value and state
        C(reset) are required.
    required: false
    default: present
    choices:
      - present
      - reset
  user:
    description:
      - BIG-IP username
    required: true
    aliases:
      - username
  validate_certs:
    description:
      - If C(no), SSL certificates will not be validated. This should only be
        used on personally controlled sites using self-signed certificates.
    required: false
    default: true
notes:
  - Requires the f5-sdk Python package on the host. This is as easy as pip
    install f5-sdk
requirements:
  - f5-sdk
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = '''
'''

RETURN = '''
'''

try:
    from f5.bigip import ManagementRoot
    HAS_F5SDK = True
except ImportError:
    HAS_F5SDK = False

CHOICES = ['enabled', 'disabled']

class BigIpSysDb(object):
    def __init__(self, *args, **kwargs):
        if not HAS_F5SDK:
            raise F5SDKError("The python f5-sdk module is required")

        self.params = kwargs
        self.api = ManagementRoot(kwargs['server'],
                                  kwargs['user'],
                                  kwargs['password'],
                                  port=kwargs['server_port'])

    def flush(self):
        changed = self.update()
        current = self.read()
        result.update(**current)

        result.update(dict(changed=changed))
        return result

    def read(self):
        settings = self.api.tm.sys.global_settings.load()
        return settings

    def update(self):
        changed = False
        current = self.read()

        if self.params['security_banner']:
            if self.params['security_banner'] != current['guiSecurityBanner']:
                changed = True
        else:
            del self.params['security_banner']

        if self.params['banner_text']:
            if self.params['banner_text'] != current['guiSecurityBannerText']:
                changed = True
        else:
            del self.params['banner_text']

        if self.params['gui_setup']:
            if self.params['gui_setup'] != current['guiSetup']:
                changed = True
        else:
            del self.params['guiSetup']

        if self.params['lcd_display']:
            if self.params['lcd_display'] != current['lcdDisplay']:
                changed = True
        else:
            del self.params['lcd_display']

        if self.params['mgmt_dhcp']:
            if self.params['mgmt_dhcp'] != current['mgmtDhcp']:
                changed = True
        else:
            del self.params['mgmt_dhcp']

        if self.params['net_reboot']:
            if self.params['net_reboot'] != current['netReboot']:
                changed = True
        else:
            del self.params['net_reboot']

        if self.params['quiet_boot']:
            if self.params['quiet_boot'] != current['quietBoot']:
                changed = True
        else:
            del self.params['quiet_boot']

        if self.params['console_timeout']:
            if self.params['console_timeout'] != current['consoleInactivityTimeout']:
                changed = True
        else:
            del self.params['console_timeout']

        if self.params['check_mode']:
            return changed

        r = self.api.tm.sys.sshd.load()
        r.update(**self.params)

        return True

def main():
    argument_spec = f5_argument_spec()

    meta_args = dict(
        security_banner=dict(required=False, choices=CHOICES, default=None),
        banner_text=dict(required=False, default=None),
        gui_setup=dict(required=false, choices=CHOICES, default=None),
        lcd_display=dict(required=False, choices=CHOICES, default=None),
        mgmt_dhcp=dict(required=False, choices=CHOICES, default=None),
        net_reboot=dict(required=False, choices=CHOICES, default=None),
        quiet_boot=dict(required=False, choices=CHOICES, default=None),
        console_timeout=dict(required=False, type='int', default=None),
        state=dict(default='present', choices=['present'])
    )
    argument_spec.update(meta_args)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True
    )

    try:
        obj = BigIpSysGlobal(**module.params)
        result = obj.flush()

        module.exit_json(**result)
    except F5ModuleError as e:
        module.fail_json(msg=str(e))

from ansible.module_utils.basic import *
from ansible.module_utils.f5 import *

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before># Yith Library Server is a password storage server.
# Copyright (C) 2012-2013 Yaco Sistemas
# Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com>
# Copyright (C) 2012-2014 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Yith Library Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.

import binascii

import requests

from pyramid.httpexceptions import HTTPUnauthorized

def get_user_info(settings, user_id):
    # Get a bearer token
    token_url = settings['twitter_bearer_token_url']
    key = settings['twitter_consumer_key']
    secret = settings['twitter_consumer_secret']
    auth = 'Basic ' + binascii.b2a_base64(key + ':' + secret)[:-1]

    response = requests.post(
        token_url,
        headers={
            'Authorization': auth,
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        data='grant_type=client_credentials',
    )
    if not response.ok:
        raise HTTPUnauthorized(response.text)

    data = response.json()
    assert data['token_type'] == 'bearer'
    access_token = data['access_token']

    # Call the user info rest API
    user_info_url = settings['twitter_user_info_url']

    response = requests.get(
        user_info_url,
        params={'user_id': user_id},
        headers={'Authorization': 'Bearer ' + access_token},
    )

    if not response.ok:
        raise HTTPUnauthorized(response.text)

    return response.json()
<commit_msg>Fix python3 support<commit_after># Yith Library Server is a password storage server.
# Copyright (C) 2012-2013 Yaco Sistemas
# Copyright (C) 2012-2013 Alejandro Blanco Escudero <alejandro.b.e@gmail.com>
# Copyright (C) 2012-2014 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com>
#
# This file is part of Yith Library Server.
#
# Yith Library Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Yith Library Server is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Yith Library Server.  If not, see <http://www.gnu.org/licenses/>.

import binascii

import requests

from pyramid.httpexceptions import HTTPUnauthorized

from yithlibraryserver.compat import text_type

def get_user_info(settings, user_id):
    # Get a bearer token
    token_url = settings['twitter_bearer_token_url']
    key = settings['twitter_consumer_key']
    secret = settings['twitter_consumer_secret']
    auth = key + ':' + secret
    auth = 'Basic ' + text_type(binascii.b2a_base64(auth.encode('ascii'))[:-1],
                                'ascii')

    response = requests.post(
        token_url,
        headers={
            'Authorization': auth.encode('ascii'),
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        data='grant_type=client_credentials',
    )
    if not response.ok:
        raise HTTPUnauthorized(response.text)

    data = response.json()
    assert data['token_type'] == 'bearer'
    access_token = data['access_token']

    # Call the user info rest API
    user_info_url = settings['twitter_user_info_url']

    response = requests.get(
        user_info_url,
        params={'user_id': user_id},
        headers={'Authorization': 'Bearer ' + access_token},
    )

    if not response.ok:
        raise HTTPUnauthorized(response.text)

    return response.json()
<|endoftext|>


<commit_before>#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import translator.toscalib.utils.yamlparser

log = logging.getLogger('tosca')

class EntityType(object):
    '''Base class for TOSCA elements.'''

    SECTIONS = (DERIVED_FROM, PROPERTIES, ATTRIBUTES, REQUIREMENTS,
                INTERFACES, CAPABILITIES) = \
               ('derived_from', 'properties', 'attributes', 'requirements',
                'interfaces', 'capabilities')

    '''TOSCA definition file.'''
    TOSCA_DEF_FILE = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "TOSCA_definition.yaml")

    loader = translator.toscalib.utils.yamlparser.load_yaml

    TOSCA_DEF = loader(TOSCA_DEF_FILE)

    RELATIONSHIP_TYPE = (DEPENDSON, HOSTEDON, CONNECTSTO, ATTACHTO) = \
                        ('tosca.relationships.DependsOn',
                         'tosca.relationships.HostedOn',
                         'tosca.relationships.ConnectsTo',
                         'tosca.relationships.AttachTo')

    NODE_PREFIX = 'tosca.nodes.'
    RELATIONSHIP_PREFIX = 'tosca.relationships.'
    CAPABILITY_PREFIX = 'tosca.capabilities.'
    INTERFACE_PREFIX = 'tosca.interfaces.'
    #currently the data types are defined only for network
    #but may have changes in the future.
    DATATYPE_PREFIX = 'tosca.datatypes.network.'
    TOSCA = 'tosca'

    def derived_from(self, defs):
        '''Return a type this type is derived from.'''
        return self.entity_value(defs, 'derived_from')

    def entity_value(self, defs, key):
        if key in defs:
            return defs[key]

    def get_value(self, ndtype, defs=None, parent=None):
        value = None
        if defs is None:
            defs = self.defs
        if ndtype in defs:
            value = defs[ndtype]
        if parent and not value:
            p = self.parent_type
            while value is None:
                #check parent node
                if not p:
                    break
                if p and p.type == 'tosca.nodes.Root':
                    break
                value = p.get_value(ndtype)
                p = p.parent_type
        return value
<commit_msg>Add missing TOSCA type keywords<commit_after>#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import translator.toscalib.utils.yamlparser

log = logging.getLogger('tosca')

class EntityType(object):
    '''Base class for TOSCA elements.'''

    SECTIONS = (DERIVED_FROM, PROPERTIES, ATTRIBUTES, REQUIREMENTS,
                INTERFACES, CAPABILITIES, RELATIONSHIP, CAPABILITY, TYPE) = \
               ('derived_from', 'properties', 'attributes', 'requirements',
                'interfaces', 'capabilities', 'relationship', 'capability',
                'type')

    '''TOSCA definition file.'''
    TOSCA_DEF_FILE = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "TOSCA_definition.yaml")

    loader = translator.toscalib.utils.yamlparser.load_yaml

    TOSCA_DEF = loader(TOSCA_DEF_FILE)

    RELATIONSHIP_TYPE = (DEPENDSON, HOSTEDON, CONNECTSTO, ATTACHTO) = \
                        ('tosca.relationships.DependsOn',
                         'tosca.relationships.HostedOn',
                         'tosca.relationships.ConnectsTo',
                         'tosca.relationships.AttachTo')

    NODE_PREFIX = 'tosca.nodes.'
    RELATIONSHIP_PREFIX = 'tosca.relationships.'
    CAPABILITY_PREFIX = 'tosca.capabilities.'
    INTERFACE_PREFIX = 'tosca.interfaces.'
    #currently the data types are defined only for network
    #but may have changes in the future.
    DATATYPE_PREFIX = 'tosca.datatypes.network.'
    TOSCA = 'tosca'

    def derived_from(self, defs):
        '''Return a type this type is derived from.'''
        return self.entity_value(defs, 'derived_from')

    def entity_value(self, defs, key):
        if key in defs:
            return defs[key]

    def get_value(self, ndtype, defs=None, parent=None):
        value = None
        if defs is None:
            defs = self.defs
        if ndtype in defs:
            value = defs[ndtype]
        if parent and not value:
            p = self.parent_type
            while value is None:
                #check parent node
                if not p:
                    break
                if p and p.type == 'tosca.nodes.Root':
                    break
                value = p.get_value(ndtype)
                p = p.parent_type
        return value
<|endoftext|>


<commit_before><commit_msg>Removed empty test runner script.<commit_after><|endoftext|>


<commit_before># coding: utf-8
from pupa.scrape import Scraper

from utils import lxmlize, CanadianLegislator as Legislator

import re

COUNCIL_PAGE = 'http://app.toronto.ca/im/council/councillors.jsp'

class TorontoPersonScraper(Scraper):

  def get_people(self):
    page = lxmlize(COUNCIL_PAGE)

    for a in page.xpath('//a[contains(@href,"councillors/")]'):
      if 'vacant' in a.attrib['href']:
        continue
      yield self.scrape_councilor(a.attrib['href'])

    a = page.xpath('//a[contains(@href,"mayor")]')[0]
    yield self.scrape_mayor(a.attrib['href'])

  def scrape_councilor(self, url):
    page = lxmlize(url)
    name = page.xpath('string(//h1)').split('Councillor')[1]
    ward_full = page.xpath('string(//strong[contains(text(), "Ward")][1])')
    ward_num, ward_name = re.search(r'(Ward \d+) (.+)', ward_full).groups()

    p = Legislator(name=name, post_id=ward_num, role='Councillor')
    p.add_source(COUNCIL_PAGE)
    p.add_source(url)

    p.image = page.xpath('string(//main//img/@src)')
    email = page.xpath('string((//a[contains(@href, "@")])[1])')
    p.add_contact('email', email, None)

    addr_cell = page.xpath('//*[contains(text(), "Toronto City Hall")]/'
                           'ancestor::td')[0]
    phone = (addr_cell.xpath('string((.//text()[contains(., "Phone:")])[1])')
                      .split(':')[1])
    p.add_contact('voice', phone, 'legislature')

    address = '\n'.join(addr_cell.xpath('./p[2]/text()')[:2])
    p.add_contact('address', address, 'legislature')

    return p

  def scrape_mayor(self, url):
    page = lxmlize(url)
    name = page.xpath("//h1/text()")[0].replace("Toronto Mayor", "").strip()

    p = Legislator(name, post_id="Toronto", role='Mayor')
    p.add_source(COUNCIL_PAGE)
    p.add_source(url)

    p.image = page.xpath('string(//article/img/@src)')

    url = page.xpath('//a[contains(text(), "Contact the Mayor")]')[0].attrib['href']
    url = url.replace('www.', 'www1.')  # @todo fix lxmlize to use the redirected URL to make links absolute
    p.add_source(url)
    page = lxmlize(url)

    mail_elem, phone_elem = page.xpath('//h3')[:2]
    address = ''.join(mail_elem.xpath('./following-sibling::p//text()'))
    phone = phone_elem.xpath('string(./following-sibling::p[1])')

    p.add_contact('address', address, 'legislature')
    p.add_contact('voice', phone, 'legislature')
    return p
<commit_msg>fix to blank addresses<commit_after># coding: utf-8
from pupa.scrape import Scraper

from utils import lxmlize, CanadianLegislator as Legislator

import re

COUNCIL_PAGE = 'http://app.toronto.ca/im/council/councillors.jsp'

class TorontoPersonScraper(Scraper):

  def get_people(self):
    page = lxmlize(COUNCIL_PAGE)

    for a in page.xpath('//a[contains(@href,"councillors/")]'):
      if 'vacant' in a.attrib['href']:
        continue
      yield self.scrape_councilor(a.attrib['href'])

    a = page.xpath('//a[contains(@href,"mayor")]')[0]
    yield self.scrape_mayor(a.attrib['href'])

  def scrape_councilor(self, url):
    page = lxmlize(url)
    name = page.xpath('string(//h1)').split('Councillor')[1]
    ward_full = page.xpath('string(//strong[contains(text(), "Ward")][1])')
    ward_num, ward_name = re.search(r'(Ward \d+) (.+)', ward_full).groups()

    p = Legislator(name=name, post_id=ward_num, role='Councillor')
    p.add_source(COUNCIL_PAGE)
    p.add_source(url)

    p.image = page.xpath('string(//main//img/@src)')
    email = page.xpath('string((//a[contains(@href, "@")])[1])')
    p.add_contact('email', email, None)

    addr_cell = page.xpath('//*[contains(text(), "Toronto City Hall")]/'
                           'ancestor::td')[0]
    phone = (addr_cell.xpath('string((.//text()[contains(., "Phone:")])[1])')
                      .split(':')[1])
    p.add_contact('voice', phone, 'legislature')

    address = '\n'.join(addr_cell.xpath('./p[2]/text()')[:2])
    if address:
        p.add_contact('address', address, 'legislature')

    return p

  def scrape_mayor(self, url):
    page = lxmlize(url)
    name = page.xpath("//h1/text()")[0].replace("Toronto Mayor", "").strip()

    p = Legislator(name, post_id="Toronto", role='Mayor')
    p.add_source(COUNCIL_PAGE)
    p.add_source(url)

    p.image = page.xpath('string(//article/img/@src)')

    url = page.xpath('//a[contains(text(), "Contact the Mayor")]')[0].attrib['href']
    url = url.replace('www.', 'www1.')  # @todo fix lxmlize to use the redirected URL to make links absolute
    p.add_source(url)
    page = lxmlize(url)

    mail_elem, phone_elem = page.xpath('//h3')[:2]
    address = ''.join(mail_elem.xpath('./following-sibling::p//text()'))
    phone = phone_elem.xpath('string(./following-sibling::p[1])')

    p.add_contact('address', address, 'legislature')
    p.add_contact('voice', phone, 'legislature')
    return p
<|endoftext|>