Set invoices to non-draft when done

Set invoices to non-draft when done

--- spiff/subscription/management/commands/process_subscriptions.py
+++ spiff/subscription/management/commands/process_subscriptions.py
@@ -4,6 +4,7 @@
 from spiff.api.plugins import find_api_classes
 from spiff.membership.utils import monthRange
 from spiff.membership.models import Member, RankLineItem
+import stripe

 class Command(BaseCommand):
   help = 'Bills active members for the month'
@@ -23,9 +24,14 @@
           if len(items) > 0 and subscription not in lineItems[subscription.user]['subscriptions']:
             lineItems[subscription.user]['subscriptions'].append(subscription)
             lineItems[subscription.user]['lineItems'] += items
+    invoices = []
     for user, data in lineItems.iteritems():
       invoice = Invoice.bundleLineItems(user, endOfMonth, data['lineItems'])
       if invoice:
         print "Created invoice", invoice
+        invoices.append(invoice)
       for subscription in data['subscriptions']:
         subscription.save()
+    for invoice in invoices:
+      invoice.draft = False
+      invoice.save()

<|original_code|>
from django.core.management import BaseCommand
from spiff.payment.models import Invoice
from spiff.subscription.models import SubscriptionPlan
from spiff.api.plugins import find_api_classes
from spiff.membership.utils import monthRange
from spiff.membership.models import Member, RankLineItem

class Command(BaseCommand):
  help = 'Bills active members for the month'

  def handle(self, *args, **options):
    startOfMonth, endOfMonth = monthRange()
    lineItems = {}
    for planCls in find_api_classes('models', SubscriptionPlan):
      plans = planCls.objects.all()
      for plan in plans:
        for subscription in plan.subscriptions.filter(active=True):
          if subscription.user not in lineItems:
            lineItems[subscription.user] = {'subscriptions': [], 'lineItems': []}

          items = plan.process(subscription)

          if len(items) > 0 and subscription not in lineItems[subscription.user]['subscriptions']:
            lineItems[subscription.user]['subscriptions'].append(subscription)
            lineItems[subscription.user]['lineItems'] += items
    for user, data in lineItems.iteritems():
      invoice = Invoice.bundleLineItems(user, endOfMonth, data['lineItems'])
      if invoice:
        print "Created invoice", invoice
      for subscription in data['subscriptions']:
        subscription.save()

<|edits_diff|>
--- spiff/subscription/management/commands/process_subscriptions.py
+++ spiff/subscription/management/commands/process_subscriptions.py
@@ -4,6 +4,7 @@
 from spiff.api.plugins import find_api_classes
 from spiff.membership.utils import monthRange
 from spiff.membership.models import Member, RankLineItem
+import stripe

 class Command(BaseCommand):
   help = 'Bills active members for the month'
@@ -23,9 +24,11 @@
           if len(items) > 0 and subscription not in lineItems[subscription.user]['subscriptions']:
             lineItems[subscription.user]['subscriptions'].append(subscription)
             lineItems[subscription.user]['lineItems'] += items
+    invoices = []
     for user, data in lineItems.iteritems():
       invoice = Invoice.bundleLineItems(user, endOfMonth, data['lineItems'])
       if invoice:
         print "Created invoice", invoice
+        invoices.append(invoice)
       for subscription in data['subscriptions']:
         subscription.save()
<|current_version|>
from django.core.management import BaseCommand
from spiff.payment.models import Invoice
from spiff.subscription.models import SubscriptionPlan
from spiff.api.plugins import find_api_classes
from spiff.membership.utils import monthRange
from spiff.membership.models import Member, RankLineItem
import stripe

class Command(BaseCommand):
  help = 'Bills active members for the month'

  def handle(self, *args, **options):
    startOfMonth, endOfMonth = monthRange()
    lineItems = {}
    for planCls in find_api_classes('models', SubscriptionPlan):
      plans = planCls.objects.all()
      for plan in plans:
        for subscription in plan.subscriptions.filter(active=True):
          if subscription.user not in lineItems:
            lineItems[subscription.user] = {'subscriptions': [], 'lineItems': []}

          items = plan.process(subscription)

          if len(items) > 0 and subscription not in lineItems[subscription.user]['subscriptions']:
            lineItems[subscription.user]['subscriptions'].append(subscription)
            lineItems[subscription.user]['lineItems'] += items
    invoices = []
    for user, data in lineItems.iteritems():
      invoice = Invoice.bundleLineItems(user, endOfMonth, data['lineItems'])
      if invoice:
        print "Created invoice", invoice
        invoices.append(invoice)
      for subscription in data['subscriptions']:
        subscription.save()

<|next_version|>
from django.core.management import BaseCommand
from spiff.payment.models import Invoice
from spiff.subscription.models import SubscriptionPlan
from spiff.api.plugins import find_api_classes
from spiff.membership.utils import monthRange
from spiff.membership.models import Member, RankLineItem
import stripe

class Command(BaseCommand):
  help = 'Bills active members for the month'

  def handle(self, *args, **options):
    startOfMonth, endOfMonth = monthRange()
    lineItems = {}
    for planCls in find_api_classes('models', SubscriptionPlan):
      plans = planCls.objects.all()
      for plan in plans:
        for subscription in plan.subscriptions.filter(active=True):
          if subscription.user not in lineItems:
            lineItems[subscription.user] = {'subscriptions': [], 'lineItems': []}

          items = plan.process(subscription)

          if len(items) > 0 and subscription not in lineItems[subscription.user]['subscriptions']:
            lineItems[subscription.user]['subscriptions'].append(subscription)
            lineItems[subscription.user]['lineItems'] += items
    invoices = []
    for user, data in lineItems.iteritems():
      invoice = Invoice.bundleLineItems(user, endOfMonth, data['lineItems'])
      if invoice:
        print "Created invoice", invoice
        invoices.append(invoice)
      for subscription in data['subscriptions']:
        subscription.save()
    for invoice in invoices:
      invoice.draft = False
      invoice.save()


Add long description to package.

Add long description to package.

--- setup.py
+++ setup.py
@@ -6,10 +6,17 @@
 from setuptools import setup

+def get_long_description():
+    with open('README.md') as readme_file:
+        return readme_file.read()
+
+
 setup(
     name='jsonapi-requests',
     version='0.6.1.dev0',
     description='Python client implementation for json api. http://jsonapi.org/',
+    long_description=get_long_description(),
+    long_description_content_type='text/markdown',
     author='Social WiFi',
     author_email='it@socialwifi.com',
     url='https://github.com/socialwifi/jsonapi-requests',

<|original_code|>
try:
    from pip._internal.req import parse_requirements
except ImportError:
    from pip.req import parse_requirements
from setuptools import find_packages
from setuptools import setup

setup(
    name='jsonapi-requests',
    version='0.6.1.dev0',
    description='Python client implementation for json api. http://jsonapi.org/',
    author='Social WiFi',
    author_email='it@socialwifi.com',
    url='https://github.com/socialwifi/jsonapi-requests',
    packages=find_packages(exclude=['tests']),
    install_requires=[str(ir.req) for ir in parse_requirements('base_requirements.txt', session=False)],
    setup_requires=['pytest-runner'],
    tests_require=['pytest', 'flask'],
    extras_require={
        'flask': ['flask']
    },
    license='BSD',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ]
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -4,6 +4,11 @@
     from pip.req import parse_requirements
 from setuptools import find_packages
 from setuptools import setup
+
+
+def get_long_description():
+    with open('README.md') as readme_file:
+        return readme_file.read()

 setup(
<|current_version|>
try:
    from pip._internal.req import parse_requirements
except ImportError:
    from pip.req import parse_requirements
from setuptools import find_packages
from setuptools import setup

def get_long_description():
    with open('README.md') as readme_file:
        return readme_file.read()

setup(
    name='jsonapi-requests',
    version='0.6.1.dev0',
    description='Python client implementation for json api. http://jsonapi.org/',
    author='Social WiFi',
    author_email='it@socialwifi.com',
    url='https://github.com/socialwifi/jsonapi-requests',
    packages=find_packages(exclude=['tests']),
    install_requires=[str(ir.req) for ir in parse_requirements('base_requirements.txt', session=False)],
    setup_requires=['pytest-runner'],
    tests_require=['pytest', 'flask'],
    extras_require={
        'flask': ['flask']
    },
    license='BSD',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ]
)

<|next_version|>
try:
    from pip._internal.req import parse_requirements
except ImportError:
    from pip.req import parse_requirements
from setuptools import find_packages
from setuptools import setup

def get_long_description():
    with open('README.md') as readme_file:
        return readme_file.read()

setup(
    name='jsonapi-requests',
    version='0.6.1.dev0',
    description='Python client implementation for json api. http://jsonapi.org/',
    long_description=get_long_description(),
    long_description_content_type='text/markdown',
    author='Social WiFi',
    author_email='it@socialwifi.com',
    url='https://github.com/socialwifi/jsonapi-requests',
    packages=find_packages(exclude=['tests']),
    install_requires=[str(ir.req) for ir in parse_requirements('base_requirements.txt', session=False)],
    setup_requires=['pytest-runner'],
    tests_require=['pytest', 'flask'],
    extras_require={
        'flask': ['flask']
    },
    license='BSD',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ]
)


Test routine for contour plotting

Test routine for contour plotting

--- tests/plots.py
+++ tests/plots.py
@@ -2,9 +2,11 @@
 from pyquante2 import basisset,rhf,h2
 from pyquante2.graphics.vtk import vtk_orbital
 from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs
+from pyquante.graphics.contourplot import test_contour

 def lineplot_orbs(): return test_plot_orbs()
 def lineplot_bfs(): return test_plot_bfs()
+def contour_orb(): return test_contour(True)

 def plot_h2():
     bfs = basisset(h2,'sto3g')

<|original_code|>
import numpy as np
from pyquante2 import basisset,rhf,h2
from pyquante2.graphics.vtk import vtk_orbital
from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs

def lineplot_orbs(): return test_plot_orbs()
def lineplot_bfs(): return test_plot_bfs()

def plot_h2():
    bfs = basisset(h2,'sto3g')
    solver = rhf(h2,bfs)
    ens = solver.converge()

    # Note: these orbitals are not coming out symmetric. Why not??
    print solver
    print solver.orbs
    vtk_orbital(h2,solver.orbs,bfs)

def plot_orbs():
    bfs = basisset(h2,'sto3g')
    orbs = np.array([[1.0,1.0],
                     [1.0,-1.0]],'d')

    vtk_orbital(h2,orbs,bfs)
    return

if __name__ == '__main__':
    plot_h2()

