Set initial mode to lobby.

Set initial mode to lobby.

--- peloid/app/shell/service.py
+++ peloid/app/shell/service.py
@@ -3,6 +3,7 @@

 from carapace.util import ssh as util

+from peloid import const
 from peloid.app import mud
 from peloid.app.shell import gameshell, setupshell

@@ -17,6 +18,7 @@
     These two are passed in the call to peloid.app.service.makeService.
     """
     game = mud.Game()
+    game.setMode(const.modes.lobby)
     sshRealm = gameshell.TerminalRealm(namespace, game)
     sshPortal = portal.Portal(sshRealm)
     factory = gameshell.GameShellFactory(sshPortal)

<|original_code|>
from twisted.cred import portal
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid.app import mud
from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    """
    The "namespace" kwargs here contains the passed objects that will be
    accessible via the shell, namely:
     * "app"
     * "services"

    These two are passed in the call to peloid.app.service.makeService.
    """
    game = mud.Game()
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = gameshell.GameShellFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    return setupshell.SetupShellServerFactory(namespace)

<|edits_diff|>
--- peloid/app/shell/service.py
+++ peloid/app/shell/service.py
@@ -3,6 +3,7 @@

 from carapace.util import ssh as util

+from peloid import const
 from peloid.app import mud
 from peloid.app.shell import gameshell, setupshell

<|current_version|>
from twisted.cred import portal
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid import const
from peloid.app import mud
from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    """
    The "namespace" kwargs here contains the passed objects that will be
    accessible via the shell, namely:
     * "app"
     * "services"

    These two are passed in the call to peloid.app.service.makeService.
    """
    game = mud.Game()
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = gameshell.GameShellFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    return setupshell.SetupShellServerFactory(namespace)
<|next_version|>
from twisted.cred import portal
from twisted.conch.checkers import SSHPublicKeyDatabase

from carapace.util import ssh as util

from peloid import const
from peloid.app import mud
from peloid.app.shell import gameshell, setupshell

def getGameShellFactory(**namespace):
    """
    The "namespace" kwargs here contains the passed objects that will be
    accessible via the shell, namely:
     * "app"
     * "services"

    These two are passed in the call to peloid.app.service.makeService.
    """
    game = mud.Game()
    game.setMode(const.modes.lobby)
    sshRealm = gameshell.TerminalRealm(namespace, game)
    sshPortal = portal.Portal(sshRealm)
    factory = gameshell.GameShellFactory(sshPortal)
    factory.privateKeys = {'ssh-rsa': util.getPrivKey()}
    factory.publicKeys = {'ssh-rsa': util.getPubKey()}
    factory.portal.registerChecker(SSHPublicKeyDatabase())
    return factory

def getSetupShellFactory(**namespace):
    return setupshell.SetupShellServerFactory(namespace)


Include readme description in pypi.

Include readme description in pypi.

PiperOrigin-RevId: 426375123

--- setup.py
+++ setup.py
@@ -14,10 +14,16 @@
 # limitations under the License.

 """Setup file for installing the BLE."""
+import pathlib
 import setuptools
+
+current_directory = pathlib.Path(__file__).parent
+description = (current_directory / 'README.md').read_text()

 setuptools.setup(
     name='balloon_learning_environment',
+    long_description=description,
+    long_description_content_type='text/markdown',
     version='0.1.1',
     packages=setuptools.find_packages(),
     install_requires=[

<|original_code|>
# coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import setuptools

setuptools.setup(
    name='balloon_learning_environment',
    version='0.1.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl >= 4.0.0',
        'flax',
        'gcsfs',
        'gin-config',
        'gym',
        'opensimplex <= 0.3.0',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-datasets >= 4.4.0',
        'tensorflow-probability',
        'transitions',
        'zarr',
    ],
    package_data={
        '': ['*.msgpack', '*.pb', '*.gin'],
    },
    python_requires='>=3.7',
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -14,7 +14,11 @@
 # limitations under the License.

 """Setup file for installing the BLE."""
+import pathlib
 import setuptools
+
+current_directory = pathlib.Path(__file__).parent
+description = (current_directory / 'README.md').read_text()

 setuptools.setup(
     name='balloon_learning_environment',
<|current_version|>
# coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import pathlib
import setuptools

current_directory = pathlib.Path(__file__).parent
description = (current_directory / 'README.md').read_text()

setuptools.setup(
    name='balloon_learning_environment',
    version='0.1.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl >= 4.0.0',
        'flax',
        'gcsfs',
        'gin-config',
        'gym',
        'opensimplex <= 0.3.0',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-datasets >= 4.4.0',
        'tensorflow-probability',
        'transitions',
        'zarr',
    ],
    package_data={
        '': ['*.msgpack', '*.pb', '*.gin'],
    },
    python_requires='>=3.7',
)

<|next_version|>
# coding=utf-8
# Copyright 2022 The Balloon Learning Environment Authors.
#
# 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.

"""Setup file for installing the BLE."""
import pathlib
import setuptools

current_directory = pathlib.Path(__file__).parent
description = (current_directory / 'README.md').read_text()

setuptools.setup(
    name='balloon_learning_environment',
    long_description=description,
    long_description_content_type='text/markdown',
    version='0.1.1',
    packages=setuptools.find_packages(),
    install_requires=[
        'absl-py',
        'dopamine-rl >= 4.0.0',
        'flax',
        'gcsfs',
        'gin-config',
        'gym',
        'opensimplex <= 0.3.0',
        's2sphere',
        'scikit-learn',
        'tensorflow',
        'tensorflow-datasets >= 4.4.0',
        'tensorflow-probability',
        'transitions',
        'zarr',
    ],
    package_data={
        '': ['*.msgpack', '*.pb', '*.gin'],
    },
    python_requires='>=3.7',
)


Add test for API endpoint

Add test for API endpoint

--- tests.py
+++ tests.py
@@ -2,6 +2,7 @@

 """Test UW Menu Flask application."""

+import json
 import unittest

 from uwmenu import app, attach_filters
@@ -27,6 +28,11 @@
         rv = self.app.get('/')
         assert 'This is an open source application available on GitHub' in rv.data

+    def test_api_endpoint(self):
+        """Ensure API endpoint returns valid JSON."""
+        rv = self.app.get('/menu/')
+        assert json.loads(rv.data)
+

 if __name__ == "__main__":
     unittest.main()

<|original_code|>
#!/usr/bin/env python

"""Test UW Menu Flask application."""

import unittest

from uwmenu import app, attach_filters

class UWMenuTestCase(unittest.TestCase):

    def setUp(self):
        attach_filters()
        app.config['TESTING'] = True
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_menu_pageload(self):
        """Ensure description on menu page is present."""
        rv = self.app.get('/')
        assert 'Weekly menus for the University of Waterloo\'s on-campus eateries.' in rv.data

    def test_about_pageload(self):
        """Ensure attribution on about page is present."""
        rv = self.app.get('/')
        assert 'This is an open source application available on GitHub' in rv.data

if __name__ == "__main__":
    unittest.main()

<|edits_diff|>
--- tests.py
+++ tests.py
@@ -2,6 +2,7 @@

 """Test UW Menu Flask application."""

+import json
 import unittest

 from uwmenu import app, attach_filters
<|current_version|>
#!/usr/bin/env python

"""Test UW Menu Flask application."""

import json
import unittest

from uwmenu import app, attach_filters

class UWMenuTestCase(unittest.TestCase):

    def setUp(self):
        attach_filters()
        app.config['TESTING'] = True
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_menu_pageload(self):
        """Ensure description on menu page is present."""
        rv = self.app.get('/')
        assert 'Weekly menus for the University of Waterloo\'s on-campus eateries.' in rv.data

    def test_about_pageload(self):
        """Ensure attribution on about page is present."""
        rv = self.app.get('/')
        assert 'This is an open source application available on GitHub' in rv.data

if __name__ == "__main__":
    unittest.main()

<|next_version|>
#!/usr/bin/env python

"""Test UW Menu Flask application."""

import json
import unittest

from uwmenu import app, attach_filters

class UWMenuTestCase(unittest.TestCase):

    def setUp(self):
        attach_filters()
        app.config['TESTING'] = True
        self.app = app.test_client()

    def tearDown(self):
        pass

    def test_menu_pageload(self):
        """Ensure description on menu page is present."""
        rv = self.app.get('/')
        assert 'Weekly menus for the University of Waterloo\'s on-campus eateries.' in rv.data

    def test_about_pageload(self):
        """Ensure attribution on about page is present."""
        rv = self.app.get('/')
        assert 'This is an open source application available on GitHub' in rv.data

    def test_api_endpoint(self):
        """Ensure API endpoint returns valid JSON."""
        rv = self.app.get('/menu/')
        assert json.loads(rv.data)

if __name__ == "__main__":
    unittest.main()


Allow to add contact to logged in users.

--- tovp/contacts/lookups.py
+++ tovp/contacts/lookups.py
@@ -1,4 +1,5 @@
 from ajax_select import LookupChannel
+from django.core.exceptions import PermissionDenied
 from django.utils.html import escape
 from django.db.models import Q
 from .models import Person
@@ -22,3 +23,8 @@
     def format_item_display(self, obj):
         """ (HTML) formatted item for displaying item in the selected deck area """
         return u"%s

" % (escape(obj.mixed_name))
+
+    def check_auth(self, request):
+        """Return results only to logged users."""
+        if not request.user.is_authenticated():
+            raise PermissionDenied

<|original_code|>
from ajax_select import LookupChannel
from django.utils.html import escape
from django.db.models import Q
from .models import Person

class PersonLookup(LookupChannel):

    model = Person

    def get_query(self, q, request):
        return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q))  # .order_by('name')

    def get_result(self, obj):
        u""" result is the simple text that is the completion of what the person typed """
        return obj.mixed_name

    def format_match(self, obj):
        """ (HTML) formatted item for display in the dropdown """
        return self.format_item_display(obj)

    def format_item_display(self, obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return u"%s

" % (escape(obj.mixed_name))

<|edits_diff|>
--- tovp/contacts/lookups.py
+++ tovp/contacts/lookups.py
@@ -1,4 +1,5 @@
 from ajax_select import LookupChannel
+from django.core.exceptions import PermissionDenied
 from django.utils.html import escape
 from django.db.models import Q
 from .models import Person
<|current_version|>
from ajax_select import LookupChannel
from django.core.exceptions import PermissionDenied
from django.utils.html import escape
from django.db.models import Q
from .models import Person

class PersonLookup(LookupChannel):

    model = Person

    def get_query(self, q, request):
        return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q))  # .order_by('name')

    def get_result(self, obj):
        u""" result is the simple text that is the completion of what the person typed """
        return obj.mixed_name

    def format_match(self, obj):
        """ (HTML) formatted item for display in the dropdown """
        return self.format_item_display(obj)

    def format_item_display(self, obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return u"%s

" % (escape(obj.mixed_name))

<|next_version|>
from ajax_select import LookupChannel
from django.core.exceptions import PermissionDenied
from django.utils.html import escape
from django.db.models import Q
from .models import Person

class PersonLookup(LookupChannel):

    model = Person

    def get_query(self, q, request):
        return Person.objects.filter(Q(first_name__icontains=q) | Q(initiated_name__icontains=q) | Q(last_name__istartswith=q))  # .order_by('name')

    def get_result(self, obj):
        u""" result is the simple text that is the completion of what the person typed """
        return obj.mixed_name

    def format_match(self, obj):
        """ (HTML) formatted item for display in the dropdown """
        return self.format_item_display(obj)

    def format_item_display(self, obj):
        """ (HTML) formatted item for displaying item in the selected deck area """
        return u"%s

" % (escape(obj.mixed_name))

    def check_auth(self, request):
        """Return results only to logged users."""
        if not request.user.is_authenticated():
            raise PermissionDenied


Fix servo sweep example in docs

Fix servo sweep example in docs

--- docs/examples/servo_sweep.py
+++ docs/examples/servo_sweep.py
@@ -1,7 +1,10 @@
 from gpiozero import Servo
 from gpiozero.tools import sin_values
+from signal import pause

 servo = Servo(17)

 servo.source = sin_values()
 servo.source_delay = 0.1
+
+pause()

<|original_code|>
from gpiozero import Servo
from gpiozero.tools import sin_values

servo = Servo(17)

servo.source = sin_values()
servo.source_delay = 0.1

<|edits_diff|>
--- docs/examples/servo_sweep.py
+++ docs/examples/servo_sweep.py
@@ -1,5 +1,6 @@
 from gpiozero import Servo
 from gpiozero.tools import sin_values
+from signal import pause

 servo = Servo(17)

<|current_version|>
from gpiozero import Servo
from gpiozero.tools import sin_values
from signal import pause

servo = Servo(17)

servo.source = sin_values()
servo.source_delay = 0.1

<|next_version|>
from gpiozero import Servo
from gpiozero.tools import sin_values
from signal import pause

servo = Servo(17)

servo.source = sin_values()
servo.source_delay = 0.1

pause()


Add `polymorphic` to `INSTALLED_APPS`, and also `MessageMiddlware` (because Django wants it).

--- polymorphic_auth/tests/settings.py
+++ polymorphic_auth/tests/settings.py
@@ -25,6 +25,7 @@
     'django.contrib.sessions',
     'django.contrib.staticfiles',
     'django_nose',
+    'polymorphic',
     'polymorphic_auth',
     'polymorphic_auth.tests',
     'polymorphic_auth.usertypes.email',
@@ -33,6 +34,7 @@
 MIDDLEWARE_CLASSES = (
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
 )

 ROOT_URLCONF = 'polymorphic_auth.tests.urls'

<|original_code|>
"""
Test settings for ``polymorphic_auth`` app.
"""

AUTH_USER_MODEL = 'polymorphic_auth.User'
POLYMORPHIC_AUTH = {
    'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser',
}

DATABASES = {
    'default': {
        'ATOMIC_REQUESTS': True,
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'polymorphic_auth',
    }
}

DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_nose',
    'polymorphic_auth',
    'polymorphic_auth.tests',
    'polymorphic_auth.usertypes.email',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'polymorphic_auth.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

<|edits_diff|>
--- polymorphic_auth/tests/settings.py
+++ polymorphic_auth/tests/settings.py
@@ -25,6 +25,7 @@
     'django.contrib.sessions',
     'django.contrib.staticfiles',
     'django_nose',
+    'polymorphic',
     'polymorphic_auth',
     'polymorphic_auth.tests',
     'polymorphic_auth.usertypes.email',
<|current_version|>
"""
Test settings for ``polymorphic_auth`` app.
"""

AUTH_USER_MODEL = 'polymorphic_auth.User'
POLYMORPHIC_AUTH = {
    'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser',
}

DATABASES = {
    'default': {
        'ATOMIC_REQUESTS': True,
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'polymorphic_auth',
    }
}

DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_nose',
    'polymorphic',
    'polymorphic_auth',
    'polymorphic_auth.tests',
    'polymorphic_auth.usertypes.email',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
)

ROOT_URLCONF = 'polymorphic_auth.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'

<|next_version|>
"""
Test settings for ``polymorphic_auth`` app.
"""

AUTH_USER_MODEL = 'polymorphic_auth.User'
POLYMORPHIC_AUTH = {
    'DEFAULT_CHILD_MODEL': 'polymorphic_auth_email.EmailUser',
}

DATABASES = {
    'default': {
        'ATOMIC_REQUESTS': True,
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'polymorphic_auth',
    }
}

DEBUG = True
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
    'django_nose',
    'polymorphic',
    'polymorphic_auth',
    'polymorphic_auth.tests',
    'polymorphic_auth.usertypes.email',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'polymorphic_auth.tests.urls'
SECRET_KEY = 'secret-key'
STATIC_URL = '/static/'
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'


Add check for PDF files

Add check for PDF files

--- ckanext/romania_theme/plugin.py
+++ ckanext/romania_theme/plugin.py
@@ -15,7 +15,9 @@
 class Romania_ThemePlugin(plugins.SingletonPlugin):
     plugins.implements(plugins.IConfigurer)
     plugins.implements(plugins.ITemplateHelpers)
+    plugins.implements(plugins.IResourceController)

+    # IConfigurer
     def update_config(self, config):
         toolkit.add_template_directory(config, 'templates')
         toolkit.add_public_directory(config, 'public')
@@ -24,3 +26,8 @@
     def get_helpers(self):
         return {'get_number_of_files': get_number_of_files,
                 'get_number_of_external_links': get_number_of_external_links}
+
++   # IResourceController
+    def before_create(self, context, resource):
+        if resource['upload'].type == 'application/pdf':
+            raise ValidationError(['Resource type not allowed as resource.'])

<|original_code|>
import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os

def get_number_of_files():
    return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]

def get_number_of_external_links():
    return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0]

class Romania_ThemePlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.ITemplateHelpers)

    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')
        toolkit.add_public_directory(config, 'public')
        toolkit.add_resource('fanstatic', 'romania_theme')

    def get_helpers(self):
        return {'get_number_of_files': get_number_of_files,
                'get_number_of_external_links': get_number_of_external_links}

<|edits_diff|>
--- ckanext/romania_theme/plugin.py
+++ ckanext/romania_theme/plugin.py
@@ -15,7 +15,9 @@
 class Romania_ThemePlugin(plugins.SingletonPlugin):
     plugins.implements(plugins.IConfigurer)
     plugins.implements(plugins.ITemplateHelpers)
+    plugins.implements(plugins.IResourceController)

+    # IConfigurer
     def update_config(self, config):
         toolkit.add_template_directory(config, 'templates')
         toolkit.add_public_directory(config, 'public')
<|current_version|>
import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os

def get_number_of_files():
    return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]

def get_number_of_external_links():
    return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0]

class Romania_ThemePlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.ITemplateHelpers)
    plugins.implements(plugins.IResourceController)

    # IConfigurer
    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')
        toolkit.add_public_directory(config, 'public')
        toolkit.add_resource('fanstatic', 'romania_theme')

    def get_helpers(self):
        return {'get_number_of_files': get_number_of_files,
                'get_number_of_external_links': get_number_of_external_links}

<|next_version|>
import ckan.model as model
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import os

def get_number_of_files():
    return model.Session.execute("select count(*) from resource where state = 'active'").first()[0]

def get_number_of_external_links():
    return model.Session.execute("select count(*) from resource where state = 'active' and url not LIKE '%data.gov.ro%'").first()[0]

class Romania_ThemePlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.ITemplateHelpers)
    plugins.implements(plugins.IResourceController)

    # IConfigurer
    def update_config(self, config):
        toolkit.add_template_directory(config, 'templates')
        toolkit.add_public_directory(config, 'public')
        toolkit.add_resource('fanstatic', 'romania_theme')

    def get_helpers(self):
        return {'get_number_of_files': get_number_of_files,
                'get_number_of_external_links': get_number_of_external_links}

+   # IResourceController
    def before_create(self, context, resource):
        if resource['upload'].type == 'application/pdf':
            raise ValidationError(['Resource type not allowed as resource.'])


Add test for run-together interpolated expressions.

--- tests/circular/template/test_interpolatedstr.py
+++ tests/circular/template/test_interpolatedstr.py
@@ -17,6 +17,11 @@
     data = t.events.pop().data
     assert s.value == "My name is Bond, James Bond."

+    # Should correctly interpolate two immediately succeeding expressions
+    ctx.sur="B"
+    s = InterpolatedStr('{{name}}{{sur}}')
+    s.bind_ctx(ctx)
+    assert s.value == "JamesB"

@@ -25,3 +30,4 @@

+

<|original_code|>
from src.circular.template.interpolatedstr import InterpolatedStr
from src.circular.template.context import Context
from tests.utils import TObserver

def test_string_interp():
    ctx = Context()
    ctx.name = "James"
    s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.")
    s.bind_ctx(ctx)
    t = TObserver(s)
    assert s.value == "My name is , James ."

    ctx.surname = "Bond"
    data = t.events.pop().data
    assert s.value == "My name is Bond, James Bond."

<|edits_diff|>
--- tests/circular/template/test_interpolatedstr.py
+++ tests/circular/template/test_interpolatedstr.py
@@ -17,6 +17,11 @@
     data = t.events.pop().data
     assert s.value == "My name is Bond, James Bond."

+    # Should correctly interpolate two immediately succeeding expressions
+    ctx.sur="B"
+    s = InterpolatedStr('{{name}}{{sur}}')
+    s.bind_ctx(ctx)
+    assert s.value == "JamesB"

<|current_version|>
from src.circular.template.interpolatedstr import InterpolatedStr
from src.circular.template.context import Context
from tests.utils import TObserver

def test_string_interp():
    ctx = Context()
    ctx.name = "James"
    s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.")
    s.bind_ctx(ctx)
    t = TObserver(s)
    assert s.value == "My name is , James ."

    ctx.surname = "Bond"
    data = t.events.pop().data
    assert s.value == "My name is Bond, James Bond."

    # Should correctly interpolate two immediately succeeding expressions
    ctx.sur="B"
    s = InterpolatedStr('{{name}}{{sur}}')
    s.bind_ctx(ctx)
    assert s.value == "JamesB"

<|next_version|>
from src.circular.template.interpolatedstr import InterpolatedStr
from src.circular.template.context import Context
from tests.utils import TObserver

def test_string_interp():
    ctx = Context()
    ctx.name = "James"
    s = InterpolatedStr("My name is {{ surname }}, {{name}} {{ surname}}.")
    s.bind_ctx(ctx)
    t = TObserver(s)
    assert s.value == "My name is , James ."

    ctx.surname = "Bond"
    data = t.events.pop().data
    assert s.value == "My name is Bond, James Bond."

    # Should correctly interpolate two immediately succeeding expressions
    ctx.sur="B"
    s = InterpolatedStr('{{name}}{{sur}}')
    s.bind_ctx(ctx)
    assert s.value == "JamesB"


Support development versions using an environment variable

--- pinax/__init__.py
+++ pinax/__init__.py
@@ -1,3 +1,6 @@
+import os
+
+
 VERSION = (0, 9, 0, "a", 1) # following PEP 386

@@ -7,6 +10,9 @@
         version = "%s.%s" % (version, VERSION[2])
     if VERSION[3] != "f":
         version = "%s%s%s" % (version, VERSION[3], VERSION[4])
+        dev = os.environ.get("PINAX_DEV_N")
+        if dev:
+            version = "%s.dev%s" % (version, dev)
     return version

<|original_code|>
VERSION = (0, 9, 0, "a", 1) # following PEP 386

def get_version():
    version = "%s.%s" % (VERSION[0], VERSION[1])
    if VERSION[2]:
        version = "%s.%s" % (version, VERSION[2])
    if VERSION[3] != "f":
        version = "%s%s%s" % (version, VERSION[3], VERSION[4])
    return version

__version__ = get_version()
<|edits_diff|>
--- pinax/__init__.py
+++ pinax/__init__.py
@@ -1,3 +1,6 @@
+import os
+
+
 VERSION = (0, 9, 0, "a", 1) # following PEP 386

<|current_version|>
import os

VERSION = (0, 9, 0, "a", 1) # following PEP 386

def get_version():
    version = "%s.%s" % (VERSION[0], VERSION[1])
    if VERSION[2]:
        version = "%s.%s" % (version, VERSION[2])
    if VERSION[3] != "f":
        version = "%s%s%s" % (version, VERSION[3], VERSION[4])
    return version

__version__ = get_version()
<|next_version|>
import os

VERSION = (0, 9, 0, "a", 1) # following PEP 386

def get_version():
    version = "%s.%s" % (VERSION[0], VERSION[1])
    if VERSION[2]:
        version = "%s.%s" % (version, VERSION[2])
    if VERSION[3] != "f":
        version = "%s%s%s" % (version, VERSION[3], VERSION[4])
        dev = os.environ.get("PINAX_DEV_N")
        if dev:
            version = "%s.dev%s" % (version, dev)
    return version

__version__ = get_version()


Make front page be == /search/

Make front page be == /search/

--- mysite/urls.py
+++ mysite/urls.py
@@ -10,4 +10,7 @@
     (r'^admin/(.*)', admin.site.root),
     (r'^static/(?P<path>.*)$', 'django.views.static.serve',
      {'document_root': settings.STATIC_DOC_ROOT}),
+    (r'^$', 'mysite.search.views.fetch_bugs'),
 )
+
+

<|original_code|>
from django.conf.urls.defaults import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^search/$', 'mysite.search.views.fetch_bugs'),
    (r'^admin/(.*)', admin.site.root),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root': settings.STATIC_DOC_ROOT}),
)

<|edits_diff|>
--- mysite/urls.py
+++ mysite/urls.py
@@ -10,4 +10,5 @@
     (r'^admin/(.*)', admin.site.root),
     (r'^static/(?P<path>.*)$', 'django.views.static.serve',
      {'document_root': settings.STATIC_DOC_ROOT}),
+    (r'^$', 'mysite.search.views.fetch_bugs'),
 )
<|current_version|>
from django.conf.urls.defaults import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^search/$', 'mysite.search.views.fetch_bugs'),
    (r'^admin/(.*)', admin.site.root),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root': settings.STATIC_DOC_ROOT}),
    (r'^$', 'mysite.search.views.fetch_bugs'),
)

<|next_version|>
from django.conf.urls.defaults import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    (r'^search/$', 'mysite.search.views.fetch_bugs'),
    (r'^admin/(.*)', admin.site.root),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root': settings.STATIC_DOC_ROOT}),
    (r'^$', 'mysite.search.views.fetch_bugs'),
)


Add Semester str method for admin interface.

Fixes #149

--- planner/models.py
+++ planner/models.py
@@ -20,9 +20,13 @@
         return self.name

+@python_2_unicode_compatible
 class Semester(models.Model):
     active = models.BooleanField(default=True)
     date = models.DateField()
+
+    def __str__(self):
+        return str(self.date)

 # XXX: This is locked in for the default value of the initial migration.

<|original_code|>
import datetime

from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

class Milestone(models.Model):
    date = models.DateTimeField()

@python_2_unicode_compatible
class School(models.Model):
    name = models.TextField()
    slug = models.SlugField(max_length=256, unique=True)
    url = models.URLField(unique=True)
    milestones_url = models.URLField()

    def __str__(self):
        return self.name

class Semester(models.Model):
    active = models.BooleanField(default=True)
    date = models.DateField()

# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
    today = datetime.date.today()
    return today.year

@python_2_unicode_compatible
class Student(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
    first_name = models.TextField()
    last_name = models.TextField()
    # XXX: Remove null constraint after migration.
    matriculation_semester = models.ForeignKey(
        Semester, null=True, on_delete=models.PROTECT)

    def __str__(self):
        return '{} {}'.format(self.first_name, self.last_name)

<|edits_diff|>
--- planner/models.py
+++ planner/models.py
@@ -20,6 +20,7 @@
         return self.name

+@python_2_unicode_compatible
 class Semester(models.Model):
     active = models.BooleanField(default=True)
     date = models.DateField()
<|current_version|>
import datetime

from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

class Milestone(models.Model):
    date = models.DateTimeField()

@python_2_unicode_compatible
class School(models.Model):
    name = models.TextField()
    slug = models.SlugField(max_length=256, unique=True)
    url = models.URLField(unique=True)
    milestones_url = models.URLField()

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Semester(models.Model):
    active = models.BooleanField(default=True)
    date = models.DateField()

# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
    today = datetime.date.today()
    return today.year

@python_2_unicode_compatible
class Student(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
    first_name = models.TextField()
    last_name = models.TextField()
    # XXX: Remove null constraint after migration.
    matriculation_semester = models.ForeignKey(
        Semester, null=True, on_delete=models.PROTECT)

    def __str__(self):
        return '{} {}'.format(self.first_name, self.last_name)

<|next_version|>
import datetime

from django.conf import settings
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

class Milestone(models.Model):
    date = models.DateTimeField()

@python_2_unicode_compatible
class School(models.Model):
    name = models.TextField()
    slug = models.SlugField(max_length=256, unique=True)
    url = models.URLField(unique=True)
    milestones_url = models.URLField()

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Semester(models.Model):
    active = models.BooleanField(default=True)
    date = models.DateField()

    def __str__(self):
        return str(self.date)

# XXX: This is locked in for the default value of the initial migration.
# I'm not sure what needs to be done to let me safely delete this and
# have migrations continue to work.
def current_year():
    today = datetime.date.today()
    return today.year

@python_2_unicode_compatible
class Student(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='students')
    first_name = models.TextField()
    last_name = models.TextField()
    # XXX: Remove null constraint after migration.
    matriculation_semester = models.ForeignKey(
        Semester, null=True, on_delete=models.PROTECT)

    def __str__(self):
        return '{} {}'.format(self.first_name, self.last_name)


Disable one test in windows-only

Disable one test in windows-only

--- test/bibliopixel/threads/sub_test.py
+++ test/bibliopixel/threads/sub_test.py
@@ -1,5 +1,6 @@
 import functools, time, unittest
 from bibliopixel.util.threads import sub
+from .. import mark_tests

 WAIT_FOR_SUB = 0.1

@@ -34,6 +35,7 @@
         pause(WAIT_FOR_SUB)
         self.assertFalse(s.is_alive())

+    @mark_tests.fails_on_windows
     def test_subprocess(self):
         self.do_test(True)

<|original_code|>
import functools, time, unittest
from bibliopixel.util.threads import sub

WAIT_FOR_SUB = 0.1

def pause(delay=0.01):
    time.sleep(delay)

def run(input, output, *arg, **kwds):
    pause()

    output.put('first')

    if arg != (1, 2, 3):
        raise ValueError('1 2 3')

    if kwds != dict(a=1):
        raise ValueError('a=1')

    pause()
    output.put('second')

class SubTest(unittest.TestCase):
    def do_test(self, use_subprocess):
        s, input, output = sub.run(
            run, 1, 2, 3, a=1, use_subprocess=use_subprocess)
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'first')
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'second')
        pause(WAIT_FOR_SUB)
        self.assertFalse(s.is_alive())

    def test_subprocess(self):
        self.do_test(True)

    def test_threading(self):
        self.do_test(False)

<|edits_diff|>
--- test/bibliopixel/threads/sub_test.py
+++ test/bibliopixel/threads/sub_test.py
@@ -1,5 +1,6 @@
 import functools, time, unittest
 from bibliopixel.util.threads import sub
+from .. import mark_tests

 WAIT_FOR_SUB = 0.1

<|current_version|>
import functools, time, unittest
from bibliopixel.util.threads import sub
from .. import mark_tests

WAIT_FOR_SUB = 0.1

def pause(delay=0.01):
    time.sleep(delay)

def run(input, output, *arg, **kwds):
    pause()

    output.put('first')

    if arg != (1, 2, 3):
        raise ValueError('1 2 3')

    if kwds != dict(a=1):
        raise ValueError('a=1')

    pause()
    output.put('second')

class SubTest(unittest.TestCase):
    def do_test(self, use_subprocess):
        s, input, output = sub.run(
            run, 1, 2, 3, a=1, use_subprocess=use_subprocess)
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'first')
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'second')
        pause(WAIT_FOR_SUB)
        self.assertFalse(s.is_alive())

    def test_subprocess(self):
        self.do_test(True)

    def test_threading(self):
        self.do_test(False)

<|next_version|>
import functools, time, unittest
from bibliopixel.util.threads import sub
from .. import mark_tests

WAIT_FOR_SUB = 0.1

def pause(delay=0.01):
    time.sleep(delay)

def run(input, output, *arg, **kwds):
    pause()

    output.put('first')

    if arg != (1, 2, 3):
        raise ValueError('1 2 3')

    if kwds != dict(a=1):
        raise ValueError('a=1')

    pause()
    output.put('second')

class SubTest(unittest.TestCase):
    def do_test(self, use_subprocess):
        s, input, output = sub.run(
            run, 1, 2, 3, a=1, use_subprocess=use_subprocess)
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'first')
        self.assertTrue(s.is_alive())
        self.assertEqual(output.get(), 'second')
        pause(WAIT_FOR_SUB)
        self.assertFalse(s.is_alive())

    @mark_tests.fails_on_windows
    def test_subprocess(self):
        self.do_test(True)

    def test_threading(self):
        self.do_test(False)


Add markdownx url, Add add-tutrorial url

--- tutorials/urls.py
+++ tutorials/urls.py
@@ -1,8 +1,12 @@
 from django.conf.urls import include, url
+from markdownx import urls as markdownx

 from tutorials import views

 urlpatterns = [
     url(r'^$', views.ListTutorials.as_view()),
     url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
+    # this not working correctly - some error in gatherTutorials
+    url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
+    url(r'^markdownx/', include(markdownx)),
 ]

<|original_code|>
from django.conf.urls import include, url

from tutorials import views

urlpatterns = [
    url(r'^$', views.ListTutorials.as_view()),
    url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
]
<|edits_diff|>
--- tutorials/urls.py
+++ tutorials/urls.py
@@ -1,4 +1,5 @@
 from django.conf.urls import include, url
+from markdownx import urls as markdownx

 from tutorials import views

<|current_version|>
from django.conf.urls import include, url
from markdownx import urls as markdownx

from tutorials import views

urlpatterns = [
    url(r'^$', views.ListTutorials.as_view()),
    url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
]
<|next_version|>
from django.conf.urls import include, url
from markdownx import urls as markdownx

from tutorials import views

urlpatterns = [
    url(r'^$', views.ListTutorials.as_view()),
    url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
    # this not working correctly - some error in gatherTutorials
    url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
    url(r'^markdownx/', include(markdownx)),
]


Add form content to the index page.

Add form content to the index page.

--- real_estate_agency/real_estate_agency/views.py
+++ real_estate_agency/real_estate_agency/views.py
@@ -2,6 +2,7 @@
 from django.template import RequestContext

 from new_buildings.models import Builder, ResidentalComplex, NewApartment
+from new_buildings.forms import SearchForm
 from feedback.models import Feedback
 from company.views import about_company_in_digits_context_processor

@@ -13,6 +14,7 @@
     feedbacks = Feedback.objects.all()[:4]
     context = {
         'feedbacks': feedbacks,
+        'form': SearchForm,
     }
     context.update(about_company_in_digits_context_processor(request))
     return render(request,

<|original_code|>
from django.shortcuts import render,render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    feedbacks = Feedback.objects.all()[:4]
    context = {
        'feedbacks': feedbacks,
    }
    context.update(about_company_in_digits_context_processor(request))
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')
<|edits_diff|>
--- real_estate_agency/real_estate_agency/views.py
+++ real_estate_agency/real_estate_agency/views.py
@@ -2,6 +2,7 @@
 from django.template import RequestContext

 from new_buildings.models import Builder, ResidentalComplex, NewApartment
+from new_buildings.forms import SearchForm
 from feedback.models import Feedback
 from company.views import about_company_in_digits_context_processor

<|current_version|>
from django.shortcuts import render,render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    feedbacks = Feedback.objects.all()[:4]
    context = {
        'feedbacks': feedbacks,
    }
    context.update(about_company_in_digits_context_processor(request))
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')
<|next_version|>
from django.shortcuts import render,render_to_response
from django.template import RequestContext

from new_buildings.models import Builder, ResidentalComplex, NewApartment
from new_buildings.forms import SearchForm
from feedback.models import Feedback
from company.views import about_company_in_digits_context_processor

def corporation_benefit_plan(request):
    return render(request, 'corporation_benefit_plan.html')

def index(request):
    feedbacks = Feedback.objects.all()[:4]
    context = {
        'feedbacks': feedbacks,
        'form': SearchForm,
    }
    context.update(about_company_in_digits_context_processor(request))
    return render(request,
                  'index.html',
                  context,
                  )

def privacy_policy(request):
    return render(request, 'privacy_policy.html')

def thanks(request):
    return render(request, 'thanks.html')


Add more verbose error to reporte on Travis parserXML.py

--- unitTestUtils/parseXML.py
+++ unitTestUtils/parseXML.py
@@ -16,8 +16,10 @@
             tree = ET.parse(infile)
             root = tree.getroot()
             if root.findall('.//FatalError'):
+                element=root.findall('.//FatalError')[0]
                 eprint("Error detected")
                 print(infile)
+                print(element.text)
                 sys.exit(1)
         except ParseError:
             eprint("The file xml isn't correct. There were some mistakes in the tests ")

<|original_code|>
#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def parse():
    for infile in glob.glob('*.xml'):
        try:
            tree = ET.parse(infile)
            root = tree.getroot()
            if root.findall('.//FatalError'):
                eprint("Error detected")
                print(infile)
                sys.exit(1)
        except ParseError:
            eprint("The file xml isn't correct. There were some mistakes in the tests ")
            sys.exit(1)

def main():
    parse()

if __name__ == '__main__':
    main()

<|edits_diff|>
--- unitTestUtils/parseXML.py
+++ unitTestUtils/parseXML.py
@@ -16,6 +16,7 @@
             tree = ET.parse(infile)
             root = tree.getroot()
             if root.findall('.//FatalError'):
+                element=root.findall('.//FatalError')[0]
                 eprint("Error detected")
                 print(infile)
                 sys.exit(1)
<|current_version|>
#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def parse():
    for infile in glob.glob('*.xml'):
        try:
            tree = ET.parse(infile)
            root = tree.getroot()
            if root.findall('.//FatalError'):
                element=root.findall('.//FatalError')[0]
                eprint("Error detected")
                print(infile)
                sys.exit(1)
        except ParseError:
            eprint("The file xml isn't correct. There were some mistakes in the tests ")
            sys.exit(1)

def main():
    parse()

if __name__ == '__main__':
    main()

<|next_version|>
#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def parse():
    for infile in glob.glob('*.xml'):
        try:
            tree = ET.parse(infile)
            root = tree.getroot()
            if root.findall('.//FatalError'):
                element=root.findall('.//FatalError')[0]
                eprint("Error detected")
                print(infile)
                print(element.text)
                sys.exit(1)
        except ParseError:
            eprint("The file xml isn't correct. There were some mistakes in the tests ")
            sys.exit(1)

def main():
    parse()

if __name__ == '__main__':
    main()


Solve RuntimeWarning that arose without knowing why.

--- setup.py
+++ setup.py
@@ -24,9 +24,12 @@
         'zope.interface',
         'nose',
         'Genshi',
+        'pylons', # XXX why does nose throw a RuntimeWarning without this?
       ],
       setup_requires=['setuptools-git',],
       entry_points="""
       # -*- Entry points: -*-
