Add a has_expired() method to the Timer class.

--- modules/tools.py
+++ modules/tools.py
@@ -7,6 +7,7 @@
         self.callbacks = list(callbacks)

         self.elapsed = 0
+        self.expired = False
         self.paused = False

     def register(self, callback):
@@ -22,13 +23,19 @@
         self.pause = False

     def update(self, time):
+        if self.expired:
+            return
+
         if self.elapsed > self.duration:
             return

         self.elapsed += time

         if self.elapsed > self.duration:
+            self.expired = True
             for callback in self.callbacks:
                 callback()

+    def has_expired(self):
+        return self.expired

<|original_code|>
inf = infinity = float('inf')

class Timer:

    def __init__(self, duration, *callbacks):
        self.duration = duration
        self.callbacks = list(callbacks)

        self.elapsed = 0
        self.paused = False

    def register(self, callback):
        self.callbacks.append(callback)

    def unregister(self, callback):
        self.callbacks.remove(callback)

    def pause(self):
        self.paused = True

    def unpause(self):
        self.pause = False

    def update(self, time):
        if self.elapsed > self.duration:
            return

        self.elapsed += time

        if self.elapsed > self.duration:
            for callback in self.callbacks:
                callback()

<|edits_diff|>
--- modules/tools.py
+++ modules/tools.py
@@ -7,6 +7,7 @@
         self.callbacks = list(callbacks)

         self.elapsed = 0
+        self.expired = False
         self.paused = False

     def register(self, callback):
@@ -22,12 +23,16 @@
         self.pause = False

     def update(self, time):
+        if self.expired:
+            return
+
         if self.elapsed > self.duration:
             return

         self.elapsed += time

         if self.elapsed > self.duration:
+            self.expired = True
             for callback in self.callbacks:
                 callback()

<|current_version|>
inf = infinity = float('inf')

class Timer:

    def __init__(self, duration, *callbacks):
        self.duration = duration
        self.callbacks = list(callbacks)

        self.elapsed = 0
        self.expired = False
        self.paused = False

    def register(self, callback):
        self.callbacks.append(callback)

    def unregister(self, callback):
        self.callbacks.remove(callback)

    def pause(self):
        self.paused = True

    def unpause(self):
        self.pause = False

    def update(self, time):
        if self.expired:
            return

        if self.elapsed > self.duration:
            return

        self.elapsed += time

        if self.elapsed > self.duration:
            self.expired = True
            for callback in self.callbacks:
                callback()

<|next_version|>
inf = infinity = float('inf')

class Timer:

    def __init__(self, duration, *callbacks):
        self.duration = duration
        self.callbacks = list(callbacks)

        self.elapsed = 0
        self.expired = False
        self.paused = False

    def register(self, callback):
        self.callbacks.append(callback)

    def unregister(self, callback):
        self.callbacks.remove(callback)

    def pause(self):
        self.paused = True

    def unpause(self):
        self.pause = False

    def update(self, time):
        if self.expired:
            return

        if self.elapsed > self.duration:
            return

        self.elapsed += time

        if self.elapsed > self.duration:
            self.expired = True
            for callback in self.callbacks:
                callback()

    def has_expired(self):
        return self.expired


Fix newlines in copying of errors

Fix newlines in copying of errors

--- glue/utils/qt/qmessagebox_widget.py
+++ glue/utils/qt/qmessagebox_widget.py
@@ -1,5 +1,6 @@
 # A patched version of QMessageBox that allows copying the error

+import os
 from ...external.qt import QtGui

 __all__ = ['QMessageBoxPatched']
@@ -36,4 +37,6 @@
     def copy_detailed(self):
         clipboard = QtGui.QApplication.clipboard()
         selected_text = self.detailed_text_widget.textCursor().selectedText()
+        # Newlines are unicode, so need to normalize them to ASCII
+        selected_text = os.linesep.join(selected_text.splitlines())
         clipboard.setText(selected_text)

<|original_code|>
# A patched version of QMessageBox that allows copying the error

from ...external.qt import QtGui

__all__ = ['QMessageBoxPatched']

class QMessageBoxPatched(QtGui.QMessageBox):

    def __init__(self, *args, **kwargs):

        super(QMessageBoxPatched, self).__init__(*args, **kwargs)

        copy_action = QtGui.QAction('&Copy', self)
        copy_action.setShortcut(QtGui.QKeySequence.Copy)
        copy_action.triggered.connect(self.copy_detailed)

        select_all = QtGui.QAction('Select &All', self)
        select_all.setShortcut(QtGui.QKeySequence.SelectAll)
        select_all.triggered.connect(self.select_all)

        menubar = QtGui.QMenuBar()
        editMenu = menubar.addMenu('&Edit')
        editMenu.addAction(copy_action)
        editMenu.addAction(select_all)

        self.layout().setMenuBar(menubar)

    @property
    def detailed_text_widget(self):
        return self.findChild(QtGui.QTextEdit)

    def select_all(self):
        self.detailed_text_widget.selectAll()

    def copy_detailed(self):
        clipboard = QtGui.QApplication.clipboard()
        selected_text = self.detailed_text_widget.textCursor().selectedText()
        clipboard.setText(selected_text)

<|edits_diff|>
--- glue/utils/qt/qmessagebox_widget.py
+++ glue/utils/qt/qmessagebox_widget.py
@@ -1,5 +1,6 @@
 # A patched version of QMessageBox that allows copying the error

+import os
 from ...external.qt import QtGui

 __all__ = ['QMessageBoxPatched']
<|current_version|>
# A patched version of QMessageBox that allows copying the error

import os
from ...external.qt import QtGui

__all__ = ['QMessageBoxPatched']

class QMessageBoxPatched(QtGui.QMessageBox):

    def __init__(self, *args, **kwargs):

        super(QMessageBoxPatched, self).__init__(*args, **kwargs)

        copy_action = QtGui.QAction('&Copy', self)
        copy_action.setShortcut(QtGui.QKeySequence.Copy)
        copy_action.triggered.connect(self.copy_detailed)

        select_all = QtGui.QAction('Select &All', self)
        select_all.setShortcut(QtGui.QKeySequence.SelectAll)
        select_all.triggered.connect(self.select_all)

        menubar = QtGui.QMenuBar()
        editMenu = menubar.addMenu('&Edit')
        editMenu.addAction(copy_action)
        editMenu.addAction(select_all)

        self.layout().setMenuBar(menubar)

    @property
    def detailed_text_widget(self):
        return self.findChild(QtGui.QTextEdit)

    def select_all(self):
        self.detailed_text_widget.selectAll()

    def copy_detailed(self):
        clipboard = QtGui.QApplication.clipboard()
        selected_text = self.detailed_text_widget.textCursor().selectedText()
        clipboard.setText(selected_text)

<|next_version|>
# A patched version of QMessageBox that allows copying the error

import os
from ...external.qt import QtGui

__all__ = ['QMessageBoxPatched']

class QMessageBoxPatched(QtGui.QMessageBox):

    def __init__(self, *args, **kwargs):

        super(QMessageBoxPatched, self).__init__(*args, **kwargs)

        copy_action = QtGui.QAction('&Copy', self)
        copy_action.setShortcut(QtGui.QKeySequence.Copy)
        copy_action.triggered.connect(self.copy_detailed)

        select_all = QtGui.QAction('Select &All', self)
        select_all.setShortcut(QtGui.QKeySequence.SelectAll)
        select_all.triggered.connect(self.select_all)

        menubar = QtGui.QMenuBar()
        editMenu = menubar.addMenu('&Edit')
        editMenu.addAction(copy_action)
        editMenu.addAction(select_all)

        self.layout().setMenuBar(menubar)

    @property
    def detailed_text_widget(self):
        return self.findChild(QtGui.QTextEdit)

    def select_all(self):
        self.detailed_text_widget.selectAll()

    def copy_detailed(self):
        clipboard = QtGui.QApplication.clipboard()
        selected_text = self.detailed_text_widget.textCursor().selectedText()
        # Newlines are unicode, so need to normalize them to ASCII
        selected_text = os.linesep.join(selected_text.splitlines())
        clipboard.setText(selected_text)


Fix prob with wooden board leftover.

Fix prob with wooden board leftover.

--- pentai/gui/goodbye_screen.py
+++ pentai/gui/goodbye_screen.py
@@ -1,4 +1,5 @@
 import kivy.core.window
+from kivy.clock import Clock
 import pentai.db.zodb_dict as z_m

 from pentai.gui.screen import Screen
@@ -9,6 +10,10 @@
         print "init goodbye screen"

     def on_enter(self, *args, **kwargs):
+        # Was getting part of the wooden board on the screen
+        Clock.schedule_once(self.shutdown, 0.1)
+
+    def shutdown(self, ignored):
         app = self.app
         app_width, app_height = kivy.core.window.Window.size

<|original_code|>
import kivy.core.window
import pentai.db.zodb_dict as z_m

from pentai.gui.screen import Screen

class GoodByeScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(GoodByeScreen, self).__init__(*args, **kwargs)
        print "init goodbye screen"

    def on_enter(self, *args, **kwargs):
        app = self.app
        app_width, app_height = kivy.core.window.Window.size

        app.config.set("PentAI", "app_width", str(app_width))
        app.config.set("PentAI", "app_height", str(app_height))
        app.config.write()

        z_m.sync()
        z_m.pack()

        self.on_pre_leave()
        self.on_leave()

        app.stop()

<|edits_diff|>
--- pentai/gui/goodbye_screen.py
+++ pentai/gui/goodbye_screen.py
@@ -1,4 +1,5 @@
 import kivy.core.window
+from kivy.clock import Clock
 import pentai.db.zodb_dict as z_m

 from pentai.gui.screen import Screen
<|current_version|>
import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m

from pentai.gui.screen import Screen

class GoodByeScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(GoodByeScreen, self).__init__(*args, **kwargs)
        print "init goodbye screen"

    def on_enter(self, *args, **kwargs):
        app = self.app
        app_width, app_height = kivy.core.window.Window.size

        app.config.set("PentAI", "app_width", str(app_width))
        app.config.set("PentAI", "app_height", str(app_height))
        app.config.write()

        z_m.sync()
        z_m.pack()

        self.on_pre_leave()
        self.on_leave()

        app.stop()

<|next_version|>
import kivy.core.window
from kivy.clock import Clock
import pentai.db.zodb_dict as z_m

from pentai.gui.screen import Screen

class GoodByeScreen(Screen):
    def __init__(self, *args, **kwargs):
        super(GoodByeScreen, self).__init__(*args, **kwargs)
        print "init goodbye screen"

    def on_enter(self, *args, **kwargs):
        # Was getting part of the wooden board on the screen
        Clock.schedule_once(self.shutdown, 0.1)

    def shutdown(self, ignored):
        app = self.app
        app_width, app_height = kivy.core.window.Window.size

        app.config.set("PentAI", "app_width", str(app_width))
        app.config.set("PentAI", "app_height", str(app_height))
        app.config.write()

        z_m.sync()
        z_m.pack()

        self.on_pre_leave()
        self.on_leave()

        app.stop()


Call django.setup() for Django >= 1.7.0

Call django.setup() for Django >= 1.7.0

--- runtests.py
+++ runtests.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 import sys
+
+import django

 from django.conf import settings

@@ -24,6 +26,8 @@

 def runtests():
+    if django.VERSION >= (1,7,0):
+        django.setup()
     TestRunner = get_runner(settings)
     test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
     failures = test_runner.run_tests(['secure_input', ])

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

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=(
            'secure_input',
        ),
        SITE_ID=1,
        SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
    )

from django.test.utils import get_runner

def runtests():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
    failures = test_runner.run_tests(['secure_input', ])
    sys.exit(failures)

if __name__ == '__main__':
    runtests()

<|edits_diff|>
--- runtests.py
+++ runtests.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 import sys
+
+import django

 from django.conf import settings

<|current_version|>
#!/usr/bin/env python
import sys

import django

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=(
            'secure_input',
        ),
        SITE_ID=1,
        SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
    )

from django.test.utils import get_runner

def runtests():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
    failures = test_runner.run_tests(['secure_input', ])
    sys.exit(failures)

if __name__ == '__main__':
    runtests()

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

import django

from django.conf import settings

if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        INSTALLED_APPS=(
            'secure_input',
        ),
        SITE_ID=1,
        SECRET_KEY='this-is-just-for-tests-so-not-that-secret',
    )

from django.test.utils import get_runner

def runtests():
    if django.VERSION >= (1,7,0):
        django.setup()
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
    failures = test_runner.run_tests(['secure_input', ])
    sys.exit(failures)

if __name__ == '__main__':
    runtests()


Set current strategy on pyramid app

Set current strategy on pyramid app

--- social/apps/pyramid_app/__init__.py
+++ social/apps/pyramid_app/__init__.py
@@ -1,6 +1,13 @@
+from social.strategies.utils import set_current_strategy_getter
+from social.apps.pyramid_app.utils import load_strategy
+
+
 def includeme(config):
     config.add_route('social.auth', '/login/{backend}')
     config.add_route('social.complete', '/complete/{backend}')
     config.add_route('social.disconnect', '/disconnect/{backend}')
     config.add_route('social.disconnect_association',
                      '/disconnect/{backend}/{association_id}')
+
+
+set_current_strategy_getter(load_strategy)

<|original_code|>
def includeme(config):
    config.add_route('social.auth', '/login/{backend}')
    config.add_route('social.complete', '/complete/{backend}')
    config.add_route('social.disconnect', '/disconnect/{backend}')
    config.add_route('social.disconnect_association',
                     '/disconnect/{backend}/{association_id}')

<|edits_diff|>
--- social/apps/pyramid_app/__init__.py
+++ social/apps/pyramid_app/__init__.py
@@ -1,3 +1,7 @@
+from social.strategies.utils import set_current_strategy_getter
+from social.apps.pyramid_app.utils import load_strategy
+
+
 def includeme(config):
     config.add_route('social.auth', '/login/{backend}')
     config.add_route('social.complete', '/complete/{backend}')
<|current_version|>
from social.strategies.utils import set_current_strategy_getter
from social.apps.pyramid_app.utils import load_strategy

def includeme(config):
    config.add_route('social.auth', '/login/{backend}')
    config.add_route('social.complete', '/complete/{backend}')
    config.add_route('social.disconnect', '/disconnect/{backend}')
    config.add_route('social.disconnect_association',
                     '/disconnect/{backend}/{association_id}')

<|next_version|>
from social.strategies.utils import set_current_strategy_getter
from social.apps.pyramid_app.utils import load_strategy

def includeme(config):
    config.add_route('social.auth', '/login/{backend}')
    config.add_route('social.complete', '/complete/{backend}')
    config.add_route('social.disconnect', '/disconnect/{backend}')
    config.add_route('social.disconnect_association',
                     '/disconnect/{backend}/{association_id}')

set_current_strategy_getter(load_strategy)


Add log file for deleted lines.

Add log file for deleted lines.

--- passwd_change.py
+++ passwd_change.py
@@ -18,10 +18,16 @@
             with open(target_file, 'r') as t:
                 target_lines = t.readlines()

+            log = open('deletel.log', 'w')
+
             with open(result_file, 'w') as r:
                 for line in target_lines:
                     if line.split(':')[0] in keys or line.split(':')[3] != '12':
                         r.write(line)
+                    else:
+                        log.write(line)
+
+            log.close()

         except Exception as e:
             print(str(e))

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

import sys

_args = sys.argv

if __name__ == "__main__":
    if len(_args) == 4:
        keys_file = _args[1]
        target_file = _args[2]
        result_file = _args[3]

        try:
            with open(keys_file, 'r') as k:
                keys = k.readlines()
                keys = [key.strip().split('@')[0] for key in keys]
                keys = [key for key in keys if key != '']
            with open(target_file, 'r') as t:
                target_lines = t.readlines()

            with open(result_file, 'w') as r:
                for line in target_lines:
                    if line.split(':')[0] in keys or line.split(':')[3] != '12':
                        r.write(line)

        except Exception as e:
            print(str(e))
            sys.exit()
    else:
        print('./passwd_change.py keys_file.txt passwd_file result_file')

<|edits_diff|>
--- passwd_change.py
+++ passwd_change.py
@@ -18,6 +18,8 @@
             with open(target_file, 'r') as t:
                 target_lines = t.readlines()

+            log = open('deletel.log', 'w')
+
             with open(result_file, 'w') as r:
                 for line in target_lines:
                     if line.split(':')[0] in keys or line.split(':')[3] != '12':
<|current_version|>
#!/usr/bin/env python3

import sys

_args = sys.argv

if __name__ == "__main__":
    if len(_args) == 4:
        keys_file = _args[1]
        target_file = _args[2]
        result_file = _args[3]

        try:
            with open(keys_file, 'r') as k:
                keys = k.readlines()
                keys = [key.strip().split('@')[0] for key in keys]
                keys = [key for key in keys if key != '']
            with open(target_file, 'r') as t:
                target_lines = t.readlines()

            log = open('deletel.log', 'w')

            with open(result_file, 'w') as r:
                for line in target_lines:
                    if line.split(':')[0] in keys or line.split(':')[3] != '12':
                        r.write(line)

        except Exception as e:
            print(str(e))
            sys.exit()
    else:
        print('./passwd_change.py keys_file.txt passwd_file result_file')

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

import sys

_args = sys.argv

if __name__ == "__main__":
    if len(_args) == 4:
        keys_file = _args[1]
        target_file = _args[2]
        result_file = _args[3]

        try:
            with open(keys_file, 'r') as k:
                keys = k.readlines()
                keys = [key.strip().split('@')[0] for key in keys]
                keys = [key for key in keys if key != '']
            with open(target_file, 'r') as t:
                target_lines = t.readlines()

            log = open('deletel.log', 'w')

            with open(result_file, 'w') as r:
                for line in target_lines:
                    if line.split(':')[0] in keys or line.split(':')[3] != '12':
                        r.write(line)
                    else:
                        log.write(line)

            log.close()

        except Exception as e:
            print(str(e))
            sys.exit()
    else:
        print('./passwd_change.py keys_file.txt passwd_file result_file')


Add names to stanford view handlers

Add names to stanford view handlers

--- openedx/stanford/cms/urls.py
+++ openedx/stanford/cms/urls.py
@@ -13,14 +13,17 @@
     url(
         r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
         contentstore.views.utility_handler,
+        name='utility_handler',
     ),
     url(
         r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
         contentstore.views.utility_captions_handler,
+        name='utility_captions_handler',
     ),
     url(
         r'^utility/bulksettings/{}$'.format(settings.COURSE_KEY_PATTERN),
         contentstore.views.utility_bulksettings_handler,
+        name='utility_bulksettings_handler',
     ),
 ]
 if settings.SHIB_ONLY_SITE:

<|original_code|>
from django.conf import settings
from django.conf.urls import url

import contentstore.views

urlpatterns = [
    url(
        r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.send_test_enrollment_email,
        name='send_test_enrollment_email',
    ),
    url(
        r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_handler,
    ),
    url(
        r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_captions_handler,
    ),
    url(
        r'^utility/bulksettings/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_bulksettings_handler,
    ),
]
if settings.SHIB_ONLY_SITE:
    urlpatterns += [
        url(
            r'^backup_signup$',
            contentstore.views.signup,
            name='backup_signup',
        ),
        url(
            r'^backup_signin$',
            contentstore.views.login_page,
            name='backup_login',
        ),
    ]