<|edits_diff|>
--- tests/plots.py
+++ tests/plots.py
@@ -2,6 +2,7 @@
 from pyquante2 import basisset,rhf,h2
 from pyquante2.graphics.vtk import vtk_orbital
 from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs
+from pyquante.graphics.contourplot import test_contour

 def lineplot_orbs(): return test_plot_orbs()
 def lineplot_bfs(): return test_plot_bfs()
<|current_version|>
import numpy as np
from pyquante2 import basisset,rhf,h2
from pyquante2.graphics.vtk import vtk_orbital
from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs
from pyquante.graphics.contourplot import test_contour

def lineplot_orbs(): return test_plot_orbs()
def lineplot_bfs(): return test_plot_bfs()

def plot_h2():
    bfs = basisset(h2,'sto3g')
    solver = rhf(h2,bfs)
    ens = solver.converge()

    # Note: these orbitals are not coming out symmetric. Why not??
    print solver
    print solver.orbs
    vtk_orbital(h2,solver.orbs,bfs)

def plot_orbs():
    bfs = basisset(h2,'sto3g')
    orbs = np.array([[1.0,1.0],
                     [1.0,-1.0]],'d')

    vtk_orbital(h2,orbs,bfs)
    return

if __name__ == '__main__':
    plot_h2()

<|next_version|>
import numpy as np
from pyquante2 import basisset,rhf,h2
from pyquante2.graphics.vtk import vtk_orbital
from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs
from pyquante.graphics.contourplot import test_contour

def lineplot_orbs(): return test_plot_orbs()
def lineplot_bfs(): return test_plot_bfs()
def contour_orb(): return test_contour(True)

def plot_h2():
    bfs = basisset(h2,'sto3g')
    solver = rhf(h2,bfs)
    ens = solver.converge()

    # Note: these orbitals are not coming out symmetric. Why not??
    print solver
    print solver.orbs
    vtk_orbital(h2,solver.orbs,bfs)

def plot_orbs():
    bfs = basisset(h2,'sto3g')
    orbs = np.array([[1.0,1.0],
                     [1.0,-1.0]],'d')

    vtk_orbital(h2,orbs,bfs)
    return

if __name__ == '__main__':
    plot_h2()


Add pause during looping retry

Add pause during looping retry

--- net/utils.py
+++ net/utils.py
@@ -1,6 +1,10 @@
+import time
+
+
 def looping_retry(func, *args):
     while True:
         try:
             return func(*args)
         except Exception:
+            time.sleep(0.5)
             pass

<|original_code|>
def looping_retry(func, *args):
    while True:
        try:
            return func(*args)
        except Exception:
            pass

<|edits_diff|>
--- net/utils.py
+++ net/utils.py
@@ -1,3 +1,6 @@
+import time
+
+
 def looping_retry(func, *args):
     while True:
         try:
<|current_version|>
import time

def looping_retry(func, *args):
    while True:
        try:
            return func(*args)
        except Exception:
            pass

<|next_version|>
import time

def looping_retry(func, *args):
    while True:
        try:
            return func(*args)
        except Exception:
            time.sleep(0.5)
            pass


Write last shutdown time when we shutdown

--- run.py
+++ run.py
@@ -5,6 +5,7 @@
 import subprocess

 from muzicast.const import BASEDIR, WEB_PORT
+from muzicast.config import GlobalConfig
 from muzicast.web import app

 print 'Running', os.getpid(), os.getppid()
@@ -23,6 +24,9 @@
     def shutdown(self, signum, frame):
         self.streamer.terminate()
         self.scanner.terminate()
+        config = GlobalConfig()
+        config['last_shutdown_time'] = int(time.time())
+        config.save()
         sys.exit(0)

 if __name__ == '__main__':

<|original_code|>
import os
import time
import sys
import signal
import subprocess

from muzicast.const import BASEDIR, WEB_PORT
from muzicast.web import app

print 'Running', os.getpid(), os.getppid()

class Runner(object):
    def run(self):
        self.streamer = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'streamer.py')])
        self.scanner = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'collection/__init__.py')])
        print 'Started streamer PID %d'%self.streamer.pid
        print 'Started scanner PID %d'%self.scanner.pid
        signal.signal(signal.SIGINT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)
        app.run('0.0.0.0', WEB_PORT, debug=True, use_reloader=False)
        #app.run('0.0.0.0', WEB_PORT, debug=False, use_reloader=False)

    def shutdown(self, signum, frame):
        self.streamer.terminate()
        self.scanner.terminate()
        sys.exit(0)

if __name__ == '__main__':
    r = Runner()
    r.run()

<|edits_diff|>
--- run.py
+++ run.py
@@ -5,6 +5,7 @@
 import subprocess

 from muzicast.const import BASEDIR, WEB_PORT
+from muzicast.config import GlobalConfig
 from muzicast.web import app

 print 'Running', os.getpid(), os.getppid()
<|current_version|>
import os
import time
import sys
import signal
import subprocess

from muzicast.const import BASEDIR, WEB_PORT
from muzicast.config import GlobalConfig
from muzicast.web import app

print 'Running', os.getpid(), os.getppid()

class Runner(object):
    def run(self):
        self.streamer = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'streamer.py')])
        self.scanner = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'collection/__init__.py')])
        print 'Started streamer PID %d'%self.streamer.pid
        print 'Started scanner PID %d'%self.scanner.pid
        signal.signal(signal.SIGINT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)
        app.run('0.0.0.0', WEB_PORT, debug=True, use_reloader=False)
        #app.run('0.0.0.0', WEB_PORT, debug=False, use_reloader=False)

    def shutdown(self, signum, frame):
        self.streamer.terminate()
        self.scanner.terminate()
        sys.exit(0)

if __name__ == '__main__':
    r = Runner()
    r.run()

<|next_version|>
import os
import time
import sys
import signal
import subprocess

from muzicast.const import BASEDIR, WEB_PORT
from muzicast.config import GlobalConfig
from muzicast.web import app

print 'Running', os.getpid(), os.getppid()

class Runner(object):
    def run(self):
        self.streamer = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'streamer.py')])
        self.scanner = subprocess.Popen([sys.executable, os.path.join(BASEDIR, 'collection/__init__.py')])
        print 'Started streamer PID %d'%self.streamer.pid
        print 'Started scanner PID %d'%self.scanner.pid
        signal.signal(signal.SIGINT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)
        app.run('0.0.0.0', WEB_PORT, debug=True, use_reloader=False)
        #app.run('0.0.0.0', WEB_PORT, debug=False, use_reloader=False)

    def shutdown(self, signum, frame):
        self.streamer.terminate()
        self.scanner.terminate()
        config = GlobalConfig()
        config['last_shutdown_time'] = int(time.time())
        config.save()
        sys.exit(0)

if __name__ == '__main__':
    r = Runner()
    r.run()


Add login required to new and edit post views

--- app/views/post_view.py
+++ app/views/post_view.py
@@ -1,5 +1,6 @@
 from flask import render_template, redirect, url_for
 from flask_classy import FlaskView, route
+from flask_user import login_required
 from ..models import PostModel
 from ..forms import PostForm

@@ -12,6 +13,7 @@
         post = post.get(entity_id)
         return render_template("post/post.html", post=post)

+    @login_required
     @route("/new/", methods=["GET", "POST"])
     def new(self):
         form = PostForm()
@@ -22,6 +24,7 @@
         return render_template("post/post_form.html", form=form,
                                url="Post:new")

+    @login_required
     @route("/edit/<entity_id>", methods=["GET", "POST"])
     def edit(self, entity_id):
         post = PostModel()

<|original_code|>
from flask import render_template, redirect, url_for
from flask_classy import FlaskView, route
from ..models import PostModel
from ..forms import PostForm

class Post(FlaskView):
    """ Here will handle post creations, delete and update."""

    def get(self, entity_id):
        post = PostModel()
        post = post.get(entity_id)
        return render_template("post/post.html", post=post)

    @route("/new/", methods=["GET", "POST"])
    def new(self):
        form = PostForm()
        if form.validate_on_submit():
            post = PostModel(**form.data)
            post.put()
            return redirect(url_for("Post:get", entity_id=post.id))
        return render_template("post/post_form.html", form=form,
                               url="Post:new")

    @route("/edit/<entity_id>", methods=["GET", "POST"])
    def edit(self, entity_id):
        post = PostModel()
        entity = post.get(entity_id)
        form = PostForm(**entity)
        if form.validate_on_submit():
            post.update(entity_id, form.data)
            return redirect(url_for("Post:get", entity_id=entity_id))
        return render_template("post/post_form.html", form=form,
                               url="Post:edit", entity_id=entity_id)

<|edits_diff|>
--- app/views/post_view.py
+++ app/views/post_view.py
@@ -1,5 +1,6 @@
 from flask import render_template, redirect, url_for
 from flask_classy import FlaskView, route
+from flask_user import login_required
 from ..models import PostModel
 from ..forms import PostForm

@@ -12,6 +13,7 @@
         post = post.get(entity_id)
         return render_template("post/post.html", post=post)

+    @login_required
     @route("/new/", methods=["GET", "POST"])
     def new(self):
         form = PostForm()
<|current_version|>
from flask import render_template, redirect, url_for
from flask_classy import FlaskView, route
from flask_user import login_required
from ..models import PostModel
from ..forms import PostForm

class Post(FlaskView):
    """ Here will handle post creations, delete and update."""

    def get(self, entity_id):
        post = PostModel()
        post = post.get(entity_id)
        return render_template("post/post.html", post=post)

    @login_required
    @route("/new/", methods=["GET", "POST"])
    def new(self):
        form = PostForm()
        if form.validate_on_submit():
            post = PostModel(**form.data)
            post.put()
            return redirect(url_for("Post:get", entity_id=post.id))
        return render_template("post/post_form.html", form=form,
                               url="Post:new")

    @route("/edit/<entity_id>", methods=["GET", "POST"])
    def edit(self, entity_id):
        post = PostModel()
        entity = post.get(entity_id)
        form = PostForm(**entity)
        if form.validate_on_submit():
            post.update(entity_id, form.data)
            return redirect(url_for("Post:get", entity_id=entity_id))
        return render_template("post/post_form.html", form=form,
                               url="Post:edit", entity_id=entity_id)

<|next_version|>
from flask import render_template, redirect, url_for
from flask_classy import FlaskView, route
from flask_user import login_required
from ..models import PostModel
from ..forms import PostForm