+      [nose.plugins]
+      pylons = pylons.test:PylonsPlugin
       """,
       )

<|original_code|>
from setuptools import setup, find_packages
import sys, os

setup(name='cc.license',
      version='0.01',
      description="License selection based on ccREL-based metadata.",
      classifiers=[],
      keywords='',
      author='Creative Commons',
      author_email='software@creativecommons.org',
      url='http://wiki.creativecommons.org/CcLicense',
      license='MIT',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      #package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
      data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
                                      'license.rdf/rdf/selectors.rdf',
                                      'license.rdf/rdf/jurisdictions.rdf']),
                  ('cc/license/xml', ['license.rdf/xml/questions.xml'])],
      zip_safe=False,
      test_suite='nose.collector',
      install_requires=[
        'setuptools',
        'zope.interface',
        'nose',
        'Genshi',
      ],
      setup_requires=['setuptools-git',],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -24,6 +24,7 @@
         'zope.interface',
         'nose',
         'Genshi',
+        'pylons', # XXX why does nose throw a RuntimeWarning without this?
       ],
       setup_requires=['setuptools-git',],
       entry_points="""
<|current_version|>
from setuptools import setup, find_packages
import sys, os

setup(name='cc.license',
      version='0.01',
      description="License selection based on ccREL-based metadata.",
      classifiers=[],
      keywords='',
      author='Creative Commons',
      author_email='software@creativecommons.org',
      url='http://wiki.creativecommons.org/CcLicense',
      license='MIT',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      #package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
      data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
                                      'license.rdf/rdf/selectors.rdf',
                                      'license.rdf/rdf/jurisdictions.rdf']),
                  ('cc/license/xml', ['license.rdf/xml/questions.xml'])],
      zip_safe=False,
      test_suite='nose.collector',
      install_requires=[
        'setuptools',
        'zope.interface',
        'nose',
        'Genshi',
        'pylons', # XXX why does nose throw a RuntimeWarning without this?
      ],
      setup_requires=['setuptools-git',],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )

<|next_version|>
from setuptools import setup, find_packages
import sys, os

setup(name='cc.license',
      version='0.01',
      description="License selection based on ccREL-based metadata.",
      classifiers=[],
      keywords='',
      author='Creative Commons',
      author_email='software@creativecommons.org',
      url='http://wiki.creativecommons.org/CcLicense',
      license='MIT',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      #package_data={'cc.license': ['*.xml', '*.txt']}, # doesn't work
      data_files=[('cc/license/rdf', ['license.rdf/rdf/index.rdf',
                                      'license.rdf/rdf/selectors.rdf',
                                      'license.rdf/rdf/jurisdictions.rdf']),
                  ('cc/license/xml', ['license.rdf/xml/questions.xml'])],
      zip_safe=False,
      test_suite='nose.collector',
      install_requires=[
        'setuptools',
        'zope.interface',
        'nose',
        'Genshi',
        'pylons', # XXX why does nose throw a RuntimeWarning without this?
      ],
      setup_requires=['setuptools-git',],
      entry_points="""
      # -*- Entry points: -*-
      [nose.plugins]
      pylons = pylons.test:PylonsPlugin
      """,
      )


Allow access to root leaves.

Allow access to root leaves.

--- server/conf/vhosts/available/token.py
+++ server/conf/vhosts/available/token.py
@@ -26,6 +26,11 @@
         xsltResource.isLeaf = True
         self.root.children['~static'].putChild('propfind.xslt', xsltResource)