<|edits_diff|>
--- openedx/stanford/cms/urls.py
+++ openedx/stanford/cms/urls.py
@@ -13,10 +13,12 @@
     url(
         r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
         contentstore.views.utility_handler,
+        name='utility_handler',
     ),
     url(
         r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
         contentstore.views.utility_captions_handler,
+        name='utility_captions_handler',
     ),
     url(
         r'^utility/bulksettings/{}$'.format(settings.COURSE_KEY_PATTERN),
<|current_version|>
from django.conf import settings
from django.conf.urls import url

import contentstore.views

urlpatterns = [
    url(
        r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.send_test_enrollment_email,
        name='send_test_enrollment_email',
    ),
    url(
        r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_handler,
        name='utility_handler',
    ),
    url(
        r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_captions_handler,
        name='utility_captions_handler',
    ),
    url(
        r'^utility/bulksettings/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_bulksettings_handler,
    ),
]
if settings.SHIB_ONLY_SITE:
    urlpatterns += [
        url(
            r'^backup_signup$',
            contentstore.views.signup,
            name='backup_signup',
        ),
        url(
            r'^backup_signin$',
            contentstore.views.login_page,
            name='backup_login',
        ),
    ]

<|next_version|>
from django.conf import settings
from django.conf.urls import url

import contentstore.views

urlpatterns = [
    url(
        r'^settings/send_test_enrollment_email/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.send_test_enrollment_email,
        name='send_test_enrollment_email',
    ),
    url(
        r'^utilities/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_handler,
        name='utility_handler',
    ),
    url(
        r'^utility/captions/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_captions_handler,
        name='utility_captions_handler',
    ),
    url(
        r'^utility/bulksettings/{}$'.format(settings.COURSE_KEY_PATTERN),
        contentstore.views.utility_bulksettings_handler,
        name='utility_bulksettings_handler',
    ),
]
if settings.SHIB_ONLY_SITE:
    urlpatterns += [
        url(
            r'^backup_signup$',
            contentstore.views.signup,
            name='backup_signup',
        ),
        url(
            r'^backup_signin$',
            contentstore.views.login_page,
            name='backup_login',
        ),
    ]


Add log to self play

Add log to self play

--- self_play.py
+++ self_play.py
@@ -6,6 +6,7 @@

   def __init__(self, game):
     self.game = game
+    self.log = []

   def play(self):
     while self.game.winner is None:
@@ -13,6 +14,7 @@
       if self.game.can_add_disc(col_index):
         success = self.game.try_turn(self.game.current_player, col_index)
         assert success
+        self.log.append(col_index)
     self.render_board()
     print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner))

<|original_code|>
import random

from game import Game, DiscState

class SelfPlay:

  def __init__(self, game):
    self.game = game

  def play(self):
    while self.game.winner is None:
      col_index = self.calc_move(self.game.current_player)
      if self.game.can_add_disc(col_index):
        success = self.game.try_turn(self.game.current_player, col_index)
        assert success
    self.render_board()
    print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner))

  def calc_move(self, current_player):
    return random.randint(0, self.game.grid.width)

  def render_board(self):
    str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"]
    for row in reversed(self.game.grid):
      row_repr = []
      for disc_value in row:
        if disc_value is DiscState.empty:
          row_repr.append("| |")
        elif disc_value is DiscState.red:
          row_repr.append("|O|")
        else:  # disc_value is black
          row_repr.append("|X|")
      row_repr.append("\n")
      str_repr += row_repr
    print("".join(str_repr))

  def disc_state_to_player_name(self, disc_state):
    if disc_state is DiscState.red:
      return "O"
    else:
      return "X"
<|edits_diff|>
--- self_play.py
+++ self_play.py
@@ -6,6 +6,7 @@

   def __init__(self, game):
     self.game = game
+    self.log = []

   def play(self):
     while self.game.winner is None:
<|current_version|>
import random

from game import Game, DiscState

class SelfPlay:

  def __init__(self, game):
    self.game = game
    self.log = []

  def play(self):
    while self.game.winner is None:
      col_index = self.calc_move(self.game.current_player)
      if self.game.can_add_disc(col_index):
        success = self.game.try_turn(self.game.current_player, col_index)
        assert success
    self.render_board()
    print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner))

  def calc_move(self, current_player):
    return random.randint(0, self.game.grid.width)

  def render_board(self):
    str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"]
    for row in reversed(self.game.grid):
      row_repr = []
      for disc_value in row:
        if disc_value is DiscState.empty:
          row_repr.append("| |")
        elif disc_value is DiscState.red:
          row_repr.append("|O|")
        else:  # disc_value is black
          row_repr.append("|X|")
      row_repr.append("\n")
      str_repr += row_repr
    print("".join(str_repr))

  def disc_state_to_player_name(self, disc_state):
    if disc_state is DiscState.red:
      return "O"
    else:
      return "X"
<|next_version|>
import random

from game import Game, DiscState

class SelfPlay:

  def __init__(self, game):
    self.game = game
    self.log = []

  def play(self):
    while self.game.winner is None:
      col_index = self.calc_move(self.game.current_player)
      if self.game.can_add_disc(col_index):
        success = self.game.try_turn(self.game.current_player, col_index)
        assert success
        self.log.append(col_index)
    self.render_board()
    print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner))

  def calc_move(self, current_player):
    return random.randint(0, self.game.grid.width)

  def render_board(self):
    str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"]
    for row in reversed(self.game.grid):
      row_repr = []
      for disc_value in row:
        if disc_value is DiscState.empty:
          row_repr.append("| |")
        elif disc_value is DiscState.red:
          row_repr.append("|O|")
        else:  # disc_value is black
          row_repr.append("|X|")
      row_repr.append("\n")
      str_repr += row_repr
    print("".join(str_repr))

  def disc_state_to_player_name(self, disc_state):
    if disc_state is DiscState.red:
      return "O"
    else:
      return "X"


Create GEM filter to get BBM App ID

Create GEM filter to get BBM App ID

--- gem/templatetags/gem_tags.py
+++ gem/templatetags/gem_tags.py
@@ -1,5 +1,7 @@
 from django.template import Library
 from django.conf import settings
+
+from gem.models import GemSettings

 register = Library()

@@ -7,6 +9,11 @@
 @register.simple_tag()
 def get_site_static_prefix():
     return settings.SITE_STATIC_PREFIX
+
+
+@register.filter()
+def get_bbm_app_id(request):
+    return GemSettings.for_site(request.site).bbm_app_id

 @register.filter('fieldtype')

<|original_code|>
from django.template import Library
from django.conf import settings

register = Library()

@register.simple_tag()
def get_site_static_prefix():
    return settings.SITE_STATIC_PREFIX

@register.filter('fieldtype')
def fieldtype(field):
    return field.field.widget.__class__.__name__

@register.filter(name='smarttruncatechars')
def smart_truncate_chars(value, max_length):

    if len(value) > max_length:
        truncd_val = value[:max_length]
        if value[max_length] != ' ':
            truncd_val = truncd_val[:truncd_val.rfind(' ')]

        return truncd_val + '...'

    return value

<|edits_diff|>
--- gem/templatetags/gem_tags.py
+++ gem/templatetags/gem_tags.py
@@ -1,5 +1,7 @@
 from django.template import Library
 from django.conf import settings
+
+from gem.models import GemSettings

 register = Library()

<|current_version|>
from django.template import Library
from django.conf import settings

from gem.models import GemSettings

register = Library()

@register.simple_tag()
def get_site_static_prefix():
    return settings.SITE_STATIC_PREFIX

@register.filter('fieldtype')
def fieldtype(field):
    return field.field.widget.__class__.__name__

@register.filter(name='smarttruncatechars')
def smart_truncate_chars(value, max_length):

    if len(value) > max_length:
        truncd_val = value[:max_length]
        if value[max_length] != ' ':
            truncd_val = truncd_val[:truncd_val.rfind(' ')]

        return truncd_val + '...'

    return value

<|next_version|>
from django.template import Library
from django.conf import settings

from gem.models import GemSettings

register = Library()

@register.simple_tag()
def get_site_static_prefix():
    return settings.SITE_STATIC_PREFIX

@register.filter()
def get_bbm_app_id(request):
    return GemSettings.for_site(request.site).bbm_app_id

@register.filter('fieldtype')
def fieldtype(field):
    return field.field.widget.__class__.__name__

@register.filter(name='smarttruncatechars')
def smart_truncate_chars(value, max_length):

    if len(value) > max_length:
        truncd_val = value[:max_length]
        if value[max_length] != ' ':
            truncd_val = truncd_val[:truncd_val.rfind(' ')]

        return truncd_val + '...'

    return value


Add verbose error for a meddling middleware

--- statictemplate/management/commands/statictemplate.py
+++ statictemplate/management/commands/statictemplate.py
@@ -9,6 +9,10 @@
 from django.shortcuts import render_to_response
 from django.template.context import RequestContext
 from django.test.client import Client
+
+
+class InvalidResponseError(Exception):
+    pass

 @contextmanager
@@ -27,6 +31,10 @@
     with override_urlconf():
         client = Client()
         response = client.get('/', {'template': template})
+        if response.status_code != 200:
+            raise InvalidResponseError(
+                'Response code was %d' % response.status_code
+            )
         return response.content

<|original_code|>
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
    from django.conf.urls.defaults import patterns, url, include
except ImportError:
    from django.conf.urls import patterns, url, include  # pragma: no cover
from django.core.management.base import BaseCommand
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client

@contextmanager
def override_urlconf():
    has_old = hasattr(settings, 'ROOT_URLCONF')
    old = getattr(settings, 'ROOT_URLCONF', None)
    settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
    yield
    if has_old:
        setattr(settings, 'ROOT_URLCONF', old)
    else:  # pragma: no cover
        delattr(settings, 'ROOT_URLCONF')

def make_static(template):
    with override_urlconf():
        client = Client()
        response = client.get('/', {'template': template})
        return response.content

class Command(BaseCommand):
    def handle(self, template, **options):
        output = make_static(template)
        self.stdout.write(output)

def render(request):
    template_name = request.GET['template']
    return render_to_response(template_name, RequestContext(request))