class Post(FlaskView):
    """ Here will handle post creations, delete and update."""

    def get(self, entity_id):
        post = PostModel()
        post = post.get(entity_id)
        return render_template("post/post.html", post=post)

    @login_required
    @route("/new/", methods=["GET", "POST"])
    def new(self):
        form = PostForm()
        if form.validate_on_submit():
            post = PostModel(**form.data)
            post.put()
            return redirect(url_for("Post:get", entity_id=post.id))
        return render_template("post/post_form.html", form=form,
                               url="Post:new")

    @login_required
    @route("/edit/<entity_id>", methods=["GET", "POST"])
    def edit(self, entity_id):
        post = PostModel()
        entity = post.get(entity_id)
        form = PostForm(**entity)
        if form.validate_on_submit():
            post.update(entity_id, form.data)
            return redirect(url_for("Post:get", entity_id=entity_id))
        return render_template("post/post_form.html", form=form,
                               url="Post:edit", entity_id=entity_id)


Add Path to Vulk package

Add Path to Vulk package

--- vulk/__init__.py
+++ vulk/__init__.py
@@ -2,4 +2,10 @@

 Cross-plateform 3D engine
 """
+from os import path as p
+
 __version__ = "0.2.0"
+
+PATH_VULK = p.dirname(p.abspath(__file__))
+PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
+PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')

<|original_code|>
"""Vulk 3D engine

Cross-plateform 3D engine
"""
__version__ = "0.2.0"

<|edits_diff|>
--- vulk/__init__.py
+++ vulk/__init__.py
@@ -2,4 +2,6 @@

 Cross-plateform 3D engine
 """
+from os import path as p
+
 __version__ = "0.2.0"
<|current_version|>
"""Vulk 3D engine

Cross-plateform 3D engine
"""
from os import path as p

__version__ = "0.2.0"

<|next_version|>
"""Vulk 3D engine

Cross-plateform 3D engine
"""
from os import path as p

__version__ = "0.2.0"

PATH_VULK = p.dirname(p.abspath(__file__))
PATH_VULK_ASSET = p.join(PATH_VULK, 'asset')
PATH_VULK_SHADER = p.join(PATH_VULK_ASSET, 'shader')


Make sure ssh config directory exists

Make sure ssh config directory exists

--- kokki/cookbooks/ssh/libraries/resources.py
+++ kokki/cookbooks/ssh/libraries/resources.py
@@ -22,6 +22,9 @@
             if not self.user:
                 raise Fail("[%s] Either path or user is required" % self)
             self.path = os.path.join(ssh_path_for_user(self.user), "known_hosts")
+        Directory(os.path.dirname(self.path),
+            owner = self.user,
+            mode = 0700)

 class SSHAuthorizedKey(Resource):
     provider = "*ssh.SSHAuthorizedKeyProvider"
@@ -39,3 +42,6 @@
             if not self.user:
                 raise Fail("[%s] Either path or user is required" % self)
             self.path = os.path.join(ssh_path_for_user(self.user), "authorized_keys")
+        Directory(os.path.dirname(self.path),
+            owner = self.user,
+            mode = 0700)

<|original_code|>

__all__ = ["SSHKnownHost", "SSHAuthorizedKey"]

import os.path
from kokki import *

class SSHKnownHost(Resource):
    provider = "*ssh.SSHKnownHostProvider"

    action = ForcedListArgument(default="include")
    host = ResourceArgument(default=lambda obj:obj.name)
    keytype = ResourceArgument()
    key = ResourceArgument()
    hashed = BooleanArgument(default=True)
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "known_hosts")

class SSHAuthorizedKey(Resource):
    provider = "*ssh.SSHAuthorizedKeyProvider"

    action = ForcedListArgument(default="include")
    keytype = ResourceArgument()
    key = ResourceArgument()
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "authorized_keys")

<|edits_diff|>
--- kokki/cookbooks/ssh/libraries/resources.py
+++ kokki/cookbooks/ssh/libraries/resources.py
@@ -22,6 +22,9 @@
             if not self.user:
                 raise Fail("[%s] Either path or user is required" % self)
             self.path = os.path.join(ssh_path_for_user(self.user), "known_hosts")
+        Directory(os.path.dirname(self.path),
+            owner = self.user,
+            mode = 0700)

 class SSHAuthorizedKey(Resource):
     provider = "*ssh.SSHAuthorizedKeyProvider"
<|current_version|>

__all__ = ["SSHKnownHost", "SSHAuthorizedKey"]

import os.path
from kokki import *

class SSHKnownHost(Resource):
    provider = "*ssh.SSHKnownHostProvider"

    action = ForcedListArgument(default="include")
    host = ResourceArgument(default=lambda obj:obj.name)
    keytype = ResourceArgument()
    key = ResourceArgument()
    hashed = BooleanArgument(default=True)
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "known_hosts")
        Directory(os.path.dirname(self.path),
            owner = self.user,
            mode = 0700)

class SSHAuthorizedKey(Resource):
    provider = "*ssh.SSHAuthorizedKeyProvider"

    action = ForcedListArgument(default="include")
    keytype = ResourceArgument()
    key = ResourceArgument()
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "authorized_keys")

<|next_version|>

__all__ = ["SSHKnownHost", "SSHAuthorizedKey"]

import os.path
from kokki import *

class SSHKnownHost(Resource):
    provider = "*ssh.SSHKnownHostProvider"

    action = ForcedListArgument(default="include")
    host = ResourceArgument(default=lambda obj:obj.name)
    keytype = ResourceArgument()
    key = ResourceArgument()
    hashed = BooleanArgument(default=True)
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "known_hosts")
        Directory(os.path.dirname(self.path),
            owner = self.user,
            mode = 0700)

class SSHAuthorizedKey(Resource):
    provider = "*ssh.SSHAuthorizedKeyProvider"

    action = ForcedListArgument(default="include")
    keytype = ResourceArgument()
    key = ResourceArgument()
    user = ResourceArgument()
    path = ResourceArgument()

    actions = Resource.actions + ["include", "exclude"]

    def validate(self):
        if not self.path:
            if not self.user:
                raise Fail("[%s] Either path or user is required" % self)
            self.path = os.path.join(ssh_path_for_user(self.user), "authorized_keys")
        Directory(os.path.dirname(self.path),
            owner = self.user,
            mode = 0700)


Add basic breadth first return

Add basic breadth first return

--- tree.py
+++ tree.py
@@ -8,8 +8,14 @@
     """
     return 1 / (math.floor(x) + 1 - (x % 1))

+
 def get_nth(n):
     """
     takes a natural number n and returns the nth element of the Calkin Wilf tree
     following a breadth first traversal
     """
+    node = 1/1
+    for i in range(1, n+1):
+        node = succ_fcn(node)
+    return node
+

<|original_code|>
import math

def succ_fcn(x):
    """
    takes an element of the Calkin Wilf tree and returns the next element
    following a breadth first traversal
    """
    return 1 / (math.floor(x) + 1 - (x % 1))

def get_nth(n):
    """
    takes a natural number n and returns the nth element of the Calkin Wilf tree
    following a breadth first traversal
    """

<|edits_diff|>
--- tree.py
+++ tree.py
@@ -8,6 +8,7 @@
     """
     return 1 / (math.floor(x) + 1 - (x % 1))