+        leaves = {}
+        for path, child in self.root.children.items():
+            if child.isLeaf == True:
+                leaves[path] = child
+
         tree = resource.TokenAccessResourceDecorator(self.root)

         self.root = resource.TokenResource(
@@ -33,3 +38,6 @@
                                              userProvider=self.user
                                              ),
                                 tree=tree)
+
+        for path, child in leaves.items():
+            self.root.putChild(path, child)

<|original_code|>
import core.provider.authentication as authentication
import core.notify.dispatcher as notify
import core.notify.plugins.available.changes as changes
import core.provider.storage as storage
import core.resource.base as resource
import conf.vhosts.available.default as default

class VHost(default.VHost):
    host = ['localhost']
    port = '8888'

    def build(self):
        """
        Build the resource tree
        """
        default.VHost.build(self)

        # [Change the notifiers] #
        self.root.notifier = notify.Manual([changes.Plugin()])

        # plain propfind xslt replaces the other one
        xsltResource = resource.StaticResource(
                            storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'),
                            expirationDays = 2
                          )
        xsltResource.isLeaf = True
        self.root.children['~static'].putChild('propfind.xslt', xsltResource)

        tree = resource.TokenAccessResourceDecorator(self.root)

        self.root = resource.TokenResource(
                                authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'],
                                             userProvider=self.user
                                             ),
                                tree=tree)