urlpatterns = patterns('',
    url('^$', render),
    url('^others', include(settings.ROOT_URLCONF))
)

<|edits_diff|>
--- statictemplate/management/commands/statictemplate.py
+++ statictemplate/management/commands/statictemplate.py
@@ -9,6 +9,10 @@
 from django.shortcuts import render_to_response
 from django.template.context import RequestContext
 from django.test.client import Client
+
+
+class InvalidResponseError(Exception):
+    pass

 @contextmanager
<|current_version|>
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
    from django.conf.urls.defaults import patterns, url, include
except ImportError:
    from django.conf.urls import patterns, url, include  # pragma: no cover
from django.core.management.base import BaseCommand
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client

class InvalidResponseError(Exception):
    pass

@contextmanager
def override_urlconf():
    has_old = hasattr(settings, 'ROOT_URLCONF')
    old = getattr(settings, 'ROOT_URLCONF', None)
    settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
    yield
    if has_old:
        setattr(settings, 'ROOT_URLCONF', old)
    else:  # pragma: no cover
        delattr(settings, 'ROOT_URLCONF')

def make_static(template):
    with override_urlconf():
        client = Client()
        response = client.get('/', {'template': template})
        return response.content

class Command(BaseCommand):
    def handle(self, template, **options):
        output = make_static(template)
        self.stdout.write(output)

def render(request):
    template_name = request.GET['template']
    return render_to_response(template_name, RequestContext(request))

urlpatterns = patterns('',
    url('^$', render),
    url('^others', include(settings.ROOT_URLCONF))
)

<|next_version|>
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from django.conf import settings
try:
    from django.conf.urls.defaults import patterns, url, include
except ImportError:
    from django.conf.urls import patterns, url, include  # pragma: no cover
from django.core.management.base import BaseCommand
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.test.client import Client

class InvalidResponseError(Exception):
    pass

@contextmanager
def override_urlconf():
    has_old = hasattr(settings, 'ROOT_URLCONF')
    old = getattr(settings, 'ROOT_URLCONF', None)
    settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
    yield
    if has_old:
        setattr(settings, 'ROOT_URLCONF', old)
    else:  # pragma: no cover
        delattr(settings, 'ROOT_URLCONF')

def make_static(template):
    with override_urlconf():
        client = Client()
        response = client.get('/', {'template': template})
        if response.status_code != 200:
            raise InvalidResponseError(
                'Response code was %d' % response.status_code
            )
        return response.content

class Command(BaseCommand):
    def handle(self, template, **options):
        output = make_static(template)
        self.stdout.write(output)

def render(request):
    template_name = request.GET['template']
    return render_to_response(template_name, RequestContext(request))

urlpatterns = patterns('',
    url('^$', render),
    url('^others', include(settings.ROOT_URLCONF))
)


Add api end point /api-detail/

Add api end point /api-detail/

--- gom_server/char_attr/router.py
+++ gom_server/char_attr/router.py
@@ -17,7 +17,11 @@
    def get_queryset(self):
       gameid = self.kwargs['gameid']
       return models.AttributeType.objects.filter(game=gameid)
+class AttributeDetailViewSet(viewsets.ModelViewSet):
+   serializer_class = AttributeSerializer
+   queryset = models.Attribute.objects.all()

 # Register actual routes when called by master urls.py
 def addRoutes(router):
    router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes')
+   router.register(r'attrib-detail', AttributeDetailViewSet)

<|original_code|>
from rest_framework import routers, serializers, viewsets
import models

# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
   class Meta:
      model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
   attributes = AttributeSerializer(many=True, read_only=True)
   class Meta:
      model = models.AttributeType
      fields = ('id', 'game', 'title', 'short_desc', 'attributes')

# ViewSets define the view behavior.
class AttributesViewSet(viewsets.ModelViewSet):
   serializer_class = AttributeTypeSerializer
   def get_queryset(self):
      gameid = self.kwargs['gameid']
      return models.AttributeType.objects.filter(game=gameid)

# Register actual routes when called by master urls.py
def addRoutes(router):
   router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes')

<|edits_diff|>
--- gom_server/char_attr/router.py
+++ gom_server/char_attr/router.py
@@ -17,6 +17,9 @@
    def get_queryset(self):
       gameid = self.kwargs['gameid']
       return models.AttributeType.objects.filter(game=gameid)
+class AttributeDetailViewSet(viewsets.ModelViewSet):
+   serializer_class = AttributeSerializer
+   queryset = models.Attribute.objects.all()

 # Register actual routes when called by master urls.py
 def addRoutes(router):
<|current_version|>
from rest_framework import routers, serializers, viewsets
import models

# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
   class Meta:
      model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
   attributes = AttributeSerializer(many=True, read_only=True)
   class Meta:
      model = models.AttributeType
      fields = ('id', 'game', 'title', 'short_desc', 'attributes')

# ViewSets define the view behavior.
class AttributesViewSet(viewsets.ModelViewSet):
   serializer_class = AttributeTypeSerializer
   def get_queryset(self):
      gameid = self.kwargs['gameid']
      return models.AttributeType.objects.filter(game=gameid)
class AttributeDetailViewSet(viewsets.ModelViewSet):
   serializer_class = AttributeSerializer
   queryset = models.Attribute.objects.all()

# Register actual routes when called by master urls.py
def addRoutes(router):
   router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes')

<|next_version|>
from rest_framework import routers, serializers, viewsets
import models

# Serializers define the API representation.
class AttributeSerializer(serializers.ModelSerializer):
   class Meta:
      model = models.Attribute
class AttributeTypeSerializer(serializers.ModelSerializer):
   attributes = AttributeSerializer(many=True, read_only=True)
   class Meta:
      model = models.AttributeType
      fields = ('id', 'game', 'title', 'short_desc', 'attributes')

# ViewSets define the view behavior.
class AttributesViewSet(viewsets.ModelViewSet):
   serializer_class = AttributeTypeSerializer
   def get_queryset(self):
      gameid = self.kwargs['gameid']
      return models.AttributeType.objects.filter(game=gameid)
class AttributeDetailViewSet(viewsets.ModelViewSet):
   serializer_class = AttributeSerializer
   queryset = models.Attribute.objects.all()

# Register actual routes when called by master urls.py
def addRoutes(router):
   router.register(r'attrib/(?P<gameid>[0-9]+)', AttributesViewSet, base_name='attributes')
   router.register(r'attrib-detail', AttributeDetailViewSet)


Stop device discovery after onboarding

Stop device discovery after onboarding

--- senic_hub/backend/views/setup_config.py
+++ senic_hub/backend/views/setup_config.py
@@ -2,6 +2,7 @@

 from ..commands import create_configuration_files_and_restart_apps_
 from ..config import path
+from ..supervisor import get_supervisor_rpc_client, stop_program

 configuration_service = Service(
@@ -15,3 +16,7 @@
 @configuration_service.post()
 def configuration_create_view(request):
     create_configuration_files_and_restart_apps_(request.registry.settings)
+
+    # stop device discovery daemon
+    supervisorctl = get_supervisor_rpc_client()
+    stop_program('device_discovery', supervisorctl)

<|original_code|>
from cornice.service import Service

from ..commands import create_configuration_files_and_restart_apps_
from ..config import path

configuration_service = Service(
    name='configuration_create',
    path=path('setup/config'),
    renderer='json',
    accept='application/json',
)

@configuration_service.post()
def configuration_create_view(request):
    create_configuration_files_and_restart_apps_(request.registry.settings)

<|edits_diff|>
--- senic_hub/backend/views/setup_config.py
+++ senic_hub/backend/views/setup_config.py
@@ -2,6 +2,7 @@

 from ..commands import create_configuration_files_and_restart_apps_
 from ..config import path
+from ..supervisor import get_supervisor_rpc_client, stop_program

 configuration_service = Service(
<|current_version|>
from cornice.service import Service

from ..commands import create_configuration_files_and_restart_apps_
from ..config import path
from ..supervisor import get_supervisor_rpc_client, stop_program

configuration_service = Service(
    name='configuration_create',
    path=path('setup/config'),
    renderer='json',
    accept='application/json',
)

@configuration_service.post()
def configuration_create_view(request):
    create_configuration_files_and_restart_apps_(request.registry.settings)

<|next_version|>
from cornice.service import Service

from ..commands import create_configuration_files_and_restart_apps_
from ..config import path
from ..supervisor import get_supervisor_rpc_client, stop_program

configuration_service = Service(
    name='configuration_create',
    path=path('setup/config'),
    renderer='json',
    accept='application/json',
)

@configuration_service.post()
def configuration_create_view(request):
    create_configuration_files_and_restart_apps_(request.registry.settings)

    # stop device discovery daemon
    supervisorctl = get_supervisor_rpc_client()
    stop_program('device_discovery', supervisorctl)


Decrease noise from code-style test

Decrease noise from code-style test

--- tests/test_style.py
+++ tests/test_style.py
@@ -1,9 +1,12 @@
+import logging
 import pkg_resources
 import unittest

 class CodeStyleTestCase(unittest.TestCase):
     def test_code_style(self):
+        logger = logging.getLogger('flake8')
+        logger.setLevel(logging.ERROR)
         flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
         try:
             flake8([])

<|original_code|>
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')

<|edits_diff|>
--- tests/test_style.py
+++ tests/test_style.py
@@ -1,3 +1,4 @@
+import logging
 import pkg_resources
 import unittest

<|current_version|>
import logging
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')

<|next_version|>
import logging
import pkg_resources
import unittest

class CodeStyleTestCase(unittest.TestCase):
    def test_code_style(self):
        logger = logging.getLogger('flake8')
        logger.setLevel(logging.ERROR)
        flake8 = pkg_resources.load_entry_point('flake8', 'console_scripts', 'flake8')
        try:
            flake8([])
        except SystemExit as e:
            if e.code != 0:
                self.fail('Code style checks failed')


Add NetworkX version checking to nffg_lib package

--- __init__.py
+++ __init__.py
@@ -14,7 +14,14 @@
 """
 Internal graph-based implementation of Network Function Forwarding Graph
 """
+from networkx.release import get_info, major as nx_major
+
+# Enabled imports directly from nffg_lib package
 from nffg import NFFG, NFFGToolBox
+
+if int(nx_major) > 1:
+  raise RuntimeError(
+    "NetworkX version(<2.0): %s is not supported!" % get_info()[2])

 __version__ = nffg.VERSION
 __all__ = ["NFFG", "NFFGToolBox"]

<|original_code|>
# Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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.
"""
Internal graph-based implementation of Network Function Forwarding Graph
"""
from nffg import NFFG, NFFGToolBox

__version__ = nffg.VERSION
__all__ = ["NFFG", "NFFGToolBox"]

<|edits_diff|>
--- __init__.py
+++ __init__.py
@@ -14,6 +14,9 @@
 """
 Internal graph-based implementation of Network Function Forwarding Graph
 """
+from networkx.release import get_info, major as nx_major
+
+# Enabled imports directly from nffg_lib package
 from nffg import NFFG, NFFGToolBox

 __version__ = nffg.VERSION
<|current_version|>
# Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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.
"""
Internal graph-based implementation of Network Function Forwarding Graph
"""
from networkx.release import get_info, major as nx_major

# Enabled imports directly from nffg_lib package
from nffg import NFFG, NFFGToolBox

__version__ = nffg.VERSION
__all__ = ["NFFG", "NFFGToolBox"]

<|next_version|>
# Copyright 2017 Janos Czentye, Balazs Nemeth, Balazs Sonkoly
#
# 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.
"""
Internal graph-based implementation of Network Function Forwarding Graph
"""
from networkx.release import get_info, major as nx_major

# Enabled imports directly from nffg_lib package
from nffg import NFFG, NFFGToolBox

if int(nx_major) > 1:
  raise RuntimeError(
    "NetworkX version(<2.0): %s is not supported!" % get_info()[2])

__version__ = nffg.VERSION
__all__ = ["NFFG", "NFFGToolBox"]


Add the variable `plata.price_includes_tax` to the template context

--- plata/context_processors.py
+++ plata/context_processors.py
@@ -7,6 +7,7 @@
     * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
     * ``plata.order``: The current order
     * ``plata.contact``: The current contact instance
+    * ``plata.price_includes_tax``: Whether prices include tax or not
     """

     shop = plata.shop_instance()
@@ -17,4 +18,5 @@
         'shop': shop,
         'order': shop.order_from_request(request),
         'contact': shop.contact_from_user(request.user),
+        'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX,
         }}

<|original_code|>
import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        }}

<|edits_diff|>
--- plata/context_processors.py
+++ plata/context_processors.py
@@ -7,6 +7,7 @@
     * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
     * ``plata.order``: The current order
     * ``plata.contact``: The current contact instance
+    * ``plata.price_includes_tax``: Whether prices include tax or not
     """

     shop = plata.shop_instance()
<|current_version|>
import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    * ``plata.price_includes_tax``: Whether prices include tax or not
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        }}