+
 def get_nth(n):
     """
     takes a natural number n and returns the nth element of the Calkin Wilf tree
<|current_version|>
import math

def succ_fcn(x):
    """
    takes an element of the Calkin Wilf tree and returns the next element
    following a breadth first traversal
    """
    return 1 / (math.floor(x) + 1 - (x % 1))

def get_nth(n):
    """
    takes a natural number n and returns the nth element of the Calkin Wilf tree
    following a breadth first traversal
    """

<|next_version|>
import math

def succ_fcn(x):
    """
    takes an element of the Calkin Wilf tree and returns the next element
    following a breadth first traversal
    """
    return 1 / (math.floor(x) + 1 - (x % 1))

def get_nth(n):
    """
    takes a natural number n and returns the nth element of the Calkin Wilf tree
    following a breadth first traversal
    """
    node = 1/1
    for i in range(1, n+1):
        node = succ_fcn(node)
    return node


Add class comment and a custom color for the decorator

--- pygments/styles/igor.py
+++ pygments/styles/igor.py
@@ -3,11 +3,15 @@
      Number, Operator, Generic

 class IgorStyle(Style):
+    """
+    Pygments version of the official colors for Igor Pro procedures.
+    """
     default_style = ""
     styles = {
         Comment:                'italic #FF0000',
         Keyword:                '#0000FF',
         Name.Function:          '#C34E00',
+        Name.Decorator:         '#CC00A3',
         Name.Class:             '#007575',
         String:                 '#009C00'
     }

<|original_code|>
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Generic

class IgorStyle(Style):
    default_style = ""
    styles = {
        Comment:                'italic #FF0000',
        Keyword:                '#0000FF',
        Name.Function:          '#C34E00',
        Name.Class:             '#007575',
        String:                 '#009C00'
    }

<|edits_diff|>
--- pygments/styles/igor.py
+++ pygments/styles/igor.py
@@ -3,6 +3,9 @@
      Number, Operator, Generic

 class IgorStyle(Style):
+    """
+    Pygments version of the official colors for Igor Pro procedures.
+    """
     default_style = ""
     styles = {
         Comment:                'italic #FF0000',
<|current_version|>
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Generic

class IgorStyle(Style):
    """
    Pygments version of the official colors for Igor Pro procedures.
    """
    default_style = ""
    styles = {
        Comment:                'italic #FF0000',
        Keyword:                '#0000FF',
        Name.Function:          '#C34E00',
        Name.Class:             '#007575',
        String:                 '#009C00'
    }

<|next_version|>
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, \
     Number, Operator, Generic

class IgorStyle(Style):
    """
    Pygments version of the official colors for Igor Pro procedures.
    """
    default_style = ""
    styles = {
        Comment:                'italic #FF0000',
        Keyword:                '#0000FF',
        Name.Function:          '#C34E00',
        Name.Decorator:         '#CC00A3',
        Name.Class:             '#007575',
        String:                 '#009C00'
    }


Repair CGC file header after loading

Repair CGC file header after loading

--- cle/backends/cgc.py
+++ cle/backends/cgc.py
@@ -2,6 +2,7 @@
 from ..loader import Loader

 ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
+CGC_HEADER = "7f43 4743 0101 0143 014d 6572 696e 6f00".replace(" ","").decode('hex')

 class CGC(ELF):
     def __init__(self, path, *args, **kwargs):
@@ -10,6 +11,7 @@
         f.write(ELF_HEADER)
         f.close()
         super(CGC, self).__init__(self.elf_path, *args, **kwargs)
+        self.memory.write_bytes(self.get_min_addr(), CGC_HEADER) # repair CGC header
         self.binary = self.elf_path
         self.os = 'cgc'
         self.execstack = True # the stack is always executable in CGC

<|original_code|>
from .elf import ELF
from ..loader import Loader

ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')

class CGC(ELF):
    def __init__(self, path, *args, **kwargs):
        self.elf_path = Loader._make_tmp_copy(path)
        f = open(self.elf_path, 'r+b')
        f.write(ELF_HEADER)
        f.close()
        super(CGC, self).__init__(self.elf_path, *args, **kwargs)
        self.binary = self.elf_path
        self.os = 'cgc'
        self.execstack = True # the stack is always executable in CGC

    supported_filetypes = ['cgc']

<|edits_diff|>
--- cle/backends/cgc.py
+++ cle/backends/cgc.py
@@ -2,6 +2,7 @@
 from ..loader import Loader

 ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
+CGC_HEADER = "7f43 4743 0101 0143 014d 6572 696e 6f00".replace(" ","").decode('hex')

 class CGC(ELF):
     def __init__(self, path, *args, **kwargs):
<|current_version|>
from .elf import ELF
from ..loader import Loader

ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
CGC_HEADER = "7f43 4743 0101 0143 014d 6572 696e 6f00".replace(" ","").decode('hex')

class CGC(ELF):
    def __init__(self, path, *args, **kwargs):
        self.elf_path = Loader._make_tmp_copy(path)
        f = open(self.elf_path, 'r+b')
        f.write(ELF_HEADER)
        f.close()
        super(CGC, self).__init__(self.elf_path, *args, **kwargs)
        self.binary = self.elf_path
        self.os = 'cgc'
        self.execstack = True # the stack is always executable in CGC

    supported_filetypes = ['cgc']

<|next_version|>
from .elf import ELF
from ..loader import Loader

ELF_HEADER = "7f45 4c46 0101 0100 0000 0000 0000 0000".replace(" ","").decode('hex')
CGC_HEADER = "7f43 4743 0101 0143 014d 6572 696e 6f00".replace(" ","").decode('hex')

class CGC(ELF):
    def __init__(self, path, *args, **kwargs):
        self.elf_path = Loader._make_tmp_copy(path)
        f = open(self.elf_path, 'r+b')
        f.write(ELF_HEADER)
        f.close()
        super(CGC, self).__init__(self.elf_path, *args, **kwargs)
        self.memory.write_bytes(self.get_min_addr(), CGC_HEADER) # repair CGC header
        self.binary = self.elf_path
        self.os = 'cgc'
        self.execstack = True # the stack is always executable in CGC

    supported_filetypes = ['cgc']


Convert output values from int to binary for neural network

--- tests/iris_test.py
+++ tests/iris_test.py
@@ -2,6 +2,8 @@

 from sklearn import datasets
 from random import shuffle
+import numpy as np
+from neuralnet import NeuralNet

 # This example loads the IRIS dataset and classifies
 # using our neural network implementation.
@@ -19,6 +21,11 @@
     # The int conversion is needed in python 3, I think (for odd number of indexes)
     train_idx = idx[:int(len(idx)/2)]
     test_idx = idx[int(len(X)/2):]
+    # Initialize zero matrix for outputs in binary form
+    Y_bin = np.zeros((len(Y),3),dtype=np.int)
+    # Convert output from int to binary representation for neural network
+    for i in range(len(Y)):
+        Y_bin[i][Y[i]] = 1

 if __name__=='__main__':
     main()

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

from sklearn import datasets
from random import shuffle

# This example loads the IRIS dataset and classifies
# using our neural network implementation.
# The results are visualized in a 2D-plot.

def main():
    iris = datasets.load_iris()
    X = iris.data
    Y = iris.target
    # Randomize (shuffle) the indexes
    # Shuffle randomizes idx in place
    idx = range(len(X))
    shuffle(idx)
    # Split the shuffled indexes into half, to training and test
    # The int conversion is needed in python 3, I think (for odd number of indexes)
    train_idx = idx[:int(len(idx)/2)]
    test_idx = idx[int(len(X)/2):]

if __name__=='__main__':
    main()

<|edits_diff|>
--- tests/iris_test.py
+++ tests/iris_test.py
@@ -2,6 +2,8 @@

 from sklearn import datasets
 from random import shuffle
+import numpy as np
+from neuralnet import NeuralNet

 # This example loads the IRIS dataset and classifies
 # using our neural network implementation.
<|current_version|>
#!/usr/bin/env python

from sklearn import datasets
from random import shuffle
import numpy as np
from neuralnet import NeuralNet

# This example loads the IRIS dataset and classifies
# using our neural network implementation.
# The results are visualized in a 2D-plot.

def main():
    iris = datasets.load_iris()
    X = iris.data
    Y = iris.target
    # Randomize (shuffle) the indexes
    # Shuffle randomizes idx in place
    idx = range(len(X))
    shuffle(idx)
    # Split the shuffled indexes into half, to training and test
    # The int conversion is needed in python 3, I think (for odd number of indexes)
    train_idx = idx[:int(len(idx)/2)]
    test_idx = idx[int(len(X)/2):]

if __name__=='__main__':
    main()

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

from sklearn import datasets
from random import shuffle
import numpy as np
from neuralnet import NeuralNet

# This example loads the IRIS dataset and classifies
# using our neural network implementation.
# The results are visualized in a 2D-plot.

def main():
    iris = datasets.load_iris()
    X = iris.data
    Y = iris.target
    # Randomize (shuffle) the indexes
    # Shuffle randomizes idx in place
    idx = range(len(X))
    shuffle(idx)
    # Split the shuffled indexes into half, to training and test
    # The int conversion is needed in python 3, I think (for odd number of indexes)
    train_idx = idx[:int(len(idx)/2)]
    test_idx = idx[int(len(X)/2):]
    # Initialize zero matrix for outputs in binary form
    Y_bin = np.zeros((len(Y),3),dtype=np.int)
    # Convert output from int to binary representation for neural network
    for i in range(len(Y)):
        Y_bin[i][Y[i]] = 1

if __name__=='__main__':
    main()


Add sleep calls for AWS loops

Add sleep calls for AWS loops

--- aws/awslib.py
+++ aws/awslib.py
@@ -1,4 +1,5 @@
 import boto3
+import time

 def await_volume(client, volumeId, waitingState, finishedState):
     while True:
@@ -6,6 +7,7 @@
         state = volumes['Volumes'][0]['State']
         if state != waitingState:
             break
+        time.sleep(1)

     if state != finishedState:
         print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes)
@@ -19,6 +21,7 @@
             break
         if state == finishedState:
             break
+        time.sleep(1)

     if state != finishedState:
         print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances)

<|original_code|>
import boto3

def await_volume(client, volumeId, waitingState, finishedState):
    while True:
        volumes = client.describe_volumes(VolumeIds=[volumeId])
        state = volumes['Volumes'][0]['State']
        if state != waitingState:
            break

    if state != finishedState:
        print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes)
        sys.exit(1)

def await_instance(client, instanceId, waitingState, finishedState):
    while True:
        instances = client.describe_instances(InstanceIds=[instanceId])
        state = instances['Reservations'][0]['Instances'][0]['State']['Name']
        if waitingState and state != waitingState:
            break
        if state == finishedState:
            break

    if state != finishedState:
        print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances)
        sys.exit(1)

<|edits_diff|>
--- aws/awslib.py
+++ aws/awslib.py
@@ -1,4 +1,5 @@
 import boto3
+import time

 def await_volume(client, volumeId, waitingState, finishedState):
     while True:
@@ -6,6 +7,7 @@
         state = volumes['Volumes'][0]['State']
         if state != waitingState:
             break
+        time.sleep(1)

     if state != finishedState:
         print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes)
<|current_version|>
import boto3
import time

def await_volume(client, volumeId, waitingState, finishedState):
    while True:
        volumes = client.describe_volumes(VolumeIds=[volumeId])
        state = volumes['Volumes'][0]['State']
        if state != waitingState:
            break
        time.sleep(1)

    if state != finishedState:
        print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes)
        sys.exit(1)

def await_instance(client, instanceId, waitingState, finishedState):
    while True:
        instances = client.describe_instances(InstanceIds=[instanceId])
        state = instances['Reservations'][0]['Instances'][0]['State']['Name']
        if waitingState and state != waitingState:
            break
        if state == finishedState:
            break

    if state != finishedState:
        print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances)
        sys.exit(1)

<|next_version|>
import boto3
import time

def await_volume(client, volumeId, waitingState, finishedState):
    while True:
        volumes = client.describe_volumes(VolumeIds=[volumeId])
        state = volumes['Volumes'][0]['State']
        if state != waitingState:
            break
        time.sleep(1)

    if state != finishedState:
        print 'Unexpected volume state (expected {}): {}'.format(finishedState, volumes)
        sys.exit(1)

def await_instance(client, instanceId, waitingState, finishedState):
    while True:
        instances = client.describe_instances(InstanceIds=[instanceId])
        state = instances['Reservations'][0]['Instances'][0]['State']['Name']
        if waitingState and state != waitingState:
            break
        if state == finishedState:
            break
        time.sleep(1)

    if state != finishedState:
        print 'Unexpected instance state (expected {}): {}'.format(finishedState, instances)
        sys.exit(1)


[marv] Support webapi extension via entry points

--- code/marv/marv_webapi/__init__.py
+++ code/marv/marv_webapi/__init__.py
@@ -4,6 +4,8 @@
 # SPDX-License-Identifier: AGPL-3.0-only

 from __future__ import absolute_import, division, print_function
+
+from pkg_resources import iter_entry_points

 from .auth import auth
 from .comment import comment
@@ -31,3 +33,8 @@

 from marv_robotics.webapi import robotics
 webapi.add_endpoint(robotics)
+
+
+for ep in iter_entry_points(group='marv_webapi'):
+    endpoint = ep.load()
+    webapi.add_endpoint(endpoint)

<|original_code|>
# -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import absolute_import, division, print_function

from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection import collection, meta
from .tooling import api_group as marv_api_group

@marv_api_group()
def webapi(app):
    pass

# Groups and endpoints are all the same for now
webapi.add_endpoint(auth)
webapi.add_endpoint(comment)
webapi.add_endpoint(dataset)
webapi.add_endpoint(delete)
webapi.add_endpoint(collection)
webapi.add_endpoint(meta)
webapi.add_endpoint(tag)

from marv_robotics.webapi import robotics
webapi.add_endpoint(robotics)

<|edits_diff|>
--- code/marv/marv_webapi/__init__.py
+++ code/marv/marv_webapi/__init__.py
@@ -4,6 +4,8 @@
 # SPDX-License-Identifier: AGPL-3.0-only

 from __future__ import absolute_import, division, print_function
+
+from pkg_resources import iter_entry_points

 from .auth import auth
 from .comment import comment
<|current_version|>
# -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import absolute_import, division, print_function

from pkg_resources import iter_entry_points

from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection import collection, meta
from .tooling import api_group as marv_api_group

@marv_api_group()
def webapi(app):
    pass

# Groups and endpoints are all the same for now
webapi.add_endpoint(auth)
webapi.add_endpoint(comment)
webapi.add_endpoint(dataset)
webapi.add_endpoint(delete)
webapi.add_endpoint(collection)
webapi.add_endpoint(meta)
webapi.add_endpoint(tag)

from marv_robotics.webapi import robotics
webapi.add_endpoint(robotics)

<|next_version|>
# -*- coding: utf-8 -*-
#
# Copyright 2016 - 2018  Ternaris.
# SPDX-License-Identifier: AGPL-3.0-only

from __future__ import absolute_import, division, print_function

from pkg_resources import iter_entry_points

from .auth import auth
from .comment import comment
from .dataset import dataset
from .delete import delete
from .tag import tag
from .collection import collection, meta
from .tooling import api_group as marv_api_group

@marv_api_group()
def webapi(app):
    pass

# Groups and endpoints are all the same for now
webapi.add_endpoint(auth)
webapi.add_endpoint(comment)
webapi.add_endpoint(dataset)
webapi.add_endpoint(delete)
webapi.add_endpoint(collection)
webapi.add_endpoint(meta)
webapi.add_endpoint(tag)

from marv_robotics.webapi import robotics
webapi.add_endpoint(robotics)

for ep in iter_entry_points(group='marv_webapi'):
    endpoint = ep.load()
    webapi.add_endpoint(endpoint)


Print final surface elevations to stdout.

--- main.py
+++ main.py
@@ -1,4 +1,6 @@
 #! /usr/bin/env python
+import sys
+
 import numpy as np

@@ -39,6 +41,9 @@
     if args.plot:
         plot_elevation(avulsion)

+    z = avulsion.get_value('land_surface__elevation')
+    np.savetxt(sys.stdout, z)
+
     avulsion.finalize()

<|original_code|>
#! /usr/bin/env python
import numpy as np

def plot_elevation(avulsion):
    import matplotlib.pyplot as plt

    z = avulsion.get_value('land_surface__elevation')

    plt.imshow(z, origin='lower', cmap='terrain')
    plt.colorbar().ax.set_label('Elevation (m)')
    plt.show()

def main():
    import argparse
    from avulsion_bmi import BmiRiverModule

    parser = argparse.ArgumentParser('Run the avulsion model')
    parser.add_argument('file', help='YAML-formatted parameters file')
    parser.add_argument('--days', type=int, default=0,
                        help='Run model for DAYS')
    parser.add_argument('--years', type=int, default=0,
                        help='Run model for YEARS')
    parser.add_argument('--plot', action='store_true',
                        help='Plot final elevations')

    args = parser.parse_args()

    np.random.seed(1945)

    avulsion = BmiRiverModule()
    avulsion.initialize(args.file)

    n_steps = int((args.days + args.years * 365.) / avulsion.get_time_step())
    for _ in xrange(n_steps):
        avulsion.update()

    if args.plot:
        plot_elevation(avulsion)

    avulsion.finalize()

if __name__ == '__main__':
    main()

<|edits_diff|>
--- main.py
+++ main.py
@@ -1,4 +1,6 @@
 #! /usr/bin/env python
+import sys
+
 import numpy as np

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

import numpy as np

def plot_elevation(avulsion):
    import matplotlib.pyplot as plt

    z = avulsion.get_value('land_surface__elevation')

    plt.imshow(z, origin='lower', cmap='terrain')
    plt.colorbar().ax.set_label('Elevation (m)')
    plt.show()

def main():
    import argparse
    from avulsion_bmi import BmiRiverModule

    parser = argparse.ArgumentParser('Run the avulsion model')
    parser.add_argument('file', help='YAML-formatted parameters file')
    parser.add_argument('--days', type=int, default=0,
                        help='Run model for DAYS')
    parser.add_argument('--years', type=int, default=0,
                        help='Run model for YEARS')
    parser.add_argument('--plot', action='store_true',
                        help='Plot final elevations')

    args = parser.parse_args()

    np.random.seed(1945)

    avulsion = BmiRiverModule()
    avulsion.initialize(args.file)

    n_steps = int((args.days + args.years * 365.) / avulsion.get_time_step())
    for _ in xrange(n_steps):
        avulsion.update()

    if args.plot:
        plot_elevation(avulsion)

    avulsion.finalize()

if __name__ == '__main__':
    main()

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

import numpy as np

def plot_elevation(avulsion):
    import matplotlib.pyplot as plt

    z = avulsion.get_value('land_surface__elevation')

    plt.imshow(z, origin='lower', cmap='terrain')
    plt.colorbar().ax.set_label('Elevation (m)')
    plt.show()

def main():
    import argparse
    from avulsion_bmi import BmiRiverModule

    parser = argparse.ArgumentParser('Run the avulsion model')
    parser.add_argument('file', help='YAML-formatted parameters file')
    parser.add_argument('--days', type=int, default=0,
                        help='Run model for DAYS')
    parser.add_argument('--years', type=int, default=0,
                        help='Run model for YEARS')
    parser.add_argument('--plot', action='store_true',
                        help='Plot final elevations')

    args = parser.parse_args()

    np.random.seed(1945)

    avulsion = BmiRiverModule()
    avulsion.initialize(args.file)

    n_steps = int((args.days + args.years * 365.) / avulsion.get_time_step())
    for _ in xrange(n_steps):
        avulsion.update()

    if args.plot:
        plot_elevation(avulsion)

    z = avulsion.get_value('land_surface__elevation')
    np.savetxt(sys.stdout, z)

    avulsion.finalize()

if __name__ == '__main__':
    main()


Fix issue where game could be in wrong cwd

--- play.py
+++ play.py
@@ -1,8 +1,11 @@
 #!/usr/bin/python3
+import os
 import readline
 import random
 import shelve
 import sys
+
+os.chdir(os.path.dirname(os.path.abspath(__file__)))

 from src import parser
 from src import locations

<|original_code|>
#!/usr/bin/python3
import readline
import random
import shelve
import sys

from src import parser
from src import locations
from src import classes

player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
    try:
        command = parser.parseCommand(input('> '))
        if command is not None:
            hasNoun = True
            action = command[0]
            if len(command) >= 2:
                noun = command[1]
            else:
                hasNoun = False
                noun = None
            if previousNoun != '' and noun == 'it':
                noun = previousNoun
            try:
                commandResult = getattr(player, action)(action, noun,
                                                        hasNoun)
            except AttributeError:
                print('You can\'t do that here.')
            if noun is not None:
                previousNoun = noun
            else:
                previousNoun = ''
            turns += 1
    except KeyboardInterrupt:
        player.die()

<|edits_diff|>
--- play.py
+++ play.py
@@ -1,4 +1,5 @@
 #!/usr/bin/python3
+import os
 import readline
 import random
 import shelve
<|current_version|>
#!/usr/bin/python3
import os
import readline
import random
import shelve
import sys

from src import parser
from src import locations
from src import classes

player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
    try:
        command = parser.parseCommand(input('> '))
        if command is not None:
            hasNoun = True
            action = command[0]
            if len(command) >= 2:
                noun = command[1]
            else:
                hasNoun = False
                noun = None
            if previousNoun != '' and noun == 'it':
                noun = previousNoun
            try:
                commandResult = getattr(player, action)(action, noun,
                                                        hasNoun)
            except AttributeError:
                print('You can\'t do that here.')
            if noun is not None:
                previousNoun = noun
            else:
                previousNoun = ''
            turns += 1
    except KeyboardInterrupt:
        player.die()

<|next_version|>
#!/usr/bin/python3
import os
import readline
import random
import shelve
import sys

os.chdir(os.path.dirname(os.path.abspath(__file__)))

from src import parser
from src import locations
from src import classes

player = classes.Player(locations, locations.start)
previousNoun = ''
turns = 0
while True:
    try:
        command = parser.parseCommand(input('> '))
        if command is not None:
            hasNoun = True
            action = command[0]
            if len(command) >= 2:
                noun = command[1]
            else:
                hasNoun = False
                noun = None
            if previousNoun != '' and noun == 'it':
                noun = previousNoun
            try:
                commandResult = getattr(player, action)(action, noun,
                                                        hasNoun)
            except AttributeError:
                print('You can\'t do that here.')
            if noun is not None:
                previousNoun = noun
            else:
                previousNoun = ''
            turns += 1
    except KeyboardInterrupt:
        player.die()


Remove some Python environment variables from user subprocess environment.

--- shell.py
+++ shell.py
@@ -1,9 +1,14 @@
 import sys, os, subprocess
+
+remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")

 def make_environment(env=None):
     if env is None:
         env = os.environ
     env = env.copy()
+    for var in remove_vars:
+        if var in env:
+            del env[var]
     env["PYTHONUNBUFFERED"] = "1"
     env["PYTHONIOENCODING"] = "UTF-8"
     return env

<|original_code|>
import sys, os, subprocess

def make_environment(env=None):
    if env is None:
        env = os.environ
    env = env.copy()
    env["PYTHONUNBUFFERED"] = "1"
    env["PYTHONIOENCODING"] = "UTF-8"
    return env

def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
    if sys.platform == "win32":
        args = cmdline
    else:
        args = [os.environ.get("SHELL", "/bin/sh")]

    process = subprocess.Popen(args,
        stdin = subprocess.PIPE if sys.platform != "win32" else None,
        stdout = subprocess.PIPE if pipe_output else None,
        stderr = subprocess.STDOUT if pipe_output else None,
        bufsize = 1,
        close_fds = (sys.platform != "win32"),
        shell = (sys.platform == "win32"),
        env = make_environment(env),
        **kwargs)

    if sys.platform != "win32":
        process.stdin.write(cmdline)
        process.stdin.close()

    return process

def kill_shell_process(process, force=False):
    if sys.platform != "win32":
        signal = "-KILL" if force else "-TERM"
        rc = subprocess.call(["pkill", signal, "-P", str(process.pid)])
        if rc == 0:
            return

    if force:
        process.kill()
    else:
        process.terminate()

<|edits_diff|>
--- shell.py
+++ shell.py
@@ -1,4 +1,6 @@
 import sys, os, subprocess
+
+remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")

 def make_environment(env=None):
     if env is None:
<|current_version|>
import sys, os, subprocess

remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")

def make_environment(env=None):
    if env is None:
        env = os.environ
    env = env.copy()
    env["PYTHONUNBUFFERED"] = "1"
    env["PYTHONIOENCODING"] = "UTF-8"
    return env

def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
    if sys.platform == "win32":
        args = cmdline
    else:
        args = [os.environ.get("SHELL", "/bin/sh")]

    process = subprocess.Popen(args,
        stdin = subprocess.PIPE if sys.platform != "win32" else None,
        stdout = subprocess.PIPE if pipe_output else None,
        stderr = subprocess.STDOUT if pipe_output else None,
        bufsize = 1,
        close_fds = (sys.platform != "win32"),
        shell = (sys.platform == "win32"),
        env = make_environment(env),
        **kwargs)

    if sys.platform != "win32":
        process.stdin.write(cmdline)
        process.stdin.close()

    return process

def kill_shell_process(process, force=False):
    if sys.platform != "win32":
        signal = "-KILL" if force else "-TERM"
        rc = subprocess.call(["pkill", signal, "-P", str(process.pid)])
        if rc == 0:
            return

    if force:
        process.kill()
    else:
        process.terminate()

<|next_version|>
import sys, os, subprocess

remove_vars = ("PYTHONHOME", "PYTHONPATH", "VERSIONER_PYTHON_PREFER_32_BIT")

def make_environment(env=None):
    if env is None:
        env = os.environ
    env = env.copy()
    for var in remove_vars:
        if var in env:
            del env[var]
    env["PYTHONUNBUFFERED"] = "1"
    env["PYTHONIOENCODING"] = "UTF-8"
    return env

def run_shell_command(cmdline, pipe_output=True, env=None, **kwargs):
    if sys.platform == "win32":
        args = cmdline
    else:
        args = [os.environ.get("SHELL", "/bin/sh")]

    process = subprocess.Popen(args,
        stdin = subprocess.PIPE if sys.platform != "win32" else None,
        stdout = subprocess.PIPE if pipe_output else None,
        stderr = subprocess.STDOUT if pipe_output else None,
        bufsize = 1,
        close_fds = (sys.platform != "win32"),
        shell = (sys.platform == "win32"),
        env = make_environment(env),
        **kwargs)

    if sys.platform != "win32":
        process.stdin.write(cmdline)
        process.stdin.close()

    return process

def kill_shell_process(process, force=False):
    if sys.platform != "win32":
        signal = "-KILL" if force else "-TERM"
        rc = subprocess.call(["pkill", signal, "-P", str(process.pid)])
        if rc == 0:
            return

    if force:
        process.kill()
    else:
        process.terminate()


Fix bug of not stopping algorithm in time.

--- board.py
+++ board.py
@@ -29,8 +29,10 @@
         for y in range(self.rows):
             if y == self.rows - 1: # Reached bottom
                 self.boardMatrix.itemset((y, column), value)
+                break
             elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
                 continue
             else: # Next row is not empty
                 self.boardMatrix.itemset((y, column), value)
+                break
         return True

<|original_code|>
import numpy

"""
Board represents a four in a row game board.