<|edits_diff|>
--- server/conf/vhosts/available/token.py
+++ server/conf/vhosts/available/token.py
@@ -33,3 +33,6 @@
                                              userProvider=self.user
                                              ),
                                 tree=tree)
+
+        for path, child in leaves.items():
+            self.root.putChild(path, child)
<|current_version|>
import core.provider.authentication as authentication
import core.notify.dispatcher as notify
import core.notify.plugins.available.changes as changes
import core.provider.storage as storage
import core.resource.base as resource
import conf.vhosts.available.default as default

class VHost(default.VHost):
    host = ['localhost']
    port = '8888'

    def build(self):
        """
        Build the resource tree
        """
        default.VHost.build(self)

        # [Change the notifiers] #
        self.root.notifier = notify.Manual([changes.Plugin()])

        # plain propfind xslt replaces the other one
        xsltResource = resource.StaticResource(
                            storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'),
                            expirationDays = 2
                          )
        xsltResource.isLeaf = True
        self.root.children['~static'].putChild('propfind.xslt', xsltResource)

        tree = resource.TokenAccessResourceDecorator(self.root)

        self.root = resource.TokenResource(
                                authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'],
                                             userProvider=self.user
                                             ),
                                tree=tree)

        for path, child in leaves.items():
            self.root.putChild(path, child)
<|next_version|>
import core.provider.authentication as authentication
import core.notify.dispatcher as notify
import core.notify.plugins.available.changes as changes
import core.provider.storage as storage
import core.resource.base as resource
import conf.vhosts.available.default as default

class VHost(default.VHost):
    host = ['localhost']
    port = '8888'

    def build(self):
        """
        Build the resource tree
        """
        default.VHost.build(self)

        # [Change the notifiers] #
        self.root.notifier = notify.Manual([changes.Plugin()])

        # plain propfind xslt replaces the other one
        xsltResource = resource.StaticResource(
                            storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'),
                            expirationDays = 2
                          )
        xsltResource.isLeaf = True
        self.root.children['~static'].putChild('propfind.xslt', xsltResource)

        leaves = {}
        for path, child in self.root.children.items():
            if child.isLeaf == True:
                leaves[path] = child

        tree = resource.TokenAccessResourceDecorator(self.root)

        self.root = resource.TokenResource(
                                authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'],
                                             userProvider=self.user
                                             ),
                                tree=tree)

        for path, child in leaves.items():
            self.root.putChild(path, child)


Make the exceptions valid on fsspec module level

--- fsspec/__init__.py
+++ fsspec/__init__.py
@@ -10,6 +10,7 @@
 from . import caching
 from ._version import get_versions
 from .core import get_fs_token_paths, open, open_files, open_local