<|next_version|>
import plata

def plata_context(request):
    """
    Adds a few variables from Plata to the context if they are available:

    * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance
    * ``plata.order``: The current order
    * ``plata.contact``: The current contact instance
    * ``plata.price_includes_tax``: Whether prices include tax or not
    """

    shop = plata.shop_instance()
    if not shop:
        return {}

    return {'plata': {
        'shop': shop,
        'order': shop.order_from_request(request),
        'contact': shop.contact_from_user(request.user),
        'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX,
        }}


Add SSLify to force SSL

Add SSLify to force SSL

--- slot/main.py
+++ slot/main.py
@@ -3,6 +3,7 @@
 from flask import Flask
 from flask_cache import Cache
 from flask_login import LoginManager
+from flask_sslify import SSLify

 # Set up logging
 log = logging.getLogger('slot')
@@ -13,6 +14,7 @@

 app = Flask(__name__)
 app.config.from_object('config')
+sslify = SSLify(app, age=300)
 cache = Cache(app, config={'CACHE_TYPE': 'redis'})

 with app.app_context():

<|original_code|>
import logging

from flask import Flask
from flask_cache import Cache
from flask_login import LoginManager

# Set up logging
log = logging.getLogger('slot')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)

app = Flask(__name__)
app.config.from_object('config')
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

with app.app_context():
    cache.clear()

from slot.users.views import users_blueprint
from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure
import slot.users.controller as user_controller
import db_fieldbook as db

app.register_blueprint(users_blueprint)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = "strong"
login_manager.login_view = "users.login"

@login_manager.user_loader
def load_user(user_id):
    print("Loading user {0}".format(user_id))
    result = user_controller.return_user_instance_or_anonymous(db.get_user(user_id))
    return result

<|edits_diff|>
--- slot/main.py
+++ slot/main.py
@@ -3,6 +3,7 @@
 from flask import Flask
 from flask_cache import Cache
 from flask_login import LoginManager
+from flask_sslify import SSLify

 # Set up logging
 log = logging.getLogger('slot')
<|current_version|>
import logging

from flask import Flask
from flask_cache import Cache
from flask_login import LoginManager
from flask_sslify import SSLify

# Set up logging
log = logging.getLogger('slot')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)

app = Flask(__name__)
app.config.from_object('config')
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

with app.app_context():
    cache.clear()

from slot.users.views import users_blueprint
from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure
import slot.users.controller as user_controller
import db_fieldbook as db

app.register_blueprint(users_blueprint)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = "strong"
login_manager.login_view = "users.login"

@login_manager.user_loader
def load_user(user_id):
    print("Loading user {0}".format(user_id))
    result = user_controller.return_user_instance_or_anonymous(db.get_user(user_id))
    return result

<|next_version|>
import logging

from flask import Flask
from flask_cache import Cache
from flask_login import LoginManager
from flask_sslify import SSLify

# Set up logging
log = logging.getLogger('slot')
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)

app = Flask(__name__)
app.config.from_object('config')
sslify = SSLify(app, age=300)
cache = Cache(app, config={'CACHE_TYPE': 'redis'})

with app.app_context():
    cache.clear()

from slot.users.views import users_blueprint
from routes import dashboard, render_new_procedure_form, receive_sms, complete_procedure
import slot.users.controller as user_controller
import db_fieldbook as db

app.register_blueprint(users_blueprint)

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = "strong"
login_manager.login_view = "users.login"

@login_manager.user_loader
def load_user(user_id):
    print("Loading user {0}".format(user_id))
    result = user_controller.return_user_instance_or_anonymous(db.get_user(user_id))
    return result


Update the pipeline to take into account the outlier rejection method to compute the RPP

--- pipeline/compute_rpp/compute_rpp.py
+++ pipeline/compute_rpp/compute_rpp.py
@@ -3,6 +3,7 @@
 import numpy as np

 from skcycling.utils import load_power_from_fit
+from skcycling.restoration import denoise
 from skcycling.power_profile import Rpp

 # The first input argument corresponding to the data path
@@ -26,6 +27,8 @@
     print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
     # Open the file
     power_ride = load_power_from_fit(filename)
+    # Reject the outliers using thresholding method
+    power_ride = denoise.outliers_rejection(power_ride)
     # Fit the ride
     rpp_rider.fit(power_ride)

<|original_code|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)

<|edits_diff|>
--- pipeline/compute_rpp/compute_rpp.py
+++ pipeline/compute_rpp/compute_rpp.py
@@ -3,6 +3,7 @@
 import numpy as np

 from skcycling.utils import load_power_from_fit
+from skcycling.restoration import denoise
 from skcycling.power_profile import Rpp

 # The first input argument corresponding to the data path
<|current_version|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)

<|next_version|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Reject the outliers using thresholding method
    power_ride = denoise.outliers_rejection(power_ride)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)


Add option to turn on queue auto delete

Add option to turn on queue auto delete

--- pyon/util/int_test.py
+++ pyon/util/int_test.py
@@ -7,6 +7,7 @@

 from pyon.container.cc import Container
 from pyon.core.bootstrap import bootstrap_pyon
+from mock import patch

 # Make this call more deterministic in time.
 bootstrap_pyon()
@@ -45,3 +46,8 @@
         if self.container:
             self.container.stop()
             self.container = None
+
+    def _turn_on_queue_auto_delete(self):
+        patcher = patch('pyon.net.channel.RecvChannel._queue_auto_delete', True)
+        patcher.start()
+        self.addCleanup(patcher.stop)

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

"""Integration test base class and utils"""

from contextlib import contextmanager
import unittest

from pyon.container.cc import Container
from pyon.core.bootstrap import bootstrap_pyon

# Make this call more deterministic in time.
bootstrap_pyon()

class IonIntegrationTestCase(unittest.TestCase):
    """
    Base test class to allow operations such as starting the container
    TODO: Integrate with IonUnitTestCase
    """

    def run(self, result=None):
        unittest.TestCase.run(self, result)

    @contextmanager
    def container(self):
        """
        Context Manager for container in tests.
        To use:
        with self.container() as cc:
            # your tests in here
        # container stopped here
        """
        self._start_container()
        try:
            yield self.container
        finally:
            self._stop_container()

    def _start_container(self):
        self.container = None
        self.addCleanup(self._stop_container)
        self.container = Container()
        self.container.start()

    def _stop_container(self):
        if self.container:
            self.container.stop()
            self.container = None

<|edits_diff|>
--- pyon/util/int_test.py
+++ pyon/util/int_test.py
@@ -7,6 +7,7 @@

 from pyon.container.cc import Container
 from pyon.core.bootstrap import bootstrap_pyon
+from mock import patch

 # Make this call more deterministic in time.
 bootstrap_pyon()
<|current_version|>
#!/usr/bin/env python

"""Integration test base class and utils"""

from contextlib import contextmanager
import unittest