Author: Isaac Arvestad
"""
class Board:
    """
    Initializes the game with a certain number of rows
    and columns.
    """
    def __init__(self, rows, columns):
        self.rows = rows
        self.columns = columns
        self.boardMatrix = numpy.zeros((rows, columns))

    """
    Attempts to add a piece to a certain column. If the column is
    full the move is illegal and false is returned, otherwise true
    is returned.
    """
    def addPiece(self, column, value):
        "Check if column is full."
        if self.boardMatrix.item(0,column) != 0:
            return False

        "Place piece."
        for y in range(self.rows):
            if y == self.rows - 1: # Reached bottom
                self.boardMatrix.itemset((y, column), value)
            elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
                continue
            else: # Next row is not empty
                self.boardMatrix.itemset((y, column), value)
        return True

<|edits_diff|>
--- board.py
+++ board.py
@@ -29,6 +29,7 @@
         for y in range(self.rows):
             if y == self.rows - 1: # Reached bottom
                 self.boardMatrix.itemset((y, column), value)
+                break
             elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
                 continue
             else: # Next row is not empty
<|current_version|>
import numpy

"""
Board represents a four in a row game board.

Author: Isaac Arvestad
"""
class Board:
    """
    Initializes the game with a certain number of rows
    and columns.
    """
    def __init__(self, rows, columns):
        self.rows = rows
        self.columns = columns
        self.boardMatrix = numpy.zeros((rows, columns))

    """
    Attempts to add a piece to a certain column. If the column is
    full the move is illegal and false is returned, otherwise true
    is returned.
    """
    def addPiece(self, column, value):
        "Check if column is full."
        if self.boardMatrix.item(0,column) != 0:
            return False

        "Place piece."
        for y in range(self.rows):
            if y == self.rows - 1: # Reached bottom
                self.boardMatrix.itemset((y, column), value)
                break
            elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
                continue
            else: # Next row is not empty
                self.boardMatrix.itemset((y, column), value)
        return True

<|next_version|>
import numpy

"""
Board represents a four in a row game board.