+from .exceptions import FSBaseException, FSTimeoutError
 from .mapping import FSMap, get_mapper
 from .registry import (
     filesystem,
@@ -25,6 +26,8 @@

 __all__ = [
     "AbstractFileSystem",
+    "FSBaseException",
+    "FSTimeoutError",
     "FSMap",
     "filesystem",
     "register_implementation",

<|original_code|>
try:
    from importlib.metadata import entry_points
except ImportError:  # python < 3.8
    try:
        from importlib_metadata import entry_points
    except ImportError:
        entry_points = None

from . import caching
from ._version import get_versions
from .core import get_fs_token_paths, open, open_files, open_local
from .mapping import FSMap, get_mapper
from .registry import (
    filesystem,
    get_filesystem_class,
    register_implementation,
    registry,
)
from .spec import AbstractFileSystem

__version__ = get_versions()["version"]
del get_versions

__all__ = [
    "AbstractFileSystem",
    "FSMap",
    "filesystem",
    "register_implementation",
    "get_filesystem_class",
    "get_fs_token_paths",
    "get_mapper",
    "open",
    "open_files",
    "open_local",
    "registry",
    "caching",
]

if entry_points is not None:
    try:
        entry_points = entry_points()
    except TypeError:
        pass  # importlib-metadata < 0.8
    else:
        for spec in entry_points.get("fsspec.specs", []):
            err_msg = f"Unable to load filesystem from {spec}"
            register_implementation(
                spec.name, spec.value.replace(":", "."), errtxt=err_msg
            )

<|edits_diff|>
--- fsspec/__init__.py
+++ fsspec/__init__.py
@@ -10,6 +10,7 @@
 from . import caching
 from ._version import get_versions
 from .core import get_fs_token_paths, open, open_files, open_local
+from .exceptions import FSBaseException, FSTimeoutError
 from .mapping import FSMap, get_mapper
 from .registry import (
     filesystem,
<|current_version|>
try:
    from importlib.metadata import entry_points
except ImportError:  # python < 3.8
    try:
        from importlib_metadata import entry_points
    except ImportError:
        entry_points = None

from . import caching
from ._version import get_versions
from .core import get_fs_token_paths, open, open_files, open_local
from .exceptions import FSBaseException, FSTimeoutError
from .mapping import FSMap, get_mapper
from .registry import (
    filesystem,
    get_filesystem_class,
    register_implementation,
    registry,
)
from .spec import AbstractFileSystem

__version__ = get_versions()["version"]
del get_versions

__all__ = [
    "AbstractFileSystem",
    "FSMap",
    "filesystem",
    "register_implementation",
    "get_filesystem_class",
    "get_fs_token_paths",
    "get_mapper",
    "open",
    "open_files",
    "open_local",
    "registry",
    "caching",
]

if entry_points is not None:
    try:
        entry_points = entry_points()
    except TypeError:
        pass  # importlib-metadata < 0.8
    else:
        for spec in entry_points.get("fsspec.specs", []):
            err_msg = f"Unable to load filesystem from {spec}"
            register_implementation(
                spec.name, spec.value.replace(":", "."), errtxt=err_msg
            )

<|next_version|>
try:
    from importlib.metadata import entry_points
except ImportError:  # python < 3.8
    try:
        from importlib_metadata import entry_points
    except ImportError:
        entry_points = None

from . import caching
from ._version import get_versions
from .core import get_fs_token_paths, open, open_files, open_local
from .exceptions import FSBaseException, FSTimeoutError
from .mapping import FSMap, get_mapper
from .registry import (
    filesystem,
    get_filesystem_class,
    register_implementation,
    registry,
)
from .spec import AbstractFileSystem

__version__ = get_versions()["version"]
del get_versions

__all__ = [
    "AbstractFileSystem",
    "FSBaseException",
    "FSTimeoutError",
    "FSMap",
    "filesystem",
    "register_implementation",
    "get_filesystem_class",
    "get_fs_token_paths",
    "get_mapper",
    "open",
    "open_files",
    "open_local",
    "registry",
    "caching",
]

if entry_points is not None:
    try:
        entry_points = entry_points()
    except TypeError:
        pass  # importlib-metadata < 0.8
    else:
        for spec in entry_points.get("fsspec.specs", []):
            err_msg = f"Unable to load filesystem from {spec}"
            register_implementation(
                spec.name, spec.value.replace(":", "."), errtxt=err_msg
            )


Update tests to reproduce bug

Update tests to reproduce bug

--- tests/fakes.py
+++ tests/fakes.py
@@ -1,7 +1,12 @@
+import six
+
+
 class FakeHttpRequest(object):
     def __init__(self, method='GET', body=''):
         self.method = method.upper()
         self.body = body
+        if six.PY3:
+            self.body = body.encode('utf-8')

 class FakeHttpResponse(object):

<|original_code|>
class FakeHttpRequest(object):
    def __init__(self, method='GET', body=''):
        self.method = method.upper()
        self.body = body

class FakeHttpResponse(object):
    def __init__(self, body, content_type='text/html'):
        self.body = body
        self.content_type = content_type
        self.status_code = 200

class FakeModel(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

<|edits_diff|>
--- tests/fakes.py
+++ tests/fakes.py
@@ -1,3 +1,6 @@
+import six
+
+
 class FakeHttpRequest(object):
     def __init__(self, method='GET', body=''):
         self.method = method.upper()
<|current_version|>
import six

class FakeHttpRequest(object):
    def __init__(self, method='GET', body=''):
        self.method = method.upper()
        self.body = body

class FakeHttpResponse(object):
    def __init__(self, body, content_type='text/html'):
        self.body = body
        self.content_type = content_type
        self.status_code = 200

class FakeModel(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

<|next_version|>
import six

class FakeHttpRequest(object):
    def __init__(self, method='GET', body=''):
        self.method = method.upper()
        self.body = body
        if six.PY3:
            self.body = body.encode('utf-8')

class FakeHttpResponse(object):
    def __init__(self, body, content_type='text/html'):
        self.body = body
        self.content_type = content_type
        self.status_code = 200

class FakeModel(object):
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)


Load .so if not on Crap OS X

Load .so if not on Crap OS X

--- learn/my_pbkdf2.py
+++ learn/my_pbkdf2.py
@@ -1,6 +1,9 @@
 import ctypes
+import platform

 __all__ = ["pbkdf2"]
+
+name = "libssl.%s" % ("dylib" if platform.system() == "Darwin" else "so")

 libssl = ctypes.CDLL("libssl.dylib")
 libssl.PKCS5_PBKDF2_HMAC_SHA1.restype = ctypes.c_int

<|original_code|>
import ctypes

__all__ = ["pbkdf2"]

libssl = ctypes.CDLL("libssl.dylib")
libssl.PKCS5_PBKDF2_HMAC_SHA1.restype = ctypes.c_int

def cBuf(data):
	return ctypes.create_string_buffer(data, len(data))

def pbkdf2(password, salt, iterations, outlen):
	targetbuf = cBuf("\0" * outlen)
	ret = libssl.PKCS5_PBKDF2_HMAC_SHA1(
			cBuf(password), len(password),
			cBuf(salt), len(salt),
			iterations, outlen,
			ctypes.byref(targetbuf))
	return targetbuf.raw if ret else None

<|edits_diff|>
--- learn/my_pbkdf2.py
+++ learn/my_pbkdf2.py
@@ -1,4 +1,5 @@
 import ctypes
+import platform

 __all__ = ["pbkdf2"]

<|current_version|>
import ctypes
import platform

__all__ = ["pbkdf2"]

libssl = ctypes.CDLL("libssl.dylib")
libssl.PKCS5_PBKDF2_HMAC_SHA1.restype = ctypes.c_int

def cBuf(data):
	return ctypes.create_string_buffer(data, len(data))

def pbkdf2(password, salt, iterations, outlen):
	targetbuf = cBuf("\0" * outlen)
	ret = libssl.PKCS5_PBKDF2_HMAC_SHA1(
			cBuf(password), len(password),
			cBuf(salt), len(salt),
			iterations, outlen,
			ctypes.byref(targetbuf))
	return targetbuf.raw if ret else None

<|next_version|>
import ctypes
import platform

__all__ = ["pbkdf2"]

name = "libssl.%s" % ("dylib" if platform.system() == "Darwin" else "so")

libssl = ctypes.CDLL("libssl.dylib")
libssl.PKCS5_PBKDF2_HMAC_SHA1.restype = ctypes.c_int

def cBuf(data):
	return ctypes.create_string_buffer(data, len(data))

def pbkdf2(password, salt, iterations, outlen):
	targetbuf = cBuf("\0" * outlen)
	ret = libssl.PKCS5_PBKDF2_HMAC_SHA1(
			cBuf(password), len(password),
			cBuf(salt), len(salt),
			iterations, outlen,
			ctypes.byref(targetbuf))
	return targetbuf.raw if ret else None


Disable Django-CMS test on Django 1.10+

Disable Django-CMS test on Django 1.10+

Someone with the time and inclination should set up the test to work with a Django-CMS version compatible with Django 1.10+, then try again

--- form_designer/tests/test_cms_plugin.py
+++ form_designer/tests/test_cms_plugin.py
@@ -1,3 +1,4 @@
+import django
 from django.contrib.auth.models import AnonymousUser
 from django.utils.crypto import get_random_string

@@ -10,6 +11,8 @@

 @pytest.mark.django_db
 def test_cms_plugin_renders_in_cms_page(rf):
+    if django.VERSION >= (1, 10):
+        pytest.xfail('This test is broken in Django 1.10+')
     fd = FormDefinition.objects.create(
         mail_to='test@example.com',
         mail_subject='Someone sent you a greeting: {{ test }}'

<|original_code|>
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string

import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefinition, FormDefinitionField

@pytest.mark.django_db
def test_cms_plugin_renders_in_cms_page(rf):
    fd = FormDefinition.objects.create(
        mail_to='test@example.com',
        mail_subject='Someone sent you a greeting: {{ test }}'
    )
    field = FormDefinitionField.objects.create(
        form_definition=fd,
        name='test',
        label=get_random_string(),
        field_class='django.forms.CharField',
    )
    page = api.create_page("test", "page.html", "en")
    ph = page.get_placeholders()[0]
    api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd)
    request = rf.get("/")
    request.user = AnonymousUser()
    request.current_page = page
    response = render_page(request, page, "fi", "test")
    response.render()
    content = response.content.decode("utf8")
    assert field.label in content
    assert "<form" in content

<|edits_diff|>
--- form_designer/tests/test_cms_plugin.py
+++ form_designer/tests/test_cms_plugin.py
@@ -1,3 +1,4 @@
+import django
 from django.contrib.auth.models import AnonymousUser
 from django.utils.crypto import get_random_string

<|current_version|>
import django
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string

import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefinition, FormDefinitionField

@pytest.mark.django_db
def test_cms_plugin_renders_in_cms_page(rf):
    fd = FormDefinition.objects.create(
        mail_to='test@example.com',
        mail_subject='Someone sent you a greeting: {{ test }}'
    )
    field = FormDefinitionField.objects.create(
        form_definition=fd,
        name='test',
        label=get_random_string(),
        field_class='django.forms.CharField',
    )
    page = api.create_page("test", "page.html", "en")
    ph = page.get_placeholders()[0]
    api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd)
    request = rf.get("/")
    request.user = AnonymousUser()
    request.current_page = page
    response = render_page(request, page, "fi", "test")
    response.render()
    content = response.content.decode("utf8")
    assert field.label in content
    assert "<form" in content

<|next_version|>
import django
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string

import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefinition, FormDefinitionField

@pytest.mark.django_db
def test_cms_plugin_renders_in_cms_page(rf):
    if django.VERSION >= (1, 10):
        pytest.xfail('This test is broken in Django 1.10+')
    fd = FormDefinition.objects.create(
        mail_to='test@example.com',
        mail_subject='Someone sent you a greeting: {{ test }}'
    )
    field = FormDefinitionField.objects.create(
        form_definition=fd,
        name='test',
        label=get_random_string(),
        field_class='django.forms.CharField',
    )
    page = api.create_page("test", "page.html", "en")
    ph = page.get_placeholders()[0]
    api.add_plugin(ph, FormDesignerPlugin, "en", form_definition=fd)
    request = rf.get("/")
    request.user = AnonymousUser()
    request.current_page = page
    response = render_page(request, page, "fi", "test")
    response.render()
    content = response.content.decode("utf8")
    assert field.label in content
    assert "<form" in content


Add docstrings to 'sudo' and 'make'.

Add docstrings to 'sudo' and 'make'.

--- basic.py
+++ basic.py
@@ -16,10 +16,12 @@

 @cmd
 def sudo(event):
+    """Responds 'okay.' to your 'sudo ...' (http://xkcd.com/149/)."""
     return 'okay.'

 @cmd
 def make(event):
+    """Tells user to go make it himself (http://xkcd.com/149/')."""
     return 'what? make it yourself.'

<|original_code|>

from brutal.core.plugin import BotPlugin, cmd, event, match, threaded

@cmd
def ping(event):
    """Responds 'pong' to your 'ping'."""

    return 'pong'

@cmd
def echo(event):
    """Echoes back the message it recieves."""
    return ' '.join(event.args)

@cmd
def sudo(event):
    return 'okay.'

@cmd
def make(event):
    return 'what? make it yourself.'

welcomes = {
    "LordPotato_": "Everybody on your knees and let's praise the mighty Potato!",
    "pepol": "Nazimod sighted, take cover!",
    "mrshu": "Hide yo codes, hide yo wife, nazireviewer is on site!",
    "jn_": "Swiggidy swooty, he's comin' for dat booty!",
    "kalerab" : "Hide your apples, 'cause he's gonna eat 'em!"
}

@event
def auto_welcome(event):
    if event.event_type == 'join':
    	if event.meta['nick'] in welcomes:
            return welcomes[event.meta['nick']]
        else:
            return event.meta['nick'] + ': hi!'

<|edits_diff|>
--- basic.py
+++ basic.py
@@ -16,6 +16,7 @@

 @cmd
 def sudo(event):
+    """Responds 'okay.' to your 'sudo ...' (http://xkcd.com/149/)."""
     return 'okay.'

 @cmd
<|current_version|>

from brutal.core.plugin import BotPlugin, cmd, event, match, threaded

@cmd
def ping(event):
    """Responds 'pong' to your 'ping'."""

    return 'pong'

@cmd
def echo(event):
    """Echoes back the message it recieves."""
    return ' '.join(event.args)

@cmd
def sudo(event):
    """Responds 'okay.' to your 'sudo ...' (http://xkcd.com/149/)."""
    return 'okay.'

@cmd
def make(event):
    return 'what? make it yourself.'

welcomes = {
    "LordPotato_": "Everybody on your knees and let's praise the mighty Potato!",
    "pepol": "Nazimod sighted, take cover!",
    "mrshu": "Hide yo codes, hide yo wife, nazireviewer is on site!",
    "jn_": "Swiggidy swooty, he's comin' for dat booty!",
    "kalerab" : "Hide your apples, 'cause he's gonna eat 'em!"
}

@event
def auto_welcome(event):
    if event.event_type == 'join':
    	if event.meta['nick'] in welcomes:
            return welcomes[event.meta['nick']]
        else:
            return event.meta['nick'] + ': hi!'

<|next_version|>

from brutal.core.plugin import BotPlugin, cmd, event, match, threaded

@cmd
def ping(event):
    """Responds 'pong' to your 'ping'."""

    return 'pong'

@cmd
def echo(event):
    """Echoes back the message it recieves."""
    return ' '.join(event.args)

@cmd
def sudo(event):
    """Responds 'okay.' to your 'sudo ...' (http://xkcd.com/149/)."""
    return 'okay.'

@cmd
def make(event):
    """Tells user to go make it himself (http://xkcd.com/149/')."""
    return 'what? make it yourself.'

welcomes = {
    "LordPotato_": "Everybody on your knees and let's praise the mighty Potato!",
    "pepol": "Nazimod sighted, take cover!",
    "mrshu": "Hide yo codes, hide yo wife, nazireviewer is on site!",
    "jn_": "Swiggidy swooty, he's comin' for dat booty!",
    "kalerab" : "Hide your apples, 'cause he's gonna eat 'em!"
}

@event
def auto_welcome(event):
    if event.event_type == 'join':
    	if event.meta['nick'] in welcomes:
            return welcomes[event.meta['nick']]
        else:
            return event.meta['nick'] + ': hi!'


game/quests: Implement getObjective and tooltip objective

--- game/quests/__init__.py
+++ game/quests/__init__.py
@@ -15,6 +15,10 @@
 	def tooltip(self):

 		self.append("name", self.obj.getName(), color=YELLOW)
+		self.appendEmptyLine()
+
+		self.append("objective", self.obj.getObjective())
+		self.appendEmptyLine()

 		ret = self.values
 		self.values = []
@@ -40,6 +44,9 @@
 	def getName(self, row):
 		return row.name

+	def getObjective(self, row):
+		return row.objective
+
 	def getSummary(self, row):
 		return row.summary

<|original_code|>
# -*- coding: utf-8 -*-
"""
Quests
 - questcache.wdb
"""

from .. import *

class Quest(Model):
	def getTooltip(self):
		return QuestTooltip(self)

class QuestTooltip(Tooltip):
	def tooltip(self):

		self.append("name", self.obj.getName(), color=YELLOW)

		ret = self.values
		self.values = []
		return ret

class QuestProxy(object):
	"""
	WDBC proxy for quests
	"""
	def __init__(self, cls):
		from pywow import wdbc
		self.__file = wdbc.get("questcache.wdb", build=-1)

	def get(self, id):
		return self.__file[id]

	def getCompleteSummary(self, row):
		return row.complete_summary

	def getDescription(self, row):
		return row.description.replace("$B", "\n")

	def getName(self, row):
		return row.name

	def getSummary(self, row):
		return row.summary

Quest.initProxy(QuestProxy)

<|edits_diff|>
--- game/quests/__init__.py
+++ game/quests/__init__.py
@@ -15,6 +15,10 @@
 	def tooltip(self):

 		self.append("name", self.obj.getName(), color=YELLOW)
+		self.appendEmptyLine()
+
+		self.append("objective", self.obj.getObjective())
+		self.appendEmptyLine()

 		ret = self.values
 		self.values = []
<|current_version|>
# -*- coding: utf-8 -*-
"""
Quests
 - questcache.wdb
"""

from .. import *

class Quest(Model):
	def getTooltip(self):
		return QuestTooltip(self)

class QuestTooltip(Tooltip):
	def tooltip(self):

		self.append("name", self.obj.getName(), color=YELLOW)
		self.appendEmptyLine()

		self.append("objective", self.obj.getObjective())
		self.appendEmptyLine()

		ret = self.values
		self.values = []
		return ret

class QuestProxy(object):
	"""
	WDBC proxy for quests
	"""
	def __init__(self, cls):
		from pywow import wdbc
		self.__file = wdbc.get("questcache.wdb", build=-1)

	def get(self, id):
		return self.__file[id]

	def getCompleteSummary(self, row):
		return row.complete_summary

	def getDescription(self, row):
		return row.description.replace("$B", "\n")

	def getName(self, row):
		return row.name

	def getSummary(self, row):
		return row.summary

Quest.initProxy(QuestProxy)

<|next_version|>
# -*- coding: utf-8 -*-
"""
Quests
 - questcache.wdb
"""

from .. import *

class Quest(Model):
	def getTooltip(self):
		return QuestTooltip(self)

class QuestTooltip(Tooltip):
	def tooltip(self):

		self.append("name", self.obj.getName(), color=YELLOW)
		self.appendEmptyLine()

		self.append("objective", self.obj.getObjective())
		self.appendEmptyLine()

		ret = self.values
		self.values = []
		return ret

class QuestProxy(object):
	"""
	WDBC proxy for quests
	"""
	def __init__(self, cls):
		from pywow import wdbc
		self.__file = wdbc.get("questcache.wdb", build=-1)

	def get(self, id):
		return self.__file[id]

	def getCompleteSummary(self, row):
		return row.complete_summary

	def getDescription(self, row):
		return row.description.replace("$B", "\n")

	def getName(self, row):
		return row.name

	def getObjective(self, row):
		return row.objective

	def getSummary(self, row):
		return row.summary

Quest.initProxy(QuestProxy)


Add location and content-type headers to response.

--- api.py
+++ api.py
@@ -1,5 +1,6 @@
 import json
 from tornado.httpserver import HTTPServer
+from tornado.httputil import HTTPHeaders
 from  tornado.web import URLSpec
 import tornado.ioloop
 import tornado.web
@@ -28,6 +29,9 @@
         if self.request.uri == "/sell":
             order = Sell(**body)
         fills = Book().match(order)
+        self.set_header("content-type", "application/json")
+        self.set_header("location", "{}://{}{}".format(self.request.protocol,
+            self.request.host, self.reverse_url("book")))
         self.write(json.dumps(fills))

<|original_code|>
import json
from tornado.httpserver import HTTPServer
from  tornado.web import URLSpec
import tornado.ioloop
import tornado.web
from tornado.options import define, options

from orders import Book, Buy, Sell

define("port", default=3000, help="run on the given port", type=int)
Book()

class BookHandler(tornado.web.RequestHandler):

    def get(self):
        ret = json.dumps(Book().orders())
        self.write(ret)

class OrderHandler(tornado.web.RequestHandler):

    def post(self, **kwargs):
        order = None
        body = json.loads(self.request.body)
        if self.request.uri == "/buy":
            order = Buy(**body)
        if self.request.uri == "/sell":
            order = Sell(**body)
        fills = Book().match(order)
        self.write(json.dumps(fills))

def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        URLSpec(r"/book", BookHandler, name="book"),
        URLSpec(r"/buy", OrderHandler, name="buy"),
        URLSpec(r"/sell", OrderHandler, name="sell"),
    ])
    http_server = HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()

<|edits_diff|>
--- api.py
+++ api.py
@@ -1,5 +1,6 @@
 import json
 from tornado.httpserver import HTTPServer
+from tornado.httputil import HTTPHeaders
 from  tornado.web import URLSpec
 import tornado.ioloop
 import tornado.web
<|current_version|>
import json
from tornado.httpserver import HTTPServer
from tornado.httputil import HTTPHeaders
from  tornado.web import URLSpec
import tornado.ioloop
import tornado.web
from tornado.options import define, options

from orders import Book, Buy, Sell

define("port", default=3000, help="run on the given port", type=int)
Book()

class BookHandler(tornado.web.RequestHandler):

    def get(self):
        ret = json.dumps(Book().orders())
        self.write(ret)

class OrderHandler(tornado.web.RequestHandler):

    def post(self, **kwargs):
        order = None
        body = json.loads(self.request.body)
        if self.request.uri == "/buy":
            order = Buy(**body)
        if self.request.uri == "/sell":
            order = Sell(**body)
        fills = Book().match(order)
        self.write(json.dumps(fills))

def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        URLSpec(r"/book", BookHandler, name="book"),
        URLSpec(r"/buy", OrderHandler, name="buy"),
        URLSpec(r"/sell", OrderHandler, name="sell"),
    ])
    http_server = HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()