from pyon.container.cc import Container
from pyon.core.bootstrap import bootstrap_pyon
from mock import patch

# Make this call more deterministic in time.
bootstrap_pyon()

class IonIntegrationTestCase(unittest.TestCase):
    """
    Base test class to allow operations such as starting the container
    TODO: Integrate with IonUnitTestCase
    """

    def run(self, result=None):
        unittest.TestCase.run(self, result)

    @contextmanager
    def container(self):
        """
        Context Manager for container in tests.
        To use:
        with self.container() as cc:
            # your tests in here
        # container stopped here
        """
        self._start_container()
        try:
            yield self.container
        finally:
            self._stop_container()

    def _start_container(self):
        self.container = None
        self.addCleanup(self._stop_container)
        self.container = Container()
        self.container.start()

    def _stop_container(self):
        if self.container:
            self.container.stop()
            self.container = None

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

"""Integration test base class and utils"""

from contextlib import contextmanager
import unittest

from pyon.container.cc import Container
from pyon.core.bootstrap import bootstrap_pyon
from mock import patch

# Make this call more deterministic in time.
bootstrap_pyon()

class IonIntegrationTestCase(unittest.TestCase):
    """
    Base test class to allow operations such as starting the container
    TODO: Integrate with IonUnitTestCase
    """

    def run(self, result=None):
        unittest.TestCase.run(self, result)

    @contextmanager
    def container(self):
        """
        Context Manager for container in tests.
        To use:
        with self.container() as cc:
            # your tests in here
        # container stopped here
        """
        self._start_container()
        try:
            yield self.container
        finally:
            self._stop_container()

    def _start_container(self):
        self.container = None
        self.addCleanup(self._stop_container)
        self.container = Container()
        self.container.start()

    def _stop_container(self):
        if self.container:
            self.container.stop()
            self.container = None

    def _turn_on_queue_auto_delete(self):
        patcher = patch('pyon.net.channel.RecvChannel._queue_auto_delete', True)
        patcher.start()
        self.addCleanup(patcher.stop)


Add logging to email daemon

Add logging to email daemon

--- sremailer.py
+++ sremailer.py
@@ -4,16 +4,21 @@
 # obtain one at http://mozilla.org/MPL/2.0/.

 import bottle
+import logging

 import stoneridge

 @bottle.post('/email')
 def email():
+    logging.debug('handling email')
     r = bottle.request.forms
     to = r.get('to')
+    logging.debug('to: %s' % (to,))
     subject = r.get('subject')
+    logging.debug('subject: %s' % (subject,))
     msg = r.get('message')
+    logging.debug('message: %s' % (msg,))

     stoneridge.sendmail(to, subject, msg)

<|original_code|>
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

import bottle

import stoneridge

@bottle.post('/email')
def email():
    r = bottle.request.forms
    to = r.get('to')
    subject = r.get('subject')
    msg = r.get('message')

    stoneridge.sendmail(to, subject, msg)

def daemon():
    stoneridge.StreamLogger.bottle_inject()
    bottle.run(host='0.0.0.0', port=2255)

@stoneridge.main
def main():
    parser = stoneridge.DaemonArgumentParser()
    parser.parse_args()
    parser.start_daemon(daemon)

<|edits_diff|>
--- sremailer.py
+++ sremailer.py
@@ -4,15 +4,19 @@
 # obtain one at http://mozilla.org/MPL/2.0/.

 import bottle
+import logging

 import stoneridge

 @bottle.post('/email')
 def email():
+    logging.debug('handling email')
     r = bottle.request.forms
     to = r.get('to')
+    logging.debug('to: %s' % (to,))
     subject = r.get('subject')
+    logging.debug('subject: %s' % (subject,))
     msg = r.get('message')

     stoneridge.sendmail(to, subject, msg)
<|current_version|>
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

import bottle
import logging

import stoneridge

@bottle.post('/email')
def email():
    logging.debug('handling email')
    r = bottle.request.forms
    to = r.get('to')
    logging.debug('to: %s' % (to,))
    subject = r.get('subject')
    logging.debug('subject: %s' % (subject,))
    msg = r.get('message')

    stoneridge.sendmail(to, subject, msg)

def daemon():
    stoneridge.StreamLogger.bottle_inject()
    bottle.run(host='0.0.0.0', port=2255)

@stoneridge.main
def main():
    parser = stoneridge.DaemonArgumentParser()
    parser.parse_args()
    parser.start_daemon(daemon)

<|next_version|>
#!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at http://mozilla.org/MPL/2.0/.

import bottle
import logging

import stoneridge

@bottle.post('/email')
def email():
    logging.debug('handling email')
    r = bottle.request.forms
    to = r.get('to')
    logging.debug('to: %s' % (to,))
    subject = r.get('subject')
    logging.debug('subject: %s' % (subject,))
    msg = r.get('message')
    logging.debug('message: %s' % (msg,))

    stoneridge.sendmail(to, subject, msg)

def daemon():
    stoneridge.StreamLogger.bottle_inject()
    bottle.run(host='0.0.0.0', port=2255)

@stoneridge.main
def main():
    parser = stoneridge.DaemonArgumentParser()
    parser.parse_args()
    parser.start_daemon(daemon)


Add logging to icds reports task

Add logging to icds reports task

--- custom/icds_reports/tasks.py
+++ custom/icds_reports/tasks.py
@@ -1,3 +1,4 @@
+import logging
 import os

 from celery.schedules import crontab
@@ -5,6 +6,8 @@
 from django.conf import settings

 from django.db import connections
+
+celery_task_logger = logging.getLogger('celery.task')

 @periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True)
@@ -14,12 +17,20 @@
         with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:

             path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
+            celery_task_logger.info("Starting icds reports update_location_tables")
             with open(path, "r") as sql_file:
                 sql_to_execute = sql_file.read()
                 cursor.execute(sql_to_execute)
+            celery_task_logger.info("Ended icds reports update_location_tables_sql")

             path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
             with open(path, "r") as sql_file:
                 sql_to_execute = sql_file.read()
                 for interval in ["0 months", "1 months", "2 months"]:
+                    celery_task_logger.info(
+                        "Starting icds reports {} update_monthly_aggregate_tables".format(interval)
+                    )
                     cursor.execute(sql_to_execute, {"interval": interval})
+                    celery_task_logger.info(
+                        "Ended icds reports {} update_monthly_aggregate_tables".format(interval)
+                    )

<|original_code|>
import os

from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings

from django.db import connections

@periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True)
def move_ucr_data_into_aggregation_tables():

    if hasattr(settings, "ICDS_UCR_DATABASE_ALIAS") and settings.ICDS_UCR_DATABASE_ALIAS:
        with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                cursor.execute(sql_to_execute)

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                for interval in ["0 months", "1 months", "2 months"]:
                    cursor.execute(sql_to_execute, {"interval": interval})

<|edits_diff|>
--- custom/icds_reports/tasks.py
+++ custom/icds_reports/tasks.py
@@ -1,3 +1,4 @@
+import logging
 import os

 from celery.schedules import crontab
@@ -5,6 +6,8 @@
 from django.conf import settings

 from django.db import connections
+
+celery_task_logger = logging.getLogger('celery.task')

 @periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True)
@@ -14,12 +17,17 @@
         with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:

             path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
+            celery_task_logger.info("Starting icds reports update_location_tables")
             with open(path, "r") as sql_file:
                 sql_to_execute = sql_file.read()
                 cursor.execute(sql_to_execute)
+            celery_task_logger.info("Ended icds reports update_location_tables_sql")

             path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
             with open(path, "r") as sql_file:
                 sql_to_execute = sql_file.read()
                 for interval in ["0 months", "1 months", "2 months"]:
+                    celery_task_logger.info(
+                        "Starting icds reports {} update_monthly_aggregate_tables".format(interval)
+                    )
                     cursor.execute(sql_to_execute, {"interval": interval})
<|current_version|>
import logging
import os

from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings

from django.db import connections

celery_task_logger = logging.getLogger('celery.task')

@periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True)
def move_ucr_data_into_aggregation_tables():

    if hasattr(settings, "ICDS_UCR_DATABASE_ALIAS") and settings.ICDS_UCR_DATABASE_ALIAS:
        with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
            celery_task_logger.info("Starting icds reports update_location_tables")
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                cursor.execute(sql_to_execute)
            celery_task_logger.info("Ended icds reports update_location_tables_sql")

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                for interval in ["0 months", "1 months", "2 months"]:
                    celery_task_logger.info(
                        "Starting icds reports {} update_monthly_aggregate_tables".format(interval)
                    )
                    cursor.execute(sql_to_execute, {"interval": interval})

<|next_version|>
import logging
import os

from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings

from django.db import connections

celery_task_logger = logging.getLogger('celery.task')

@periodic_task(run_every=crontab(minute=0, hour=0), acks_late=True)
def move_ucr_data_into_aggregation_tables():

    if hasattr(settings, "ICDS_UCR_DATABASE_ALIAS") and settings.ICDS_UCR_DATABASE_ALIAS:
        with connections[settings.ICDS_UCR_DATABASE_ALIAS].cursor() as cursor:

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_locations_table.sql')
            celery_task_logger.info("Starting icds reports update_location_tables")
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                cursor.execute(sql_to_execute)
            celery_task_logger.info("Ended icds reports update_location_tables_sql")

            path = os.path.join(os.path.dirname(__file__), 'sql_templates', 'update_monthly_aggregate_tables.sql')
            with open(path, "r") as sql_file:
                sql_to_execute = sql_file.read()
                for interval in ["0 months", "1 months", "2 months"]:
                    celery_task_logger.info(
                        "Starting icds reports {} update_monthly_aggregate_tables".format(interval)
                    )
                    cursor.execute(sql_to_execute, {"interval": interval})
                    celery_task_logger.info(
                        "Ended icds reports {} update_monthly_aggregate_tables".format(interval)
                    )