Author: Isaac Arvestad
"""
class Board:
    """
    Initializes the game with a certain number of rows
    and columns.
    """
    def __init__(self, rows, columns):
        self.rows = rows
        self.columns = columns
        self.boardMatrix = numpy.zeros((rows, columns))

    """
    Attempts to add a piece to a certain column. If the column is
    full the move is illegal and false is returned, otherwise true
    is returned.
    """
    def addPiece(self, column, value):
        "Check if column is full."
        if self.boardMatrix.item(0,column) != 0:
            return False

        "Place piece."
        for y in range(self.rows):
            if y == self.rows - 1: # Reached bottom
                self.boardMatrix.itemset((y, column), value)
                break
            elif self.boardMatrix.item(y + 1, column) == 0: # Next row is also empty
                continue
            else: # Next row is not empty
                self.boardMatrix.itemset((y, column), value)
                break
        return True


Add fields properties to all form Meta classes

--- mozcal/admin/forms.py
+++ mozcal/admin/forms.py
@@ -6,8 +6,10 @@
 class EventForm(ModelForm):
   class Meta:
     model = Event
+    fields = ['title', 'space', 'start', 'end', 'areas', 'description', 'details']

 class SpaceForm(ModelForm):
   class Meta:
     model = Space
+    fields = ['name', 'address', 'address2', 'city', 'country', 'description', 'lat', 'lon']

<|original_code|>
from django.forms import ModelForm

from mozcal.events.models import Event, Space

class EventForm(ModelForm):
  class Meta:
    model = Event

class SpaceForm(ModelForm):
  class Meta:
    model = Space

<|edits_diff|>
--- mozcal/admin/forms.py
+++ mozcal/admin/forms.py
@@ -6,6 +6,7 @@
 class EventForm(ModelForm):
   class Meta:
     model = Event
+    fields = ['title', 'space', 'start', 'end', 'areas', 'description', 'details']

 class SpaceForm(ModelForm):
<|current_version|>
from django.forms import ModelForm

from mozcal.events.models import Event, Space

class EventForm(ModelForm):
  class Meta:
    model = Event
    fields = ['title', 'space', 'start', 'end', 'areas', 'description', 'details']

class SpaceForm(ModelForm):
  class Meta:
    model = Space

<|next_version|>
from django.forms import ModelForm

from mozcal.events.models import Event, Space

class EventForm(ModelForm):
  class Meta:
    model = Event
    fields = ['title', 'space', 'start', 'end', 'areas', 'description', 'details']

class SpaceForm(ModelForm):
  class Meta:
    model = Space
    fields = ['name', 'address', 'address2', 'city', 'country', 'description', 'lat', 'lon']


Add missing host field to Apple TV

Add missing host field to Apple TV

--- netdisco/discoverables/apple_tv.py
+++ netdisco/discoverables/apple_tv.py
@@ -1,4 +1,5 @@
 """Discover Apple TV media players."""
+import ipaddress
 from . import MDNSDiscoverable

@@ -13,6 +14,7 @@
         """Returns most important info from mDNS entries."""
         props = entry.properties
         info = {
+            'host': str(ipaddress.ip_address(entry.address)),
             'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
             'hsgid': props.get(b'hG').decode('utf-8')
             }

<|original_code|>
"""Discover Apple TV media players."""
from . import MDNSDiscoverable

# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
    """Add support for Apple TV devices."""

    def __init__(self, nd):
        super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')

    def info_from_entry(self, entry):
        """Returns most important info from mDNS entries."""
        props = entry.properties
        info = {
            'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
            'hsgid': props.get(b'hG').decode('utf-8')
            }
        return info

    def get_info(self):
        """Get details from Apple TV instances."""
        return [self.info_from_entry(entry) for entry in self.get_entries()]

<|edits_diff|>
--- netdisco/discoverables/apple_tv.py
+++ netdisco/discoverables/apple_tv.py
@@ -1,4 +1,5 @@
 """Discover Apple TV media players."""
+import ipaddress
 from . import MDNSDiscoverable

<|current_version|>
"""Discover Apple TV media players."""
import ipaddress
from . import MDNSDiscoverable

# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
    """Add support for Apple TV devices."""

    def __init__(self, nd):
        super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')

    def info_from_entry(self, entry):
        """Returns most important info from mDNS entries."""
        props = entry.properties
        info = {
            'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
            'hsgid': props.get(b'hG').decode('utf-8')
            }
        return info

    def get_info(self):
        """Get details from Apple TV instances."""
        return [self.info_from_entry(entry) for entry in self.get_entries()]

<|next_version|>
"""Discover Apple TV media players."""
import ipaddress
from . import MDNSDiscoverable

# pylint: disable=too-few-public-methods
class Discoverable(MDNSDiscoverable):
    """Add support for Apple TV devices."""

    def __init__(self, nd):
        super(Discoverable, self).__init__(nd, '_appletv-v2._tcp.local.')

    def info_from_entry(self, entry):
        """Returns most important info from mDNS entries."""
        props = entry.properties
        info = {
            'host': str(ipaddress.ip_address(entry.address)),
            'name': props.get(b'Name').decode('utf-8').replace('\xa0', ' '),
            'hsgid': props.get(b'hG').decode('utf-8')
            }
        return info

    def get_info(self):
        """Get details from Apple TV instances."""
        return [self.info_from_entry(entry) for entry in self.get_entries()]


Add long description for package

Add long description for package

--- setup.py
+++ setup.py
@@ -1,4 +1,7 @@
 from setuptools import setup
+
+with open('README.md', 'r', encoding='utf-8') as fh:
+    long_description = fh.read()

 setup(
@@ -6,6 +9,8 @@
     py_modules=['ingreedypy'],
     version='1.3.2',
     description='ingreedy-py parses recipe ingredient lines into a object',
+    long_description=long_description,
+    long_description_content_type='text/markdown',
     author='Scott Cooper',
     author_email='scttcper@gmail.com',
     url='https://github.com/openculinary/ingreedy-py',

<|original_code|>
from setuptools import setup

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,4 +1,7 @@
 from setuptools import setup
+
+with open('README.md', 'r', encoding='utf-8') as fh:
+    long_description = fh.read()

 setup(
<|current_version|>
from setuptools import setup

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

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)

<|next_version|>
from setuptools import setup

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

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.2',
    description='ingreedy-py parses recipe ingredient lines into a object',
    long_description=long_description,
    long_description_content_type='text/markdown',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    extras_require={
        'tests': [
            'pytest',
            'pytest-cov',
        ]
    },
    classifiers=[],
)


Remove excessive parenthesis + add docstrings to module, class, and all public methods

--- dashboard/src/configuration.py
+++ dashboard/src/configuration.py
@@ -1,13 +1,17 @@
+"""Configuration for the Dashboard."""
 from server_configuration import *
 from s3_configuration import *

 class Configuration():
+    """Class representing configuration for the Dashboard."""

     def __init__(self):
+        """Construct the configuration structure."""
         self.stage = ServerConfiguration('STAGE')
         self.prod = ServerConfiguration('PROD')
         self.s3 = S3Configuration()

     def __repr__(self):
+        """Return string representation for the configuration object."""
         return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)

<|original_code|>
from server_configuration import *
from s3_configuration import *

class Configuration():

    def __init__(self):
        self.stage = ServerConfiguration('STAGE')
        self.prod = ServerConfiguration('PROD')
        self.s3 = S3Configuration()

    def __repr__(self):
        return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)

<|edits_diff|>
--- dashboard/src/configuration.py
+++ dashboard/src/configuration.py
@@ -1,10 +1,13 @@
+"""Configuration for the Dashboard."""
 from server_configuration import *
 from s3_configuration import *

 class Configuration():
+    """Class representing configuration for the Dashboard."""

     def __init__(self):
+        """Construct the configuration structure."""
         self.stage = ServerConfiguration('STAGE')
         self.prod = ServerConfiguration('PROD')
         self.s3 = S3Configuration()
<|current_version|>
"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *

class Configuration():
    """Class representing configuration for the Dashboard."""

    def __init__(self):
        """Construct the configuration structure."""
        self.stage = ServerConfiguration('STAGE')
        self.prod = ServerConfiguration('PROD')
        self.s3 = S3Configuration()

    def __repr__(self):
        return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)

<|next_version|>
"""Configuration for the Dashboard."""
from server_configuration import *
from s3_configuration import *

class Configuration():
    """Class representing configuration for the Dashboard."""

    def __init__(self):
        """Construct the configuration structure."""
        self.stage = ServerConfiguration('STAGE')
        self.prod = ServerConfiguration('PROD')
        self.s3 = S3Configuration()

    def __repr__(self):
        """Return string representation for the configuration object."""
        return "Stage: {s}\nProd: {p}\nS3: {d}".format(s=self.stage, p=self.prod, d=self.s3)


Add README to test suite

Add README to test suite

--- sql/tests/__init__.py
+++ sql/tests/__init__.py
@@ -8,6 +8,7 @@
 import sql

 here = os.path.dirname(__file__)
+readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))

 def test_suite():
@@ -26,6 +27,9 @@
     suite = unittest.TestSuite()
     for mod in (sql,):
         suite.addTest(doctest.DocTestSuite(mod))
+    if os.path.isfile(readme):
+        suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
+                tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
     return suite

<|original_code|>
#This file is part of python-sql.  The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest

import sql

here = os.path.dirname(__file__)

def test_suite():
    suite = additional_tests()
    loader = unittest.TestLoader()
    for fn in os.listdir(here):
        if fn.startswith('test') and fn.endswith('.py'):
            modname = 'sql.tests.' + fn[:-3]
            __import__(modname)
            module = sys.modules[modname]
            suite.addTests(loader.loadTestsFromModule(module))
    return suite

def additional_tests():
    suite = unittest.TestSuite()
    for mod in (sql,):
        suite.addTest(doctest.DocTestSuite(mod))
    return suite

def main():
    suite = test_suite()
    runner = unittest.TextTestRunner()
    runner.run(suite)

if __name__ == '__main__':
    sys.path.insert(0, os.path.dirname(os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))))
    main()

<|edits_diff|>
--- sql/tests/__init__.py
+++ sql/tests/__init__.py
@@ -8,6 +8,7 @@
 import sql

 here = os.path.dirname(__file__)
+readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))

 def test_suite():
<|current_version|>
#This file is part of python-sql.  The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest

import sql

here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))

def test_suite():
    suite = additional_tests()
    loader = unittest.TestLoader()
    for fn in os.listdir(here):
        if fn.startswith('test') and fn.endswith('.py'):
            modname = 'sql.tests.' + fn[:-3]
            __import__(modname)
            module = sys.modules[modname]
            suite.addTests(loader.loadTestsFromModule(module))
    return suite

def additional_tests():
    suite = unittest.TestSuite()
    for mod in (sql,):
        suite.addTest(doctest.DocTestSuite(mod))
    return suite

def main():
    suite = test_suite()
    runner = unittest.TextTestRunner()
    runner.run(suite)

if __name__ == '__main__':
    sys.path.insert(0, os.path.dirname(os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))))
    main()

<|next_version|>
#This file is part of python-sql.  The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
import sys
import os
import unittest
import doctest

import sql

here = os.path.dirname(__file__)
readme = os.path.normpath(os.path.join(here, '..', '..', 'README'))

def test_suite():
    suite = additional_tests()
    loader = unittest.TestLoader()
    for fn in os.listdir(here):
        if fn.startswith('test') and fn.endswith('.py'):
            modname = 'sql.tests.' + fn[:-3]
            __import__(modname)
            module = sys.modules[modname]
            suite.addTests(loader.loadTestsFromModule(module))
    return suite

def additional_tests():
    suite = unittest.TestSuite()
    for mod in (sql,):
        suite.addTest(doctest.DocTestSuite(mod))
    if os.path.isfile(readme):
        suite.addTest(doctest.DocFileSuite(readme, module_relative=False,
                tearDown=lambda t: sql.Flavor.set(sql.Flavor())))
    return suite

def main():
    suite = test_suite()
    runner = unittest.TextTestRunner()
    runner.run(suite)

if __name__ == '__main__':
    sys.path.insert(0, os.path.dirname(os.path.dirname(
                os.path.dirname(os.path.abspath(__file__)))))
    main()


Configure logging in client tests, so client logs show up.

--- rest-api/test/client_test/base.py
+++ rest-api/test/client_test/base.py
@@ -4,6 +4,7 @@
 import unittest

 from client.client import Client
+from tools.main_util import configure_logging

 # To run the tests against the test instance instead,
 # set environment variable PMI_DRC_RDR_INSTANCE.
@@ -15,6 +16,7 @@
 class BaseClientTest(unittest.TestCase):
   def setUp(self):
     super(BaseClientTest, self).setUp()
+    configure_logging()
     self.maxDiff = None
     instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
     creds_file = os.environ.get('TESTING_CREDS_FILE')

<|original_code|>
import copy
import json
import os
import unittest

from client.client import Client

# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'

_OFFLINE_BASE_PATH = 'offline'

class BaseClientTest(unittest.TestCase):
  def setUp(self):
    super(BaseClientTest, self).setUp()
    self.maxDiff = None
    instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
    creds_file = os.environ.get('TESTING_CREDS_FILE')
    self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
    self.offline_client = Client(
        base_path=_OFFLINE_BASE_PATH,
        parse_cli=False,
        default_instance=instance,
        creds_file=creds_file)

  def assertJsonEquals(self, obj_a, obj_b):
    obj_b = copy.deepcopy(obj_b)
    for transient_key in ('etag', 'kind', 'meta'):
      if transient_key in obj_b:
        del obj_b[transient_key]
    self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))

def _pretty(obj):
  return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))

<|edits_diff|>
--- rest-api/test/client_test/base.py
+++ rest-api/test/client_test/base.py
@@ -4,6 +4,7 @@
 import unittest

 from client.client import Client
+from tools.main_util import configure_logging

 # To run the tests against the test instance instead,
 # set environment variable PMI_DRC_RDR_INSTANCE.
<|current_version|>
import copy
import json
import os
import unittest

from client.client import Client
from tools.main_util import configure_logging

# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'

_OFFLINE_BASE_PATH = 'offline'

class BaseClientTest(unittest.TestCase):
  def setUp(self):
    super(BaseClientTest, self).setUp()
    self.maxDiff = None
    instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
    creds_file = os.environ.get('TESTING_CREDS_FILE')
    self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
    self.offline_client = Client(
        base_path=_OFFLINE_BASE_PATH,
        parse_cli=False,
        default_instance=instance,
        creds_file=creds_file)

  def assertJsonEquals(self, obj_a, obj_b):
    obj_b = copy.deepcopy(obj_b)
    for transient_key in ('etag', 'kind', 'meta'):
      if transient_key in obj_b:
        del obj_b[transient_key]
    self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))

def _pretty(obj):
  return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))

<|next_version|>
import copy
import json
import os
import unittest

from client.client import Client
from tools.main_util import configure_logging

# To run the tests against the test instance instead,
# set environment variable PMI_DRC_RDR_INSTANCE.
_DEFAULT_INSTANCE = 'http://localhost:8080'

_OFFLINE_BASE_PATH = 'offline'

class BaseClientTest(unittest.TestCase):
  def setUp(self):
    super(BaseClientTest, self).setUp()
    configure_logging()
    self.maxDiff = None
    instance = os.environ.get('PMI_DRC_RDR_INSTANCE') or _DEFAULT_INSTANCE
    creds_file = os.environ.get('TESTING_CREDS_FILE')
    self.client = Client(parse_cli=False, default_instance=instance, creds_file=creds_file)
    self.offline_client = Client(
        base_path=_OFFLINE_BASE_PATH,
        parse_cli=False,
        default_instance=instance,
        creds_file=creds_file)

  def assertJsonEquals(self, obj_a, obj_b):
    obj_b = copy.deepcopy(obj_b)
    for transient_key in ('etag', 'kind', 'meta'):
      if transient_key in obj_b:
        del obj_b[transient_key]
    self.assertMultiLineEqual(_pretty(obj_a), _pretty(obj_b))

def _pretty(obj):
  return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))


Add Channel and the convenience exchange classes

--- rabbitpy/__init__.py
+++ rabbitpy/__init__.py
@@ -25,7 +25,12 @@
 logging.getLogger('rabbitpy').addHandler(NullHandler())

 from rabbitpy.connection import Connection
+from rabbitpy.channel import Channel
 from rabbitpy.exchange import Exchange
+from rabbitpy.exchange import DirectExchange
+from rabbitpy.exchange import FanoutExchange
+from rabbitpy.exchange import HeadersExchange
+from rabbitpy.exchange import TopicExchange
 from rabbitpy.message import Message
 from rabbitpy.amqp_queue import Queue
 from rabbitpy.tx import Tx

<|original_code|>
"""
rabbitpy, a pythonic RabbitMQ client