<|next_version|>
import json
from tornado.httpserver import HTTPServer
from tornado.httputil import HTTPHeaders
from  tornado.web import URLSpec
import tornado.ioloop
import tornado.web
from tornado.options import define, options

from orders import Book, Buy, Sell

define("port", default=3000, help="run on the given port", type=int)
Book()

class BookHandler(tornado.web.RequestHandler):

    def get(self):
        ret = json.dumps(Book().orders())
        self.write(ret)

class OrderHandler(tornado.web.RequestHandler):

    def post(self, **kwargs):
        order = None
        body = json.loads(self.request.body)
        if self.request.uri == "/buy":
            order = Buy(**body)
        if self.request.uri == "/sell":
            order = Sell(**body)
        fills = Book().match(order)
        self.set_header("content-type", "application/json")
        self.set_header("location", "{}://{}{}".format(self.request.protocol,
            self.request.host, self.reverse_url("book")))
        self.write(json.dumps(fills))

def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
        URLSpec(r"/book", BookHandler, name="book"),
        URLSpec(r"/buy", OrderHandler, name="buy"),
        URLSpec(r"/sell", OrderHandler, name="sell"),
    ])
    http_server = HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()


Add PyPI long project description

Add PyPI long project description

--- setup.py
+++ setup.py
@@ -9,12 +9,16 @@
 settings = SafeConfigParser()
 settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))