Clean up after cloned repo if needed. (partial checkin)

--- cookiecutter/main.py
+++ cookiecutter/main.py
@@ -14,6 +14,7 @@
 import argparse
 import os

+from .cleanup import remove_repo
 from .find import find_template
 from .generate import generate_context, generate_files
 from .vcs import git_clone
@@ -34,6 +35,7 @@

     # If it's a git repo, clone and prompt
     if args.input_dir.endswith('.git'):
+        got_repo_arg = True
         repo_dir = git_clone(args.input_dir)
         project_template = find_template(repo_dir)
         os.chdir(repo_dir)
@@ -47,6 +49,11 @@
         context=context
     )

+    # Remove repo if Cookiecutter cloned it in the first place.
+    # Here the user just wants a project, not a project template.
+    if got_repo_arg:
+        generated_project = context['project']['repo_name']
+        remove_repo(repo_dir, generated_project)

 if __name__ == '__main__':
     main()

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

"""
cookiecutter.main
-----------------

Main entry point for the `cookiecutter` command.

The code in this module is also a good example of how to use Cookiecutter as a
library rather than a script.
"""

import argparse
import os

from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone

def main():
    """ Entry point for the package, as defined in setup.py. """

    # Get command line input/output arguments
    parser = argparse.ArgumentParser(
        description='Create a project from a Cookiecutter project template.'
    )
    parser.add_argument(
        'input_dir',
        help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
    )
    args = parser.parse_args()

    # If it's a git repo, clone and prompt
    if args.input_dir.endswith('.git'):
        repo_dir = git_clone(args.input_dir)
        project_template = find_template(repo_dir)
        os.chdir(repo_dir)
    else:
        project_template = args.input_dir

    # Create project from local context and project template.
    context = generate_context()
    generate_files(
        input_dir=project_template,
        context=context
    )

if __name__ == '__main__':
    main()

<|edits_diff|>
--- cookiecutter/main.py
+++ cookiecutter/main.py
@@ -14,6 +14,7 @@
 import argparse
 import os

+from .cleanup import remove_repo
 from .find import find_template
 from .generate import generate_context, generate_files
 from .vcs import git_clone
@@ -34,6 +35,7 @@

     # If it's a git repo, clone and prompt
     if args.input_dir.endswith('.git'):
+        got_repo_arg = True
         repo_dir = git_clone(args.input_dir)
         project_template = find_template(repo_dir)
         os.chdir(repo_dir)
<|current_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
cookiecutter.main
-----------------

Main entry point for the `cookiecutter` command.

The code in this module is also a good example of how to use Cookiecutter as a
library rather than a script.
"""

import argparse
import os

from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone

def main():
    """ Entry point for the package, as defined in setup.py. """

    # Get command line input/output arguments
    parser = argparse.ArgumentParser(
        description='Create a project from a Cookiecutter project template.'
    )
    parser.add_argument(
        'input_dir',
        help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
    )
    args = parser.parse_args()

    # If it's a git repo, clone and prompt
    if args.input_dir.endswith('.git'):
        got_repo_arg = True
        repo_dir = git_clone(args.input_dir)
        project_template = find_template(repo_dir)
        os.chdir(repo_dir)
    else:
        project_template = args.input_dir

    # Create project from local context and project template.
    context = generate_context()
    generate_files(
        input_dir=project_template,
        context=context
    )

if __name__ == '__main__':
    main()

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

"""
cookiecutter.main
-----------------

Main entry point for the `cookiecutter` command.

The code in this module is also a good example of how to use Cookiecutter as a
library rather than a script.
"""

import argparse
import os

from .cleanup import remove_repo
from .find import find_template
from .generate import generate_context, generate_files
from .vcs import git_clone

def main():
    """ Entry point for the package, as defined in setup.py. """

    # Get command line input/output arguments
    parser = argparse.ArgumentParser(
        description='Create a project from a Cookiecutter project template.'
    )
    parser.add_argument(
        'input_dir',
        help='Cookiecutter project template dir, e.g. {{project.repo_name}}/'
    )
    args = parser.parse_args()

    # If it's a git repo, clone and prompt
    if args.input_dir.endswith('.git'):
        got_repo_arg = True
        repo_dir = git_clone(args.input_dir)
        project_template = find_template(repo_dir)
        os.chdir(repo_dir)
    else:
        project_template = args.input_dir

    # Create project from local context and project template.
    context = generate_context()
    generate_files(
        input_dir=project_template,
        context=context
    )

    # Remove repo if Cookiecutter cloned it in the first place.
    # Here the user just wants a project, not a project template.
    if got_repo_arg:
        generated_project = context['project']['repo_name']
        remove_repo(repo_dir, generated_project)

if __name__ == '__main__':
    main()


Define Conllable with an abstract method.

--- pyconll/conllable.py
+++ pyconll/conllable.py
@@ -3,6 +3,8 @@
 is a Conll object, such as a treebank, sentence, or token, and therefore has a
 conll method.
 """
+
+import abc

 class Conllable:
@@ -11,6 +13,9 @@
     CoNLL representation.
     """

+    __metaclass__ = abc.ABCMeta
+
+    @abc.abstractmethod
     def conll(self):
         """
         Provides a conll representation of the component.

<|original_code|>
"""
Holds the Conllable interface, which is a marker interface to show that a class
is a Conll object, such as a treebank, sentence, or token, and therefore has a
conll method.
"""

class Conllable:
    """
    A Conllable mixin to indicate that the component can be converted into a
    CoNLL representation.
    """

    def conll(self):
        """
        Provides a conll representation of the component.

        Returns:
            A string conll representation of the base component.

        Raises:
            NotImplementedError: If the child class does not implement the
                method.
        """
        raise NotImplementedError("No implementation for conll")