"""
__version__ = '0.14.0'
version = __version__

DEBUG = False

import logging

try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        """Python 2.6 does not have a NullHandler"""
        def emit(self, record):
            """Emit a record

            :param record record: The record to emit

            """
            pass

logging.getLogger('rabbitpy').addHandler(NullHandler())

from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx

from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange

<|edits_diff|>
--- rabbitpy/__init__.py
+++ rabbitpy/__init__.py
@@ -25,6 +25,7 @@
 logging.getLogger('rabbitpy').addHandler(NullHandler())

 from rabbitpy.connection import Connection
+from rabbitpy.channel import Channel
 from rabbitpy.exchange import Exchange
 from rabbitpy.message import Message
 from rabbitpy.amqp_queue import Queue
<|current_version|>
"""
rabbitpy, a pythonic RabbitMQ client

"""
__version__ = '0.14.0'
version = __version__

DEBUG = False

import logging

try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        """Python 2.6 does not have a NullHandler"""
        def emit(self, record):
            """Emit a record

            :param record record: The record to emit

            """
            pass

logging.getLogger('rabbitpy').addHandler(NullHandler())

from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx

from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange

<|next_version|>
"""
rabbitpy, a pythonic RabbitMQ client

"""
__version__ = '0.14.0'
version = __version__

DEBUG = False

import logging

try:
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        """Python 2.6 does not have a NullHandler"""
        def emit(self, record):
            """Emit a record

            :param record record: The record to emit

            """
            pass

logging.getLogger('rabbitpy').addHandler(NullHandler())

from rabbitpy.connection import Connection
from rabbitpy.channel import Channel
from rabbitpy.exchange import Exchange
from rabbitpy.exchange import DirectExchange
from rabbitpy.exchange import FanoutExchange
from rabbitpy.exchange import HeadersExchange
from rabbitpy.exchange import TopicExchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx

from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple import publish
from rabbitpy.simple import create_queue
from rabbitpy.simple import delete_queue
from rabbitpy.simple import create_direct_exchange
from rabbitpy.simple import create_fanout_exchange
from rabbitpy.simple import create_topic_exchange
from rabbitpy.simple import delete_exchange


Set Mongoengine user for Django 1.5 in tests.

--- tests/test_project/settings.py
+++ tests/test_project/settings.py
@@ -33,11 +33,14 @@
 TEST_RUNNER = 'tastypie_mongoengine.test_runner.MongoEngineTestSuiteRunner'

 INSTALLED_APPS = (
+    'mongoengine.django.mongo_auth',
     'tastypie',
     'tastypie_mongoengine',
     'test_project.test_app',
 )

+AUTH_USER_MODEL = 'mongo_auth.MongoUser'
+
 MONGO_DATABASE_NAME = 'test_project'

 import mongoengine

<|original_code|>
# Django settings for test_project project

DEBUG = True

# We are not really using a relational database, but tests fail without
# defining it because flush command is being run, which expects it
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

# Make this unique, and don't share it with anybody
SECRET_KEY = 'sq=uf!nqw=aibl+y1&5pp=)b7pc=c$4hnh$om*_c48r)^t!ob)'

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

ROOT_URLCONF = 'test_project.urls'

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

SESSION_ENGINE = 'mongoengine.django.sessions'

TEST_RUNNER = 'tastypie_mongoengine.test_runner.MongoEngineTestSuiteRunner'

INSTALLED_APPS = (
    'tastypie',
    'tastypie_mongoengine',
    'test_project.test_app',
)

MONGO_DATABASE_NAME = 'test_project'

import mongoengine
mongoengine.connect(MONGO_DATABASE_NAME)

<|edits_diff|>
--- tests/test_project/settings.py
+++ tests/test_project/settings.py
@@ -33,6 +33,7 @@
 TEST_RUNNER = 'tastypie_mongoengine.test_runner.MongoEngineTestSuiteRunner'

 INSTALLED_APPS = (
+    'mongoengine.django.mongo_auth',
     'tastypie',
     'tastypie_mongoengine',
     'test_project.test_app',
<|current_version|>
# Django settings for test_project project

DEBUG = True

# We are not really using a relational database, but tests fail without
# defining it because flush command is being run, which expects it
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

# Make this unique, and don't share it with anybody
SECRET_KEY = 'sq=uf!nqw=aibl+y1&5pp=)b7pc=c$4hnh$om*_c48r)^t!ob)'

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

ROOT_URLCONF = 'test_project.urls'

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

SESSION_ENGINE = 'mongoengine.django.sessions'

TEST_RUNNER = 'tastypie_mongoengine.test_runner.MongoEngineTestSuiteRunner'

INSTALLED_APPS = (
    'mongoengine.django.mongo_auth',
    'tastypie',
    'tastypie_mongoengine',
    'test_project.test_app',
)

MONGO_DATABASE_NAME = 'test_project'

import mongoengine
mongoengine.connect(MONGO_DATABASE_NAME)

<|next_version|>
# Django settings for test_project project

DEBUG = True

# We are not really using a relational database, but tests fail without
# defining it because flush command is being run, which expects it
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    }
}

# Make this unique, and don't share it with anybody
SECRET_KEY = 'sq=uf!nqw=aibl+y1&5pp=)b7pc=c$4hnh$om*_c48r)^t!ob)'

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

ROOT_URLCONF = 'test_project.urls'

AUTHENTICATION_BACKENDS = (
    'mongoengine.django.auth.MongoEngineBackend',
)

SESSION_ENGINE = 'mongoengine.django.sessions'

TEST_RUNNER = 'tastypie_mongoengine.test_runner.MongoEngineTestSuiteRunner'

INSTALLED_APPS = (
    'mongoengine.django.mongo_auth',
    'tastypie',
    'tastypie_mongoengine',
    'test_project.test_app',
)

AUTH_USER_MODEL = 'mongo_auth.MongoUser'

MONGO_DATABASE_NAME = 'test_project'

import mongoengine
mongoengine.connect(MONGO_DATABASE_NAME)


Add dtype of iteration variable

Dimension: Add dtype of iteration variable

--- devito/dimension.py
+++ devito/dimension.py
@@ -1,5 +1,8 @@
 import cgen
+
+import numpy as np
 from sympy import Symbol
+

 __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']

@@ -39,6 +42,11 @@
         """Variable declaration for C-level kernel headers"""
         return cgen.Value("const int", self.ccode)

+    @property
+    def dtype(self):
+        """The data type of the iteration variable"""
+        return np.int32
+

 # Set of default dimensions for space and time
 x = Dimension('x')

<|original_code|>
import cgen
from sympy import Symbol

__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']

class Dimension(Symbol):
    """Index object that represents a problem dimension and thus
    defines a potential iteration space.

    :param size: Optional, size of the array dimension.
    :param buffered: Optional, boolean flag indicating whether to
                     buffer variables when iterating this dimension.
    """

    def __new__(cls, name, **kwargs):
        newobj = Symbol.__new__(cls, name)
        newobj.size = kwargs.get('size', None)
        newobj.buffered = kwargs.get('buffered', None)
        newobj._count = 0
        return newobj

    def __str__(self):
        return self.name

    def get_varname(self):
        """Generates a new variables name based on an internal counter"""
        name = "%s%d" % (self.name, self._count)
        self._count += 1
        return name

    @property
    def ccode(self):
        """C-level variable name of this dimension"""
        return "%s_size" % self.name if self.size is None else "%d" % self.size

    @property
    def decl(self):
        """Variable declaration for C-level kernel headers"""
        return cgen.Value("const int", self.ccode)

# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')

<|edits_diff|>
--- devito/dimension.py
+++ devito/dimension.py
@@ -1,5 +1,8 @@
 import cgen
+
+import numpy as np
 from sympy import Symbol
+

 __all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']

<|current_version|>
import cgen

import numpy as np
from sympy import Symbol

__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']

class Dimension(Symbol):
    """Index object that represents a problem dimension and thus
    defines a potential iteration space.

    :param size: Optional, size of the array dimension.
    :param buffered: Optional, boolean flag indicating whether to
                     buffer variables when iterating this dimension.
    """

    def __new__(cls, name, **kwargs):
        newobj = Symbol.__new__(cls, name)
        newobj.size = kwargs.get('size', None)
        newobj.buffered = kwargs.get('buffered', None)
        newobj._count = 0
        return newobj

    def __str__(self):
        return self.name

    def get_varname(self):
        """Generates a new variables name based on an internal counter"""
        name = "%s%d" % (self.name, self._count)
        self._count += 1
        return name

    @property
    def ccode(self):
        """C-level variable name of this dimension"""
        return "%s_size" % self.name if self.size is None else "%d" % self.size

    @property
    def decl(self):
        """Variable declaration for C-level kernel headers"""
        return cgen.Value("const int", self.ccode)

# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')

<|next_version|>
import cgen

import numpy as np
from sympy import Symbol

__all__ = ['Dimension', 'x', 'y', 'z', 't', 'p']

class Dimension(Symbol):
    """Index object that represents a problem dimension and thus
    defines a potential iteration space.

    :param size: Optional, size of the array dimension.
    :param buffered: Optional, boolean flag indicating whether to
                     buffer variables when iterating this dimension.
    """

    def __new__(cls, name, **kwargs):
        newobj = Symbol.__new__(cls, name)
        newobj.size = kwargs.get('size', None)
        newobj.buffered = kwargs.get('buffered', None)
        newobj._count = 0
        return newobj

    def __str__(self):
        return self.name

    def get_varname(self):
        """Generates a new variables name based on an internal counter"""
        name = "%s%d" % (self.name, self._count)
        self._count += 1
        return name

    @property
    def ccode(self):
        """C-level variable name of this dimension"""
        return "%s_size" % self.name if self.size is None else "%d" % self.size

    @property
    def decl(self):
        """Variable declaration for C-level kernel headers"""
        return cgen.Value("const int", self.ccode)

    @property
    def dtype(self):
        """The data type of the iteration variable"""
        return np.int32

# Set of default dimensions for space and time
x = Dimension('x')
y = Dimension('y')
z = Dimension('z')
t = Dimension('t')
p = Dimension('p')