+with open('README.md', 'r') as fh:
+    long_description = fh.read()

 setup(
     name='aws-ec2-assign-elastic-ip',
     version=settings.get('general', 'version'),
     license='Apache License, Version 2.0',
     description='Automatically assign Elastic IPs to AWS EC2 instances',
+    long_description=long_description,
+    long_description_content_type='text/markdown',
     author='Sebastian Dahlgren, Skymill Solutions',
     author_email='sebastian.dahlgren@skymill.se',
     url='https://github.com/skymill/aws-ec2-assign-elastic-ip',

<|original_code|>
""" Setup script for PyPI """
import os
from setuptools import setup
try:
    from ConfigParser import SafeConfigParser
except ImportError:
    from configparser import SafeConfigParser

settings = SafeConfigParser()
settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))

setup(
    name='aws-ec2-assign-elastic-ip',
    version=settings.get('general', 'version'),
    license='Apache License, Version 2.0',
    description='Automatically assign Elastic IPs to AWS EC2 instances',
    author='Sebastian Dahlgren, Skymill Solutions',
    author_email='sebastian.dahlgren@skymill.se',
    url='https://github.com/skymill/aws-ec2-assign-elastic-ip',
    keywords="aws amazon web services ec2 as elasticip eip",
    platforms=['Any'],
    packages=['aws_ec2_assign_elastic_ip'],
    scripts=['aws-ec2-assign-elastic-ip'],
    include_package_data=True,
    zip_safe=False,
    install_requires=['boto >= 2.36.0', 'netaddr >= 0.7.12'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -9,6 +9,8 @@
 settings = SafeConfigParser()
 settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))

+with open('README.md', 'r') as fh:
+    long_description = fh.read()

 setup(
     name='aws-ec2-assign-elastic-ip',
<|current_version|>
""" Setup script for PyPI """
import os
from setuptools import setup
try:
    from ConfigParser import SafeConfigParser
except ImportError:
    from configparser import SafeConfigParser

settings = SafeConfigParser()
settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))

with open('README.md', 'r') as fh:
    long_description = fh.read()

setup(
    name='aws-ec2-assign-elastic-ip',
    version=settings.get('general', 'version'),
    license='Apache License, Version 2.0',
    description='Automatically assign Elastic IPs to AWS EC2 instances',
    author='Sebastian Dahlgren, Skymill Solutions',
    author_email='sebastian.dahlgren@skymill.se',
    url='https://github.com/skymill/aws-ec2-assign-elastic-ip',
    keywords="aws amazon web services ec2 as elasticip eip",
    platforms=['Any'],
    packages=['aws_ec2_assign_elastic_ip'],
    scripts=['aws-ec2-assign-elastic-ip'],
    include_package_data=True,
    zip_safe=False,
    install_requires=['boto >= 2.36.0', 'netaddr >= 0.7.12'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)

<|next_version|>
""" Setup script for PyPI """
import os
from setuptools import setup
try:
    from ConfigParser import SafeConfigParser
except ImportError:
    from configparser import SafeConfigParser

settings = SafeConfigParser()
settings.read(os.path.realpath('aws_ec2_assign_elastic_ip/settings.conf'))

with open('README.md', 'r') as fh:
    long_description = fh.read()

setup(
    name='aws-ec2-assign-elastic-ip',
    version=settings.get('general', 'version'),
    license='Apache License, Version 2.0',
    description='Automatically assign Elastic IPs to AWS EC2 instances',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Sebastian Dahlgren, Skymill Solutions',
    author_email='sebastian.dahlgren@skymill.se',
    url='https://github.com/skymill/aws-ec2-assign-elastic-ip',
    keywords="aws amazon web services ec2 as elasticip eip",
    platforms=['Any'],
    packages=['aws_ec2_assign_elastic_ip'],
    scripts=['aws-ec2-assign-elastic-ip'],
    include_package_data=True,
    zip_safe=False,
    install_requires=['boto >= 2.36.0', 'netaddr >= 0.7.12'],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Apache Software License',
        'Operating System :: OS Independent',
        'Programming Language :: Python'
    ]
)


Load config when loading dallinger.experiments

--- dallinger/experiments/__init__.py
+++ dallinger/experiments/__init__.py
@@ -3,7 +3,12 @@
 """
 import logging
 from pkg_resources import iter_entry_points
+
+from ..config import get_config
 from ..experiment import Experiment
+
+config = get_config()
+config.load()

 logger = logging.getLogger(__name__)
 logger.addHandler(logging.NullHandler())

<|original_code|>
"""A home for all Dallinger Experiments. Experiments should be registered
with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group.
"""
import logging
from pkg_resources import iter_entry_points
from ..experiment import Experiment

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment

for entry_point in iter_entry_points(group='dallinger.experiments'):
    try:
        globals()[entry_point.name] = entry_point.load()
    except ImportError:
        logger.exception('Could not import registered entry point {}'.format(
            entry_point.name
        ))

<|edits_diff|>
--- dallinger/experiments/__init__.py
+++ dallinger/experiments/__init__.py
@@ -3,6 +3,8 @@
 """
 import logging
 from pkg_resources import iter_entry_points
+
+from ..config import get_config
 from ..experiment import Experiment

 logger = logging.getLogger(__name__)
<|current_version|>
"""A home for all Dallinger Experiments. Experiments should be registered
with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group.
"""
import logging
from pkg_resources import iter_entry_points

from ..config import get_config
from ..experiment import Experiment

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment

for entry_point in iter_entry_points(group='dallinger.experiments'):
    try:
        globals()[entry_point.name] = entry_point.load()
    except ImportError:
        logger.exception('Could not import registered entry point {}'.format(
            entry_point.name
        ))

<|next_version|>
"""A home for all Dallinger Experiments. Experiments should be registered
with a ``setuptools`` ``entry_point`` for the ``dallinger.experiments`` group.
"""
import logging
from pkg_resources import iter_entry_points

from ..config import get_config
from ..experiment import Experiment

config = get_config()
config.load()

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

# Avoid PEP-8 warning, we want this to be importable from this location
Experiment = Experiment

for entry_point in iter_entry_points(group='dallinger.experiments'):
    try:
        globals()[entry_point.name] = entry_point.load()
    except ImportError:
        logger.exception('Could not import registered entry point {}'.format(
            entry_point.name
        ))


Set SO_REUSEADDR in client test.

Set SO_REUSEADDR in client test.

--- test/lib/01-con-discon-success.py
+++ test/lib/01-con-discon-success.py
@@ -16,6 +16,7 @@

 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 sock.bind(('', 1888))
 sock.listen(5)

@@ -34,9 +35,12 @@
         print("Expected: "+connect_packet+" length="+str(len(connect_packet)))
     else:
         rc = 0
+
+    conn.close()
 finally:
     client.terminate()
     client.wait()
+    sock.close()

 exit(rc)

<|original_code|>
#!/usr/bin/python

# Test whether a client produces a correct connect and subsequent disconnect.

import os
import subprocess
import socket
import sys
import time
from struct import *

rc = 1
keepalive = 60
connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success")
connack_packet = pack('!BBBB', 32, 2, 0, 0);

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 1888))
sock.listen(5)

client_args = sys.argv[1:]
env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp'
client = subprocess.Popen(client_args, env=env)

try:
    (conn, address) = sock.accept()
    connect_recvd = conn.recv(256)

    if connect_recvd != connect_packet:
        print("FAIL: Received incorrect connect.")
        print("Received: "+connect_recvd+" length="+str(len(connect_recvd)))
        print("Expected: "+connect_packet+" length="+str(len(connect_packet)))
    else:
        rc = 0
finally:
    client.terminate()
    client.wait()

exit(rc)

<|edits_diff|>
--- test/lib/01-con-discon-success.py
+++ test/lib/01-con-discon-success.py
@@ -16,6 +16,7 @@

 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
 sock.bind(('', 1888))
 sock.listen(5)

@@ -34,6 +35,8 @@
         print("Expected: "+connect_packet+" length="+str(len(connect_packet)))
     else:
         rc = 0
+
+    conn.close()
 finally:
     client.terminate()
     client.wait()
<|current_version|>
#!/usr/bin/python

# Test whether a client produces a correct connect and subsequent disconnect.

import os
import subprocess
import socket
import sys
import time
from struct import *

rc = 1
keepalive = 60
connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success")
connack_packet = pack('!BBBB', 32, 2, 0, 0);

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 1888))
sock.listen(5)

client_args = sys.argv[1:]
env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp'
client = subprocess.Popen(client_args, env=env)

try:
    (conn, address) = sock.accept()
    connect_recvd = conn.recv(256)

    if connect_recvd != connect_packet:
        print("FAIL: Received incorrect connect.")
        print("Received: "+connect_recvd+" length="+str(len(connect_recvd)))
        print("Expected: "+connect_packet+" length="+str(len(connect_packet)))
    else:
        rc = 0

    conn.close()
finally:
    client.terminate()
    client.wait()

exit(rc)

<|next_version|>
#!/usr/bin/python

# Test whether a client produces a correct connect and subsequent disconnect.

import os
import subprocess
import socket
import sys
import time
from struct import *

rc = 1
keepalive = 60
connect_packet = pack('!BBH6sBBHH21s', 16, 12+2+21,6,"MQIsdp",3,2,keepalive,21,"01-con-discon-success")
connack_packet = pack('!BBBB', 32, 2, 0, 0);

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 1888))
sock.listen(5)

client_args = sys.argv[1:]
env = dict(os.environ)
env['LD_LIBRARY_PATH'] = '../../lib:../../lib/cpp'
client = subprocess.Popen(client_args, env=env)

try:
    (conn, address) = sock.accept()
    connect_recvd = conn.recv(256)

    if connect_recvd != connect_packet:
        print("FAIL: Received incorrect connect.")
        print("Received: "+connect_recvd+" length="+str(len(connect_recvd)))
        print("Expected: "+connect_packet+" length="+str(len(connect_packet)))
    else:
        rc = 0

    conn.close()
finally:
    client.terminate()
    client.wait()
    sock.close()

exit(rc)