<|edits_diff|>
--- pyconll/conllable.py
+++ pyconll/conllable.py
@@ -3,6 +3,8 @@
 is a Conll object, such as a treebank, sentence, or token, and therefore has a
 conll method.
 """
+
+import abc

 class Conllable:
<|current_version|>
"""
Holds the Conllable interface, which is a marker interface to show that a class
is a Conll object, such as a treebank, sentence, or token, and therefore has a
conll method.
"""

import abc

class Conllable:
    """
    A Conllable mixin to indicate that the component can be converted into a
    CoNLL representation.
    """

    def conll(self):
        """
        Provides a conll representation of the component.

        Returns:
            A string conll representation of the base component.

        Raises:
            NotImplementedError: If the child class does not implement the
                method.
        """
        raise NotImplementedError("No implementation for conll")

<|next_version|>
"""
Holds the Conllable interface, which is a marker interface to show that a class
is a Conll object, such as a treebank, sentence, or token, and therefore has a
conll method.
"""

import abc

class Conllable:
    """
    A Conllable mixin to indicate that the component can be converted into a
    CoNLL representation.
    """

    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def conll(self):
        """
        Provides a conll representation of the component.

        Returns:
            A string conll representation of the base component.

        Raises:
            NotImplementedError: If the child class does not implement the
                method.
        """
        raise NotImplementedError("No implementation for conll")


Disable view caching during development

Disable view caching during development

Not ideal, but useful when you change the source code. Otherwise you
would have to run "manage.py invalidate all" for every change.

--- heltour/tournament/decorators.py
+++ heltour/tournament/decorators.py
@@ -1,6 +1,7 @@
 from cacheops.query import cached_as, \
                            cached_view_as as _cacheops_cached_view_as, \
                            install_cacheops
+from heltour import settings

 # TODO: This should be run automatically by django. I have no idea why it isn't.
 install_cacheops()
@@ -13,6 +14,10 @@
     vary_request = cva_kwargs.pop('vary_request', None)

     def wrap(func):
+        if settings.DEBUG:
+            # Disable view caching during development
+            return func
+
         def proxy(request, vary_value, *proxy_args, **proxy_kwargs):
             return func(request, *proxy_args, **proxy_kwargs)

<|original_code|>
from cacheops.query import cached_as, \
                           cached_view_as as _cacheops_cached_view_as, \
                           install_cacheops

# TODO: This should be run automatically by django. I have no idea why it isn't.
install_cacheops()

# Modify the cacheops.cached_view_as decorator to take a "vary_request" lambda
# that allows us to serve different copies of the view to different types of users
# e.g. logged-in vs anonymous users
def cached_view_as(*cva_args, **cva_kwargs):

    vary_request = cva_kwargs.pop('vary_request', None)

    def wrap(func):
        def proxy(request, vary_value, *proxy_args, **proxy_kwargs):
            return func(request, *proxy_args, **proxy_kwargs)

        wrapped_proxy = _cacheops_cached_view_as(*cva_args, **cva_kwargs)(proxy)

        def wrapped(request, *args, **kwargs):
            if vary_request is None:
                return wrapped_proxy(request, None, *args, **kwargs)
            else:
                return wrapped_proxy(request, vary_request(request), *args, **kwargs)

        return wrapped

    return wrap

<|edits_diff|>
--- heltour/tournament/decorators.py
+++ heltour/tournament/decorators.py
@@ -1,6 +1,7 @@
 from cacheops.query import cached_as, \
                            cached_view_as as _cacheops_cached_view_as, \
                            install_cacheops
+from heltour import settings

 # TODO: This should be run automatically by django. I have no idea why it isn't.
 install_cacheops()
<|current_version|>
from cacheops.query import cached_as, \
                           cached_view_as as _cacheops_cached_view_as, \
                           install_cacheops
from heltour import settings

# TODO: This should be run automatically by django. I have no idea why it isn't.
install_cacheops()

# Modify the cacheops.cached_view_as decorator to take a "vary_request" lambda
# that allows us to serve different copies of the view to different types of users
# e.g. logged-in vs anonymous users
def cached_view_as(*cva_args, **cva_kwargs):

    vary_request = cva_kwargs.pop('vary_request', None)

    def wrap(func):
        def proxy(request, vary_value, *proxy_args, **proxy_kwargs):
            return func(request, *proxy_args, **proxy_kwargs)

        wrapped_proxy = _cacheops_cached_view_as(*cva_args, **cva_kwargs)(proxy)

        def wrapped(request, *args, **kwargs):
            if vary_request is None:
                return wrapped_proxy(request, None, *args, **kwargs)
            else:
                return wrapped_proxy(request, vary_request(request), *args, **kwargs)

        return wrapped

    return wrap

<|next_version|>
from cacheops.query import cached_as, \
                           cached_view_as as _cacheops_cached_view_as, \
                           install_cacheops
from heltour import settings

# TODO: This should be run automatically by django. I have no idea why it isn't.
install_cacheops()

# Modify the cacheops.cached_view_as decorator to take a "vary_request" lambda
# that allows us to serve different copies of the view to different types of users
# e.g. logged-in vs anonymous users
def cached_view_as(*cva_args, **cva_kwargs):

    vary_request = cva_kwargs.pop('vary_request', None)

    def wrap(func):
        if settings.DEBUG:
            # Disable view caching during development
            return func

        def proxy(request, vary_value, *proxy_args, **proxy_kwargs):
            return func(request, *proxy_args, **proxy_kwargs)

        wrapped_proxy = _cacheops_cached_view_as(*cva_args, **cva_kwargs)(proxy)

        def wrapped(request, *args, **kwargs):
            if vary_request is None:
                return wrapped_proxy(request, None, *args, **kwargs)
            else:
                return wrapped_proxy(request, vary_request(request), *args, **kwargs)

        return wrapped

    return wrap


Remove old entries (~2 months, keep 100000 entries)

--- lib/__init__.py
+++ lib/__init__.py
@@ -16,9 +16,11 @@

 	def add_humidity(self, value):
 		self.send('humidity', value)
+		self.remove_old('humidity')

 	def add_temperature(self, value):
 		self.send('temperature', value)
+		self.remove_old('temperature')

 	def get_data(self, name, start=0, end=200):
 		return self.redis.lrange(name, start, end)
@@ -28,3 +30,6 @@

 	def get_humidity(self, start=0, end=200):
 		return self.get_data(self.get_key('humidity'), start, end)
+
+	def remove_old(self, name, len=100000):
+		self.redis.ltrim(self.get_key(name), 0, len)

<|original_code|>
import redis
import json
import time

class DHTStorage():
	def __init__(self, key):
		self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
		self.key = key

	def get_key(self, name):
		return "%s:%s" % (self.key, name)

	def send(self, name, data):
		pushData = {'time': time.time(), 'value': data}
		self.redis.lpush(self.get_key(name), json.dumps(pushData))

	def add_humidity(self, value):
		self.send('humidity', value)

	def add_temperature(self, value):
		self.send('temperature', value)

	def get_data(self, name, start=0, end=200):
		return self.redis.lrange(name, start, end)

	def get_temperature(self, start=0, end=200):
		return self.get_data(self.get_key('temperature'), start, end)

	def get_humidity(self, start=0, end=200):
		return self.get_data(self.get_key('humidity'), start, end)

<|edits_diff|>
--- lib/__init__.py
+++ lib/__init__.py
@@ -16,9 +16,11 @@

 	def add_humidity(self, value):
 		self.send('humidity', value)
+		self.remove_old('humidity')

 	def add_temperature(self, value):
 		self.send('temperature', value)
+		self.remove_old('temperature')

 	def get_data(self, name, start=0, end=200):
 		return self.redis.lrange(name, start, end)
<|current_version|>
import redis
import json
import time

class DHTStorage():
	def __init__(self, key):
		self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
		self.key = key

	def get_key(self, name):
		return "%s:%s" % (self.key, name)

	def send(self, name, data):
		pushData = {'time': time.time(), 'value': data}
		self.redis.lpush(self.get_key(name), json.dumps(pushData))

	def add_humidity(self, value):
		self.send('humidity', value)
		self.remove_old('humidity')

	def add_temperature(self, value):
		self.send('temperature', value)
		self.remove_old('temperature')

	def get_data(self, name, start=0, end=200):
		return self.redis.lrange(name, start, end)

	def get_temperature(self, start=0, end=200):
		return self.get_data(self.get_key('temperature'), start, end)

	def get_humidity(self, start=0, end=200):
		return self.get_data(self.get_key('humidity'), start, end)

<|next_version|>
import redis
import json
import time

class DHTStorage():
	def __init__(self, key):
		self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)
		self.key = key

	def get_key(self, name):
		return "%s:%s" % (self.key, name)

	def send(self, name, data):
		pushData = {'time': time.time(), 'value': data}
		self.redis.lpush(self.get_key(name), json.dumps(pushData))

	def add_humidity(self, value):
		self.send('humidity', value)
		self.remove_old('humidity')

	def add_temperature(self, value):
		self.send('temperature', value)
		self.remove_old('temperature')

	def get_data(self, name, start=0, end=200):
		return self.redis.lrange(name, start, end)

	def get_temperature(self, start=0, end=200):
		return self.get_data(self.get_key('temperature'), start, end)

	def get_humidity(self, start=0, end=200):
		return self.get_data(self.get_key('humidity'), start, end)

	def remove_old(self, name, len=100000):
		self.redis.ltrim(self.get_key(name), 0, len)


Add registration to cost tracking

Add registration to cost tracking

--- src/nodeconductor_paas_oracle/apps.py
+++ src/nodeconductor_paas_oracle/apps.py
@@ -8,5 +8,11 @@

     def ready(self):
         from nodeconductor.structure import SupportedServices
+        from nodeconductor.cost_tracking import CostTrackingRegister
+
         from .backend import OracleBackend
         SupportedServices.register_backend(OracleBackend)
+
+        # cost tracking
+        from .cost_tracking import OracleCostTrackingBackend
+        CostTrackingRegister.register(self.label, OracleCostTrackingBackend)

<|original_code|>
from django.apps import AppConfig

class OracleConfig(AppConfig):
    name = 'nodeconductor_paas_oracle'
    verbose_name = 'Oracle'
    service_name = 'Oracle'

    def ready(self):
        from nodeconductor.structure import SupportedServices
        from .backend import OracleBackend
        SupportedServices.register_backend(OracleBackend)

<|edits_diff|>
--- src/nodeconductor_paas_oracle/apps.py
+++ src/nodeconductor_paas_oracle/apps.py
@@ -8,5 +8,7 @@

     def ready(self):
         from nodeconductor.structure import SupportedServices
+        from nodeconductor.cost_tracking import CostTrackingRegister
+
         from .backend import OracleBackend
         SupportedServices.register_backend(OracleBackend)
<|current_version|>
from django.apps import AppConfig

class OracleConfig(AppConfig):
    name = 'nodeconductor_paas_oracle'
    verbose_name = 'Oracle'
    service_name = 'Oracle'

    def ready(self):
        from nodeconductor.structure import SupportedServices
        from nodeconductor.cost_tracking import CostTrackingRegister

        from .backend import OracleBackend
        SupportedServices.register_backend(OracleBackend)

<|next_version|>
from django.apps import AppConfig

class OracleConfig(AppConfig):
    name = 'nodeconductor_paas_oracle'
    verbose_name = 'Oracle'
    service_name = 'Oracle'

    def ready(self):
        from nodeconductor.structure import SupportedServices
        from nodeconductor.cost_tracking import CostTrackingRegister

        from .backend import OracleBackend
        SupportedServices.register_backend(OracleBackend)

        # cost tracking
        from .cost_tracking import OracleCostTrackingBackend
        CostTrackingRegister.register(self.label, OracleCostTrackingBackend)


Make login a utility so it can be re-used elsewhere.

Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>

--- django_autologin/utils.py
+++ django_autologin/utils.py
@@ -1,5 +1,8 @@
 import urllib
 import urlparse
+
+from django.conf import settings
+from django.contrib import auth

 from . import app_settings

@@ -17,3 +20,7 @@
     return urlparse.urlunparse(
         (bits[0], bits[1], bits[2], bits[3], query, bits[5]),
     )
+
+def login(request, user):
+    user.backend = settings.AUTHENTICATION_BACKENDS[0]
+    auth.login(request, user)

<|original_code|>
import urllib
import urlparse

from . import app_settings

def strip_token(url):
    bits = urlparse.urlparse(url)
    original_query = urlparse.parse_qsl(bits.query)

    query = {}
    for k, v in original_query:
        if k != app_settings.KEY:
            query[k] = v

    query = urllib.urlencode(query)

    return urlparse.urlunparse(
        (bits[0], bits[1], bits[2], bits[3], query, bits[5]),
    )

<|edits_diff|>
--- django_autologin/utils.py
+++ django_autologin/utils.py
@@ -1,5 +1,8 @@
 import urllib
 import urlparse
+
+from django.conf import settings
+from django.contrib import auth

 from . import app_settings

<|current_version|>
import urllib
import urlparse

from django.conf import settings
from django.contrib import auth

from . import app_settings

def strip_token(url):
    bits = urlparse.urlparse(url)
    original_query = urlparse.parse_qsl(bits.query)

    query = {}
    for k, v in original_query:
        if k != app_settings.KEY:
            query[k] = v

    query = urllib.urlencode(query)

    return urlparse.urlunparse(
        (bits[0], bits[1], bits[2], bits[3], query, bits[5]),
    )

<|next_version|>
import urllib
import urlparse

from django.conf import settings
from django.contrib import auth

from . import app_settings

def strip_token(url):
    bits = urlparse.urlparse(url)
    original_query = urlparse.parse_qsl(bits.query)

    query = {}
    for k, v in original_query:
        if k != app_settings.KEY:
            query[k] = v

    query = urllib.urlencode(query)

    return urlparse.urlunparse(
        (bits[0], bits[1], bits[2], bits[3], query, bits[5]),
    )

def login(request, user):
    user.backend = settings.AUTHENTICATION_BACKENDS[0]
    auth.login(request, user)