Fix Python 3 issue with long()

Fix Python 3 issue with long()

--- fluentcms_googlemaps/views.py
+++ fluentcms_googlemaps/views.py
@@ -1,5 +1,6 @@
 from __future__ import unicode_literals

+import sys
 import json

 from django.core.exceptions import ObjectDoesNotExist
@@ -7,6 +8,9 @@
 from django.views.generic.detail import BaseDetailView

 from .models import Marker
+
+if sys.version_info[0] >= 3:
+    long = int

 class MarkerDetailView(BaseDetailView):

<|original_code|>
from __future__ import unicode_literals

import json

from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponse
from django.views.generic.detail import BaseDetailView

from .models import Marker

class MarkerDetailView(BaseDetailView):
    """
    Simple view for fetching marker details.
    """
    # TODO: support different object types. Perhaps through django-polymorphic?
    model = Marker
    pk_url_kwarg = 'id'

    def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.
        """
        if queryset is None:
            queryset = self.get_queryset()

        # Take a GET parameter instead of URLConf variable.
        try:
            pk = long(self.request.GET[self.pk_url_kwarg])
        except (KeyError, ValueError):
            raise Http404("Invalid Parameters")
        queryset = queryset.filter(pk=pk)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except ObjectDoesNotExist as e:
            raise Http404(e)
        return obj

    def render_to_response(self, context):
        return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8')

    def get_json_data(self, context):
        """
        Generate the JSON data to send back to the client.
        :rtype: dict
        """
        return self.object.to_dict(detailed=True)

<|edits_diff|>
--- fluentcms_googlemaps/views.py
+++ fluentcms_googlemaps/views.py
@@ -1,5 +1,6 @@
 from __future__ import unicode_literals

+import sys
 import json

 from django.core.exceptions import ObjectDoesNotExist
<|current_version|>
from __future__ import unicode_literals

import sys
import json

from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponse
from django.views.generic.detail import BaseDetailView

from .models import Marker

class MarkerDetailView(BaseDetailView):
    """
    Simple view for fetching marker details.
    """
    # TODO: support different object types. Perhaps through django-polymorphic?
    model = Marker
    pk_url_kwarg = 'id'

    def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.
        """
        if queryset is None:
            queryset = self.get_queryset()

        # Take a GET parameter instead of URLConf variable.
        try:
            pk = long(self.request.GET[self.pk_url_kwarg])
        except (KeyError, ValueError):
            raise Http404("Invalid Parameters")
        queryset = queryset.filter(pk=pk)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except ObjectDoesNotExist as e:
            raise Http404(e)
        return obj

    def render_to_response(self, context):
        return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8')

    def get_json_data(self, context):
        """
        Generate the JSON data to send back to the client.
        :rtype: dict
        """
        return self.object.to_dict(detailed=True)

<|next_version|>
from __future__ import unicode_literals

import sys
import json

from django.core.exceptions import ObjectDoesNotExist
from django.http import Http404, HttpResponse
from django.views.generic.detail import BaseDetailView

from .models import Marker

if sys.version_info[0] >= 3:
    long = int

class MarkerDetailView(BaseDetailView):
    """
    Simple view for fetching marker details.
    """
    # TODO: support different object types. Perhaps through django-polymorphic?
    model = Marker
    pk_url_kwarg = 'id'

    def get_object(self, queryset=None):
        """
        Returns the object the view is displaying.
        """
        if queryset is None:
            queryset = self.get_queryset()

        # Take a GET parameter instead of URLConf variable.
        try:
            pk = long(self.request.GET[self.pk_url_kwarg])
        except (KeyError, ValueError):
            raise Http404("Invalid Parameters")
        queryset = queryset.filter(pk=pk)

        try:
            # Get the single item from the filtered queryset
            obj = queryset.get()
        except ObjectDoesNotExist as e:
            raise Http404(e)
        return obj

    def render_to_response(self, context):
        return HttpResponse(json.dumps(self.get_json_data(context)), content_type='application/json; charset=utf-8')

    def get_json_data(self, context):
        """
        Generate the JSON data to send back to the client.
        :rtype: dict
        """
        return self.object.to_dict(detailed=True)


Add a utility for echoing in the IO utils.

--- autoload/splicelib/util/io.py
+++ autoload/splicelib/util/io.py
@@ -1,5 +1,9 @@
 import sys
+import vim

 def error(m):
     sys.stderr.write(str(m) + '\n')
+
+def echomsg(m):
+    vim.command('echomsg "%s"' % m)

<|original_code|>
import sys

def error(m):
    sys.stderr.write(str(m) + '\n')

<|edits_diff|>
--- autoload/splicelib/util/io.py
+++ autoload/splicelib/util/io.py
@@ -1,4 +1,5 @@
 import sys
+import vim

 def error(m):
<|current_version|>
import sys
import vim

def error(m):
    sys.stderr.write(str(m) + '\n')

<|next_version|>
import sys
import vim

def error(m):
    sys.stderr.write(str(m) + '\n')

def echomsg(m):
    vim.command('echomsg "%s"' % m)


Raise exceptions for common errors rather than returning invalid data.

--- cadorsfeed/fetch.py
+++ cadorsfeed/fetch.py
@@ -1,3 +1,4 @@
+from werkzeug.exceptions import NotFound, InternalServerError
 import mechanize
 import re

@@ -16,7 +17,13 @@
     br.select_form(name="pageForm")
     br["txt_ReportDate"] = reportDate
     response2 = br.submit(name="btn_SearchTop")
+    print response2.geturl()
+    if not response2.geturl().startswith("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/rpt.aspx"):
+        raise InternalServerError()
     data = response2.get_data()
+    if re.search("There were no results for the search criteria you entered",
+                 data):
+        raise NotFound()
     data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""",
                            "<!-- viewstate field stripped -->",
                            data)

<|original_code|>
import mechanize
import re

def fetchLatest():
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    latestDate = br["txt_ReportDate"]
    return latestDate

def fetchReport(reportDate):
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    br["txt_ReportDate"] = reportDate
    response2 = br.submit(name="btn_SearchTop")
    data = response2.get_data()
    data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""",
                           "<!-- viewstate field stripped -->",
                           data)
    return data_filtered.decode("utf-8")

<|edits_diff|>
--- cadorsfeed/fetch.py
+++ cadorsfeed/fetch.py
@@ -1,3 +1,4 @@
+from werkzeug.exceptions import NotFound, InternalServerError
 import mechanize
 import re

@@ -16,6 +17,9 @@
     br.select_form(name="pageForm")
     br["txt_ReportDate"] = reportDate
     response2 = br.submit(name="btn_SearchTop")
+    print response2.geturl()
+    if not response2.geturl().startswith("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/rpt.aspx"):
+        raise InternalServerError()
     data = response2.get_data()
     data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""",
                            "<!-- viewstate field stripped -->",
<|current_version|>
from werkzeug.exceptions import NotFound, InternalServerError
import mechanize
import re

def fetchLatest():
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    latestDate = br["txt_ReportDate"]
    return latestDate

def fetchReport(reportDate):
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    br["txt_ReportDate"] = reportDate
    response2 = br.submit(name="btn_SearchTop")
    print response2.geturl()
    if not response2.geturl().startswith("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/rpt.aspx"):
        raise InternalServerError()
    data = response2.get_data()
    data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""",
                           "<!-- viewstate field stripped -->",
                           data)
    return data_filtered.decode("utf-8")

<|next_version|>
from werkzeug.exceptions import NotFound, InternalServerError
import mechanize
import re

def fetchLatest():
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    latestDate = br["txt_ReportDate"]
    return latestDate

def fetchReport(reportDate):
    br = mechanize.Browser()
    br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng")
    br.select_form(name="pageForm")
    br["txt_ReportDate"] = reportDate
    response2 = br.submit(name="btn_SearchTop")
    print response2.geturl()
    if not response2.geturl().startswith("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/rpt.aspx"):
        raise InternalServerError()
    data = response2.get_data()
    if re.search("There were no results for the search criteria you entered",
                 data):
        raise NotFound()
    data_filtered = re.sub("""<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="[A-Za-z0-9/+=]*" />""",
                           "<!-- viewstate field stripped -->",
                           data)
    return data_filtered.decode("utf-8")


Set fake_s3_upload view to be CSRF exempt

--- buckets/test/views.py
+++ buckets/test/views.py
@@ -1,8 +1,10 @@
 from django.core.files.storage import default_storage
+from django.views.decorators.csrf import csrf_exempt
 from django.views.decorators.http import require_POST
 from django.http import HttpResponse

+@csrf_exempt
 @require_POST
 def fake_s3_upload(request):
     key = request.POST.get('key')

<|original_code|>
from django.core.files.storage import default_storage
from django.views.decorators.http import require_POST
from django.http import HttpResponse

@require_POST
def fake_s3_upload(request):
    key = request.POST.get('key')

    file = request.FILES.get('file')
    default_storage.save(key, file.read())

    return HttpResponse('', status=204)

<|edits_diff|>
--- buckets/test/views.py
+++ buckets/test/views.py
@@ -1,4 +1,5 @@
 from django.core.files.storage import default_storage
+from django.views.decorators.csrf import csrf_exempt
 from django.views.decorators.http import require_POST
 from django.http import HttpResponse

<|current_version|>
from django.core.files.storage import default_storage
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse

@require_POST
def fake_s3_upload(request):
    key = request.POST.get('key')

    file = request.FILES.get('file')
    default_storage.save(key, file.read())

    return HttpResponse('', status=204)

<|next_version|>
from django.core.files.storage import default_storage
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse

@csrf_exempt
@require_POST
def fake_s3_upload(request):
    key = request.POST.get('key')

    file = request.FILES.get('file')
    default_storage.save(key, file.read())

    return HttpResponse('', status=204)


Disable Hypothesis health check for PyPy.

--- tests/conftest.py
+++ tests/conftest.py
@@ -1,4 +1,8 @@
+import platform
+
 import pytest
+
+from hypothesis import HealthCheck, settings

 from cattr import Converter

@@ -6,3 +10,7 @@
 @pytest.fixture()
 def converter():
     return Converter()
+
+
+if platform.python_implementation() == 'PyPy':
+    settings.default.suppress_health_check.append(HealthCheck.too_slow)

<|original_code|>
import pytest

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()

<|edits_diff|>
--- tests/conftest.py
+++ tests/conftest.py
@@ -1,4 +1,8 @@
+import platform
+
 import pytest
+
+from hypothesis import HealthCheck, settings

 from cattr import Converter

<|current_version|>
import platform

import pytest

from hypothesis import HealthCheck, settings

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()

<|next_version|>
import platform

import pytest

from hypothesis import HealthCheck, settings

from cattr import Converter

@pytest.fixture()
def converter():
    return Converter()

if platform.python_implementation() == 'PyPy':
    settings.default.suppress_health_check.append(HealthCheck.too_slow)


Set the default URL to point to index.html.

--- vsub/urls.py
+++ vsub/urls.py
@@ -1,5 +1,7 @@
 from django.conf.urls import patterns, include, url
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
+from django.views.generic import TemplateView

 # See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
 admin.autodiscover()
@@ -7,4 +9,8 @@
 urlpatterns = patterns('',
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
     url(r'^admin/', include(admin.site.urls)),
+
+    (r'^/?$', TemplateView.as_view(template_name='index.html')),
 )
+
+urlpatterns += staticfiles_urlpatterns()

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

# See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

<|edits_diff|>
--- vsub/urls.py
+++ vsub/urls.py
@@ -1,5 +1,7 @@
 from django.conf.urls import patterns, include, url
 from django.contrib import admin
+from django.contrib.staticfiles.urls import staticfiles_urlpatterns
+from django.views.generic import TemplateView

 # See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
 admin.autodiscover()
@@ -7,4 +9,6 @@
 urlpatterns = patterns('',
     url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
     url(r'^admin/', include(admin.site.urls)),
+
+    (r'^/?$', TemplateView.as_view(template_name='index.html')),
 )
<|current_version|>
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView

# See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    (r'^/?$', TemplateView.as_view(template_name='index.html')),
)

<|next_version|>
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.generic import TemplateView

# See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#hooking-adminsite-instances-into-your-urlconf
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    url(r'^admin/', include(admin.site.urls)),

    (r'^/?$', TemplateView.as_view(template_name='index.html')),
)

urlpatterns += staticfiles_urlpatterns()


Set CF_STACK environment variable in compile tests

--- tests/common/base.py
+++ tests/common/base.py
@@ -25,5 +25,9 @@
         self.opts.set_download_url(
             'http://localhost:5000/binaries/{STACK}')

+        os.environ["CF_STACK"] = "cflinuxfs2"
+
     def tearDown(self):
         self.dh.cleanup()
+
+        del os.environ["CF_STACK"]

<|original_code|>
import os
from build_pack_utils import BuildPack
from common.integration import DirectoryHelper
from common.integration import OptionsHelper

class BaseCompileApp(object):
    def setUp(self):
        self.dh = DirectoryHelper()
        (self.build_dir,
         self.cache_dir,
         self.temp_dir) = self.dh.create_bp_env(self.app_name)
        self.bp = BuildPack({
            'BUILD_DIR': self.build_dir,
            'CACHE_DIR': self.cache_dir,
            'TMPDIR': self.temp_dir
        }, '.')
        if 'BP_DEBUG' in os.environ.keys():
            self.bp._ctx['BP_DEBUG'] = True
        self.dh.copy_build_pack_to(self.bp.bp_dir)
        self.dh.register_to_delete(self.bp.bp_dir)
        self.opts = OptionsHelper(os.path.join(self.bp.bp_dir,
                                               'defaults',
                                               'options.json'))
        self.opts.set_download_url(
            'http://localhost:5000/binaries/{STACK}')

    def tearDown(self):
        self.dh.cleanup()

<|edits_diff|>
--- tests/common/base.py
+++ tests/common/base.py
@@ -25,5 +25,7 @@
         self.opts.set_download_url(
             'http://localhost:5000/binaries/{STACK}')

+        os.environ["CF_STACK"] = "cflinuxfs2"
+
     def tearDown(self):
         self.dh.cleanup()
<|current_version|>
import os
from build_pack_utils import BuildPack
from common.integration import DirectoryHelper
from common.integration import OptionsHelper

class BaseCompileApp(object):
    def setUp(self):
        self.dh = DirectoryHelper()
        (self.build_dir,
         self.cache_dir,
         self.temp_dir) = self.dh.create_bp_env(self.app_name)
        self.bp = BuildPack({
            'BUILD_DIR': self.build_dir,
            'CACHE_DIR': self.cache_dir,
            'TMPDIR': self.temp_dir
        }, '.')
        if 'BP_DEBUG' in os.environ.keys():
            self.bp._ctx['BP_DEBUG'] = True
        self.dh.copy_build_pack_to(self.bp.bp_dir)
        self.dh.register_to_delete(self.bp.bp_dir)
        self.opts = OptionsHelper(os.path.join(self.bp.bp_dir,
                                               'defaults',
                                               'options.json'))
        self.opts.set_download_url(
            'http://localhost:5000/binaries/{STACK}')

        os.environ["CF_STACK"] = "cflinuxfs2"

    def tearDown(self):
        self.dh.cleanup()

<|next_version|>
import os
from build_pack_utils import BuildPack
from common.integration import DirectoryHelper
from common.integration import OptionsHelper

class BaseCompileApp(object):
    def setUp(self):
        self.dh = DirectoryHelper()
        (self.build_dir,
         self.cache_dir,
         self.temp_dir) = self.dh.create_bp_env(self.app_name)
        self.bp = BuildPack({
            'BUILD_DIR': self.build_dir,
            'CACHE_DIR': self.cache_dir,
            'TMPDIR': self.temp_dir
        }, '.')
        if 'BP_DEBUG' in os.environ.keys():
            self.bp._ctx['BP_DEBUG'] = True
        self.dh.copy_build_pack_to(self.bp.bp_dir)
        self.dh.register_to_delete(self.bp.bp_dir)
        self.opts = OptionsHelper(os.path.join(self.bp.bp_dir,
                                               'defaults',
                                               'options.json'))
        self.opts.set_download_url(
            'http://localhost:5000/binaries/{STACK}')

        os.environ["CF_STACK"] = "cflinuxfs2"

    def tearDown(self):
        self.dh.cleanup()

        del os.environ["CF_STACK"]


Add search fields to stock models

Add search fields to stock models

--- casexml/apps/stock/admin.py
+++ casexml/apps/stock/admin.py
@@ -1,15 +1,19 @@
 from django.contrib import admin
 from .models import *
+

 class StockReportAdmin(admin.ModelAdmin):
     model = StockReport
     list_display = ['date', 'type', 'form_id']
     list_filter = ['date', 'type']
+    search_fields = ['form_id']
+

 class StockTransactionAdmin(admin.ModelAdmin):
     model = StockTransaction
     list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand']
     list_filter = ['report__date', 'section_id', 'type', 'subtype']
+    search_fields = ['case_id', 'product_id']

     def report_date(self, obj):
         return obj.report.date

<|original_code|>
from django.contrib import admin
from .models import *

class StockReportAdmin(admin.ModelAdmin):
    model = StockReport
    list_display = ['date', 'type', 'form_id']
    list_filter = ['date', 'type']

class StockTransactionAdmin(admin.ModelAdmin):
    model = StockTransaction
    list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand']
    list_filter = ['report__date', 'section_id', 'type', 'subtype']

    def report_date(self, obj):
        return obj.report.date
    report_date.admin_order_field = 'report__date'

admin.site.register(StockReport, StockReportAdmin)
admin.site.register(StockTransaction, StockTransactionAdmin)

<|edits_diff|>
--- casexml/apps/stock/admin.py
+++ casexml/apps/stock/admin.py
@@ -1,10 +1,13 @@
 from django.contrib import admin
 from .models import *
+

 class StockReportAdmin(admin.ModelAdmin):
     model = StockReport
     list_display = ['date', 'type', 'form_id']
     list_filter = ['date', 'type']
+    search_fields = ['form_id']
+

 class StockTransactionAdmin(admin.ModelAdmin):
     model = StockTransaction
<|current_version|>
from django.contrib import admin
from .models import *

class StockReportAdmin(admin.ModelAdmin):
    model = StockReport
    list_display = ['date', 'type', 'form_id']
    list_filter = ['date', 'type']
    search_fields = ['form_id']

class StockTransactionAdmin(admin.ModelAdmin):
    model = StockTransaction
    list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand']
    list_filter = ['report__date', 'section_id', 'type', 'subtype']

    def report_date(self, obj):
        return obj.report.date
    report_date.admin_order_field = 'report__date'

admin.site.register(StockReport, StockReportAdmin)
admin.site.register(StockTransaction, StockTransactionAdmin)

<|next_version|>
from django.contrib import admin
from .models import *

class StockReportAdmin(admin.ModelAdmin):
    model = StockReport
    list_display = ['date', 'type', 'form_id']
    list_filter = ['date', 'type']
    search_fields = ['form_id']

class StockTransactionAdmin(admin.ModelAdmin):
    model = StockTransaction
    list_display = ['report_date', 'section_id', 'type', 'subtype', 'case_id', 'product_id', 'quantity', 'stock_on_hand']
    list_filter = ['report__date', 'section_id', 'type', 'subtype']
    search_fields = ['case_id', 'product_id']

    def report_date(self, obj):
        return obj.report.date
    report_date.admin_order_field = 'report__date'

admin.site.register(StockReport, StockReportAdmin)
admin.site.register(StockTransaction, StockTransactionAdmin)


Add crosshair and hover tools to bokeh html output

Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>

--- cw/cw305/util/plot.py
+++ cw/cw305/util/plot.py
@@ -7,6 +7,7 @@
 from bokeh.plotting import figure, show
 from bokeh.palettes import Dark2_5 as palette
 from bokeh.io import output_file
+from bokeh.models import tools

 def save_plot_to_file(traces, num_traces, outfile):
@@ -14,6 +15,8 @@
   colors = itertools.cycle(palette)
   xrange = range(len(traces[0]))
   plot = figure(plot_width=800)
+  plot.add_tools(tools.CrosshairTool())
+  plot.add_tools(tools.HoverTool())
   for i in range(min(len(traces), num_traces)):
     plot.line(xrange, traces[i], line_color=next(colors))
   output_file(outfile)

<|original_code|>
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0

import itertools

from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file

def save_plot_to_file(traces, num_traces, outfile):
  """Save plot figure to file."""
  colors = itertools.cycle(palette)
  xrange = range(len(traces[0]))
  plot = figure(plot_width=800)
  for i in range(min(len(traces), num_traces)):
    plot.line(xrange, traces[i], line_color=next(colors))
  output_file(outfile)
  show(plot)

<|edits_diff|>
--- cw/cw305/util/plot.py
+++ cw/cw305/util/plot.py
@@ -7,6 +7,7 @@
 from bokeh.plotting import figure, show
 from bokeh.palettes import Dark2_5 as palette
 from bokeh.io import output_file
+from bokeh.models import tools

 def save_plot_to_file(traces, num_traces, outfile):
<|current_version|>
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0

import itertools

from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
from bokeh.models import tools

def save_plot_to_file(traces, num_traces, outfile):
  """Save plot figure to file."""
  colors = itertools.cycle(palette)
  xrange = range(len(traces[0]))
  plot = figure(plot_width=800)
  for i in range(min(len(traces), num_traces)):
    plot.line(xrange, traces[i], line_color=next(colors))
  output_file(outfile)
  show(plot)

<|next_version|>
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0

import itertools

from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
from bokeh.models import tools

def save_plot_to_file(traces, num_traces, outfile):
  """Save plot figure to file."""
  colors = itertools.cycle(palette)
  xrange = range(len(traces[0]))
  plot = figure(plot_width=800)
  plot.add_tools(tools.CrosshairTool())
  plot.add_tools(tools.HoverTool())
  for i in range(min(len(traces), num_traces)):
    plot.line(xrange, traces[i], line_color=next(colors))
  output_file(outfile)
  show(plot)


Add a filter for CantIdentifyUrl errors.

--- localtv/management/commands/update_original_data.py
+++ localtv/management/commands/update_original_data.py
@@ -3,6 +3,7 @@
 from django.core.management.base import NoArgsCommand
 from localtv.management import site_too_old
 from localtv import models
+import vidscraper.errors

 class Command(NoArgsCommand):

@@ -15,5 +16,7 @@
             video__status=models.FEED_STATUS_REJECTED):
             try:
                 original.update()
+            except vidscraper.errors.CantIdentifyUrl, e:
+                pass # It is okay if we cannot update a remote video. No need to be noisy.
             except Exception:
                 traceback.print_exc()

<|original_code|>
import traceback

from django.core.management.base import NoArgsCommand
from localtv.management import site_too_old
from localtv import models

class Command(NoArgsCommand):

    args = ''

    def handle_noargs(self, **options):
        if site_too_old():
            return
        for original in models.OriginalVideo.objects.exclude(
            video__status=models.FEED_STATUS_REJECTED):
            try:
                original.update()
            except Exception:
                traceback.print_exc()

<|edits_diff|>
--- localtv/management/commands/update_original_data.py
+++ localtv/management/commands/update_original_data.py
@@ -3,6 +3,7 @@
 from django.core.management.base import NoArgsCommand
 from localtv.management import site_too_old
 from localtv import models
+import vidscraper.errors

 class Command(NoArgsCommand):

<|current_version|>
import traceback

from django.core.management.base import NoArgsCommand
from localtv.management import site_too_old
from localtv import models
import vidscraper.errors

class Command(NoArgsCommand):

    args = ''

    def handle_noargs(self, **options):
        if site_too_old():
            return
        for original in models.OriginalVideo.objects.exclude(
            video__status=models.FEED_STATUS_REJECTED):
            try:
                original.update()
            except Exception:
                traceback.print_exc()

<|next_version|>
import traceback

from django.core.management.base import NoArgsCommand
from localtv.management import site_too_old
from localtv import models
import vidscraper.errors

class Command(NoArgsCommand):

    args = ''

    def handle_noargs(self, **options):
        if site_too_old():
            return
        for original in models.OriginalVideo.objects.exclude(
            video__status=models.FEED_STATUS_REJECTED):
            try:
                original.update()
            except vidscraper.errors.CantIdentifyUrl, e:
                pass # It is okay if we cannot update a remote video. No need to be noisy.
            except Exception:
                traceback.print_exc()


Add workaround for PyPy round() bug with NumPy data types

--- future/builtins/backports/newround.py
+++ future/builtins/backports/newround.py
@@ -2,6 +2,9 @@
 ``python-future``: pure Python implementation of Python 3 round().
 """

+from future.utils import PYPY
+
+
 def newround(number, ndigits=None):
     """
     See Python 3 documentation: uses Banker's Rounding.
@@ -29,6 +32,11 @@
     if ndigits < 0:
         raise NotImplementedError('negative ndigits not supported yet')
     exponent = Decimal('10') ** (-ndigits)
+
+    if PYPY:
+        # Work around issue #24: round() breaks on PyPy with NumPy's types
+        if 'numpy' in repr(type(number)):
+            number = float(number)
     d = Decimal.from_float(number).quantize(exponent,
                                             rounding=ROUND_HALF_EVEN)
     if return_int:

<|original_code|>
"""
``python-future``: pure Python implementation of Python 3 round().
"""

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']

<|edits_diff|>
--- future/builtins/backports/newround.py
+++ future/builtins/backports/newround.py
@@ -2,6 +2,9 @@
 ``python-future``: pure Python implementation of Python 3 round().
 """

+from future.utils import PYPY
+
+
 def newround(number, ndigits=None):
     """
     See Python 3 documentation: uses Banker's Rounding.
<|current_version|>
"""
``python-future``: pure Python implementation of Python 3 round().
"""

from future.utils import PYPY

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']

<|next_version|>
"""
``python-future``: pure Python implementation of Python 3 round().
"""

from future.utils import PYPY

def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    # Use the decimal module for simplicity of implementation (and
    # hopefully correctness).
    from decimal import Decimal, ROUND_HALF_EVEN

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)
    d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    if return_int:
        return int(d)
    else:
        return float(d)

__all__ = ['newround']


Make Ignores try to find '.mnignore'

Make Ignores try to find '.mnignore'

If it doesn't find it, that's okay, and no action is required.

--- morenines/ignores.py
+++ morenines/ignores.py
@@ -2,9 +2,15 @@
 from fnmatch import fnmatchcase
 import click

+from morenines.util import find_file
+
+
 class Ignores(object):
     @classmethod
     def read(cls, path):
+        if not path:
+            path = find_file('.mnignore')
+
         ignores = cls()

         if path:

<|original_code|>
import os
from fnmatch import fnmatchcase
import click

class Ignores(object):
    @classmethod
    def read(cls, path):
        ignores = cls()

        if path:
            with click.open_file(path, 'r') as stream:
                ignores.patterns = [line.strip() for line in stream]

        return ignores

    def __init__(self):
        self.patterns = []

    def match(self, path):
        filename = os.path.basename(path)

        if any(fnmatchcase(filename, pattern) for pattern in self.patterns):
            return True
        else:
            return False

<|edits_diff|>
--- morenines/ignores.py
+++ morenines/ignores.py
@@ -1,6 +1,9 @@
 import os
 from fnmatch import fnmatchcase
 import click
+
+from morenines.util import find_file
+

 class Ignores(object):
     @classmethod
<|current_version|>
import os
from fnmatch import fnmatchcase
import click

from morenines.util import find_file

class Ignores(object):
    @classmethod
    def read(cls, path):
        ignores = cls()

        if path:
            with click.open_file(path, 'r') as stream:
                ignores.patterns = [line.strip() for line in stream]

        return ignores

    def __init__(self):
        self.patterns = []

    def match(self, path):
        filename = os.path.basename(path)

        if any(fnmatchcase(filename, pattern) for pattern in self.patterns):
            return True
        else:
            return False

<|next_version|>
import os
from fnmatch import fnmatchcase
import click

from morenines.util import find_file

class Ignores(object):
    @classmethod
    def read(cls, path):
        if not path:
            path = find_file('.mnignore')

        ignores = cls()

        if path:
            with click.open_file(path, 'r') as stream:
                ignores.patterns = [line.strip() for line in stream]

        return ignores

    def __init__(self):
        self.patterns = []

    def match(self, path):
        filename = os.path.basename(path)

        if any(fnmatchcase(filename, pattern) for pattern in self.patterns):
            return True
        else:
            return False


Make it easier to clean up tests by closing db sessions

Also added a convenience test base class

--- src/newt/db/tests/base.py
+++ src/newt/db/tests/base.py
@@ -1,8 +1,11 @@
 import gc
 import sys
+import unittest
+
 PYPY = hasattr(sys, 'pypy_version_info')

 from .. import pg_connection
+from .._util import closing

 class DBSetup(object):

@@ -24,6 +27,11 @@
             super(DBSetup, self).setUp()

     def drop_db(self):
+        self.base_cursor.execute(
+            """
+            select pg_terminate_backend(pid) from pg_stat_activity
+            where datname = %s
+            """, (self.dbname,))
         self.base_cursor.execute('drop database if exists ' + self.dbname)

     def tearDown(self):
@@ -40,3 +48,6 @@
         self.drop_db()
         self.base_cursor.close()
         self.base_conn.close()
+
+class TestCase(DBSetup, unittest.TestCase):
+    pass

<|original_code|>
import gc
import sys
PYPY = hasattr(sys, 'pypy_version_info')

from .. import pg_connection

class DBSetup(object):

    maxDiff = None

    @property
    def dsn(self):
        return 'postgresql://localhost/' + self.dbname

    def setUp(self, call_super=True):
        self.dbname = self.__class__.__name__.lower() + '_newt_test_database'
        self.base_conn = pg_connection('')
        self.base_conn.autocommit = True
        self.base_cursor = self.base_conn.cursor()
        self.drop_db()
        self.base_cursor.execute('create database ' + self.dbname)
        self.call_super = call_super
        if call_super:
            super(DBSetup, self).setUp()

    def drop_db(self):
        self.base_cursor.execute('drop database if exists ' + self.dbname)

    def tearDown(self):
        if self.call_super:
            super(DBSetup, self).tearDown()

        if PYPY:
            # Make sure there aren't any leaked connections around
            # that would keep us from dropping the DB
            # (https://travis-ci.org/newtdb/db/jobs/195267673)
            # This needs a fix from RelStorage post 2.0.0.
            gc.collect()
            gc.collect()
        self.drop_db()
        self.base_cursor.close()
        self.base_conn.close()

<|edits_diff|>
--- src/newt/db/tests/base.py
+++ src/newt/db/tests/base.py
@@ -1,8 +1,11 @@
 import gc
 import sys
+import unittest
+
 PYPY = hasattr(sys, 'pypy_version_info')

 from .. import pg_connection
+from .._util import closing

 class DBSetup(object):

@@ -24,6 +27,11 @@
             super(DBSetup, self).setUp()

     def drop_db(self):
+        self.base_cursor.execute(
+            """
+            select pg_terminate_backend(pid) from pg_stat_activity
+            where datname = %s
+            """, (self.dbname,))
         self.base_cursor.execute('drop database if exists ' + self.dbname)

     def tearDown(self):
<|current_version|>
import gc
import sys
import unittest

PYPY = hasattr(sys, 'pypy_version_info')

from .. import pg_connection
from .._util import closing

class DBSetup(object):

    maxDiff = None

    @property
    def dsn(self):
        return 'postgresql://localhost/' + self.dbname

    def setUp(self, call_super=True):
        self.dbname = self.__class__.__name__.lower() + '_newt_test_database'
        self.base_conn = pg_connection('')
        self.base_conn.autocommit = True
        self.base_cursor = self.base_conn.cursor()
        self.drop_db()
        self.base_cursor.execute('create database ' + self.dbname)
        self.call_super = call_super
        if call_super:
            super(DBSetup, self).setUp()

    def drop_db(self):
        self.base_cursor.execute(
            """
            select pg_terminate_backend(pid) from pg_stat_activity
            where datname = %s
            """, (self.dbname,))
        self.base_cursor.execute('drop database if exists ' + self.dbname)

    def tearDown(self):
        if self.call_super:
            super(DBSetup, self).tearDown()

        if PYPY:
            # Make sure there aren't any leaked connections around
            # that would keep us from dropping the DB
            # (https://travis-ci.org/newtdb/db/jobs/195267673)
            # This needs a fix from RelStorage post 2.0.0.
            gc.collect()
            gc.collect()
        self.drop_db()
        self.base_cursor.close()
        self.base_conn.close()

<|next_version|>
import gc
import sys
import unittest

PYPY = hasattr(sys, 'pypy_version_info')

from .. import pg_connection
from .._util import closing

class DBSetup(object):

    maxDiff = None

    @property
    def dsn(self):
        return 'postgresql://localhost/' + self.dbname

    def setUp(self, call_super=True):
        self.dbname = self.__class__.__name__.lower() + '_newt_test_database'
        self.base_conn = pg_connection('')
        self.base_conn.autocommit = True
        self.base_cursor = self.base_conn.cursor()
        self.drop_db()
        self.base_cursor.execute('create database ' + self.dbname)
        self.call_super = call_super
        if call_super:
            super(DBSetup, self).setUp()

    def drop_db(self):
        self.base_cursor.execute(
            """
            select pg_terminate_backend(pid) from pg_stat_activity
            where datname = %s
            """, (self.dbname,))
        self.base_cursor.execute('drop database if exists ' + self.dbname)

    def tearDown(self):
        if self.call_super:
            super(DBSetup, self).tearDown()

        if PYPY:
            # Make sure there aren't any leaked connections around
            # that would keep us from dropping the DB
            # (https://travis-ci.org/newtdb/db/jobs/195267673)
            # This needs a fix from RelStorage post 2.0.0.
            gc.collect()
            gc.collect()
        self.drop_db()
        self.base_cursor.close()
        self.base_conn.close()

class TestCase(DBSetup, unittest.TestCase):
    pass


Insert customizable docstring at the beginning of settings file

--- pirx/base.py
+++ pirx/base.py
@@ -1,9 +1,16 @@
 import collections
+import datetime

 class Settings(object):
+    docstring = 'Settings built with Pirx on %(datetime)s'
+
     def __init__(self):
         self._settings = collections.OrderedDict()
+        docstring = self.docstring % {
+            'datetime': datetime.datetime.now()
+            }
+        self._set_raw_value('"""%s"""' % docstring)

     def __setattr__(self, name, value):
         if name.startswith('_'):

<|original_code|>
import collections

class Settings(object):
    def __init__(self):
        self._settings = collections.OrderedDict()

    def __setattr__(self, name, value):
        if name.startswith('_'):
            super(Settings, self).__setattr__(name, value)
        else:
            self._settings[name] = value

    def __str__(self):
        lines = []
        for name, value in self._settings.iteritems():
            if name.startswith('_'):
                lines.append(value)
            else:
                lines.append('%s = %s' % (name.upper(), value.__repr__()))
        return '\n'.join(lines)

    def _set_raw_value(self, value):
        self._settings['_%d' % len(self._settings)] = value

    def imp(self, module_name):
        value = 'import %s' % module_name
        self._set_raw_value(value)

<|edits_diff|>
--- pirx/base.py
+++ pirx/base.py
@@ -1,7 +1,10 @@
 import collections
+import datetime

 class Settings(object):
+    docstring = 'Settings built with Pirx on %(datetime)s'
+
     def __init__(self):
         self._settings = collections.OrderedDict()

<|current_version|>
import collections
import datetime

class Settings(object):
    docstring = 'Settings built with Pirx on %(datetime)s'

    def __init__(self):
        self._settings = collections.OrderedDict()

    def __setattr__(self, name, value):
        if name.startswith('_'):
            super(Settings, self).__setattr__(name, value)
        else:
            self._settings[name] = value

    def __str__(self):
        lines = []
        for name, value in self._settings.iteritems():
            if name.startswith('_'):
                lines.append(value)
            else:
                lines.append('%s = %s' % (name.upper(), value.__repr__()))
        return '\n'.join(lines)

    def _set_raw_value(self, value):
        self._settings['_%d' % len(self._settings)] = value

    def imp(self, module_name):
        value = 'import %s' % module_name
        self._set_raw_value(value)

<|next_version|>
import collections
import datetime

class Settings(object):
    docstring = 'Settings built with Pirx on %(datetime)s'

    def __init__(self):
        self._settings = collections.OrderedDict()
        docstring = self.docstring % {
            'datetime': datetime.datetime.now()
            }
        self._set_raw_value('"""%s"""' % docstring)

    def __setattr__(self, name, value):
        if name.startswith('_'):
            super(Settings, self).__setattr__(name, value)
        else:
            self._settings[name] = value

    def __str__(self):
        lines = []
        for name, value in self._settings.iteritems():
            if name.startswith('_'):
                lines.append(value)
            else:
                lines.append('%s = %s' % (name.upper(), value.__repr__()))
        return '\n'.join(lines)

    def _set_raw_value(self, value):
        self._settings['_%d' % len(self._settings)] = value

    def imp(self, module_name):
        value = 'import %s' % module_name
        self._set_raw_value(value)


Add argparse for info on hb command

Add argparse for info on hb command

--- homebrew/command_line.py
+++ homebrew/command_line.py
@@ -1,6 +1,9 @@
 # -*- coding: utf-8 -*-
+import argparse
+
 from .homebrew import HomeBrew

 def main():
+    argparse.ArgumentParser(description='Get homebrew info').parse_args()
     HomeBrew().log_info()

<|original_code|>
# -*- coding: utf-8 -*-
from .homebrew import HomeBrew

def main():
    HomeBrew().log_info()

<|edits_diff|>
--- homebrew/command_line.py
+++ homebrew/command_line.py
@@ -1,4 +1,6 @@
 # -*- coding: utf-8 -*-
+import argparse
+
 from .homebrew import HomeBrew

<|current_version|>
# -*- coding: utf-8 -*-
import argparse

from .homebrew import HomeBrew

def main():
    HomeBrew().log_info()

<|next_version|>
# -*- coding: utf-8 -*-
import argparse

from .homebrew import HomeBrew

def main():
    argparse.ArgumentParser(description='Get homebrew info').parse_args()
    HomeBrew().log_info()


Add a warning about future versions dropping Py2 support

Refs #64

--- valohai_cli/cli.py
+++ valohai_cli/cli.py
@@ -1,7 +1,10 @@
 import logging
+import platform
+import sys

 import click

+from valohai_cli.messages import warn
 from valohai_cli.plugin_cli import RecursiveHelpPluginCLI
 from valohai_cli.table import TABLE_FORMATS, TABLE_FORMAT_META_KEY

@@ -15,3 +18,8 @@
         logging.basicConfig(level=logging.DEBUG)
     ctx.debug = debug
     ctx.meta[TABLE_FORMAT_META_KEY] = table_format
+    if platform.python_implementation() in ('CPython', 'PyPy') and sys.version_info[:2] < (3, 5):
+        warn(
+            'A future version of the tool will drop support Python versions older than 3.5. '
+            'You are currently using Python %s. Please upgrade!' % platform.python_version()
+        )

<|original_code|>
import logging

import click

from valohai_cli.plugin_cli import RecursiveHelpPluginCLI
from valohai_cli.table import TABLE_FORMATS, TABLE_FORMAT_META_KEY

@click.command(cls=RecursiveHelpPluginCLI, commands_module='valohai_cli.commands')
@click.option('--debug/--no-debug', default=False, envvar='VALOHAI_DEBUG')
@click.option('--table-format', type=click.Choice(TABLE_FORMATS), default='human')
@click.pass_context
def cli(ctx, debug, table_format):
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    ctx.debug = debug
    ctx.meta[TABLE_FORMAT_META_KEY] = table_format

<|edits_diff|>
--- valohai_cli/cli.py
+++ valohai_cli/cli.py
@@ -1,7 +1,10 @@
 import logging
+import platform
+import sys

 import click

+from valohai_cli.messages import warn
 from valohai_cli.plugin_cli import RecursiveHelpPluginCLI
 from valohai_cli.table import TABLE_FORMATS, TABLE_FORMAT_META_KEY

<|current_version|>
import logging
import platform
import sys

import click

from valohai_cli.messages import warn
from valohai_cli.plugin_cli import RecursiveHelpPluginCLI
from valohai_cli.table import TABLE_FORMATS, TABLE_FORMAT_META_KEY

@click.command(cls=RecursiveHelpPluginCLI, commands_module='valohai_cli.commands')
@click.option('--debug/--no-debug', default=False, envvar='VALOHAI_DEBUG')
@click.option('--table-format', type=click.Choice(TABLE_FORMATS), default='human')
@click.pass_context
def cli(ctx, debug, table_format):
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    ctx.debug = debug
    ctx.meta[TABLE_FORMAT_META_KEY] = table_format

<|next_version|>
import logging
import platform
import sys

import click

from valohai_cli.messages import warn
from valohai_cli.plugin_cli import RecursiveHelpPluginCLI
from valohai_cli.table import TABLE_FORMATS, TABLE_FORMAT_META_KEY

@click.command(cls=RecursiveHelpPluginCLI, commands_module='valohai_cli.commands')
@click.option('--debug/--no-debug', default=False, envvar='VALOHAI_DEBUG')
@click.option('--table-format', type=click.Choice(TABLE_FORMATS), default='human')
@click.pass_context
def cli(ctx, debug, table_format):
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    ctx.debug = debug
    ctx.meta[TABLE_FORMAT_META_KEY] = table_format
    if platform.python_implementation() in ('CPython', 'PyPy') and sys.version_info[:2] < (3, 5):
        warn(
            'A future version of the tool will drop support Python versions older than 3.5. '
            'You are currently using Python %s. Please upgrade!' % platform.python_version()
        )


Include one tank on player 1 on game creation

--- src/engine/request_handler.py
+++ src/engine/request_handler.py
@@ -4,6 +4,8 @@
 import EBQP

 from . import world
+from . import types
+from . import consts

 class GameRequestHandler:
@@ -34,6 +36,7 @@
         uid1 = args['uid1']
         uid2 = args['uid2']
         self.world = world.World([uid1, uid2])
+        self.world.add_unit(uid1, types.new_unit('Tank', consts.RED))

         self.responses = {
             EBQP.view: self.respond_view,

<|original_code|>
import Queue
import json

import EBQP

from . import world

class GameRequestHandler:
    def __init__(self):
        self.world = None
        self.responses = {
            EBQP.new: self.respond_new,
        }

    def process(self, request):
        request_pieces = request.split(EBQP.packet_delimiter, 1)
        command = request_pieces[0]
        params = request_pieces[1].strip() if len(request_pieces) > 1 else ''
        try:
            json_args = json.loads(params)
        except Exception as e:
            return "process:failure:bad json"

        if command in self.responses:
            return self.responses[command](json_args)
        else:
            return "process:failure:unsupported command"

    def respond_new(self, args):
        if 'uid1' not in args or 'uid2' not in args:
            return 'new:failure:missing uid'

        uid1 = args['uid1']
        uid2 = args['uid2']
        self.world = world.World([uid1, uid2])

        self.responses = {
            EBQP.view: self.respond_view,
            EBQP.move: self.respond_move,
        }
        return 'new:success'

    def respond_view(self, args):
        return 'view:success:%s' % self.world.to_json()

    #TODO
    def respond_move(self, args):
        return 'move:failure:unimplemented'

<|edits_diff|>
--- src/engine/request_handler.py
+++ src/engine/request_handler.py
@@ -4,6 +4,8 @@
 import EBQP

 from . import world
+from . import types
+from . import consts

 class GameRequestHandler:
<|current_version|>
import Queue
import json

import EBQP

from . import world
from . import types
from . import consts

class GameRequestHandler:
    def __init__(self):
        self.world = None
        self.responses = {
            EBQP.new: self.respond_new,
        }

    def process(self, request):
        request_pieces = request.split(EBQP.packet_delimiter, 1)
        command = request_pieces[0]
        params = request_pieces[1].strip() if len(request_pieces) > 1 else ''
        try:
            json_args = json.loads(params)
        except Exception as e:
            return "process:failure:bad json"

        if command in self.responses:
            return self.responses[command](json_args)
        else:
            return "process:failure:unsupported command"

    def respond_new(self, args):
        if 'uid1' not in args or 'uid2' not in args:
            return 'new:failure:missing uid'

        uid1 = args['uid1']
        uid2 = args['uid2']
        self.world = world.World([uid1, uid2])

        self.responses = {
            EBQP.view: self.respond_view,
            EBQP.move: self.respond_move,
        }
        return 'new:success'

    def respond_view(self, args):
        return 'view:success:%s' % self.world.to_json()

    #TODO
    def respond_move(self, args):
        return 'move:failure:unimplemented'

<|next_version|>
import Queue
import json

import EBQP

from . import world
from . import types
from . import consts

class GameRequestHandler:
    def __init__(self):
        self.world = None
        self.responses = {
            EBQP.new: self.respond_new,
        }

    def process(self, request):
        request_pieces = request.split(EBQP.packet_delimiter, 1)
        command = request_pieces[0]
        params = request_pieces[1].strip() if len(request_pieces) > 1 else ''
        try:
            json_args = json.loads(params)
        except Exception as e:
            return "process:failure:bad json"

        if command in self.responses:
            return self.responses[command](json_args)
        else:
            return "process:failure:unsupported command"

    def respond_new(self, args):
        if 'uid1' not in args or 'uid2' not in args:
            return 'new:failure:missing uid'

        uid1 = args['uid1']
        uid2 = args['uid2']
        self.world = world.World([uid1, uid2])
        self.world.add_unit(uid1, types.new_unit('Tank', consts.RED))

        self.responses = {
            EBQP.view: self.respond_view,
            EBQP.move: self.respond_move,
        }
        return 'new:success'

    def respond_view(self, args):
        return 'view:success:%s' % self.world.to_json()

    #TODO
    def respond_move(self, args):
        return 'move:failure:unimplemented'


Set docstrings for check functions

Set docstrings for check functions

--- pirx/checks.py
+++ pirx/checks.py
@@ -4,9 +4,14 @@

 def host(name):
+    """Check if host name is equal to the given name"""
     return socket.gethostname() == name

 def arg(name, expected_value=None):
+    """
+    Check if command-line argument with a given name was passed and if it has
+    the expected value.
+    """
     args = [
         arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
     ]

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

def host(name):
    return socket.gethostname() == name

def arg(name, expected_value=None):
    args = [
        arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
    ]
    for arg_name, arg_value in args:
        if arg_name.lstrip('--') == name:
            return arg_value == expected_value
    return False

<|edits_diff|>
--- pirx/checks.py
+++ pirx/checks.py
@@ -4,6 +4,7 @@

 def host(name):
+    """Check if host name is equal to the given name"""
     return socket.gethostname() == name

 def arg(name, expected_value=None):
<|current_version|>
#!/usr/bin/env python
import socket
import sys

def host(name):
    """Check if host name is equal to the given name"""
    return socket.gethostname() == name

def arg(name, expected_value=None):
    args = [
        arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
    ]
    for arg_name, arg_value in args:
        if arg_name.lstrip('--') == name:
            return arg_value == expected_value
    return False

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

def host(name):
    """Check if host name is equal to the given name"""
    return socket.gethostname() == name

def arg(name, expected_value=None):
    """
    Check if command-line argument with a given name was passed and if it has
    the expected value.
    """
    args = [
        arg.split('=') for arg in sys.argv[1:] if '=' in arg else (arg, None)
    ]
    for arg_name, arg_value in args:
        if arg_name.lstrip('--') == name:
            return arg_value == expected_value
    return False


Make sure to load_backend as part of load_plugins

--- spicedham/__init__.py
+++ spicedham/__init__.py
@@ -1,6 +1,7 @@
 from pkg_resources import iter_entry_points

 from spicedham.config import load_config
+from spicedham.backend import load_backend

 _plugins = None

@@ -10,6 +11,8 @@
     """
     global _plugins
     if _plugins == None:
+        # In order to use the plugins config and backend must be loaded.
+        load_backend()
         load_config()
         _plugins = []
         for plugin in iter_entry_points(group='spicedham.classifiers', name=None):

<|original_code|>
from pkg_resources import iter_entry_points

from spicedham.config import load_config

_plugins = None

def load_plugins():
    """
    If not already loaded, load plugins.
    """
    global _plugins
    if _plugins == None:
        load_config()
        _plugins = []
        for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
            pluginClass = plugin.load()
            _plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in _plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in _plugins:
        value = plugin.classify(tag, classification_data)
        # Skip _plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no _plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0

<|edits_diff|>
--- spicedham/__init__.py
+++ spicedham/__init__.py
@@ -1,6 +1,7 @@
 from pkg_resources import iter_entry_points

 from spicedham.config import load_config
+from spicedham.backend import load_backend

 _plugins = None

<|current_version|>
from pkg_resources import iter_entry_points

from spicedham.config import load_config
from spicedham.backend import load_backend

_plugins = None

def load_plugins():
    """
    If not already loaded, load plugins.
    """
    global _plugins
    if _plugins == None:
        load_config()
        _plugins = []
        for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
            pluginClass = plugin.load()
            _plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in _plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in _plugins:
        value = plugin.classify(tag, classification_data)
        # Skip _plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no _plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0

<|next_version|>
from pkg_resources import iter_entry_points

from spicedham.config import load_config
from spicedham.backend import load_backend

_plugins = None

def load_plugins():
    """
    If not already loaded, load plugins.
    """
    global _plugins
    if _plugins == None:
        # In order to use the plugins config and backend must be loaded.
        load_backend()
        load_config()
        _plugins = []
        for plugin in iter_entry_points(group='spicedham.classifiers', name=None):
            pluginClass = plugin.load()
            _plugins.append(pluginClass())

def train(tag, training_data, is_spam):
    """
    Calls each plugin's train function.
    """
    for plugin in _plugins:
        plugin.train(tag, training_data, is_spam)

def classify(tag, classification_data):
    """
    Calls each plugin's classify function and averages the results.
    """
    average_score = 0
    total = 0
    for plugin in _plugins:
        value = plugin.classify(tag, classification_data)
        # Skip _plugins which give a score of None
        if value != None:
            total += 1
            average_score += value
    # On rare occasions no _plugins will give scores. If so, return 0
    if total > 0:
        return average_score / total
    else:
        return 0


Add note and fatal to Log

Add note and fatal to Log

--- util/log.py
+++ util/log.py
@@ -20,8 +20,17 @@
     Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)

   @classmethod
+  def note(cls, msg, new_line = True):
+    Log.print_msg("Note", msg, Colors.YELLOW_FG, new_line)
+
+  @classmethod
   def err(cls, msg, new_line = True):
     Log.print_msg("Error", msg, Colors.RED_FG, new_line)
+
+  @classmethod
+  def fatal(cls, msg, new_line = True):
+    Log.print_msg("Fatal", msg, Colors.RED_FG, new_line)
+    exit(1)

   @classmethod
   def raw(cls, msg, new_line = True):

<|original_code|>
import sys
from colors import Colors

class Log:

  @classmethod
  def print_msg(cls, title, msg, color, new_line = True):
    Log.raw("{0}{1}{2}: {3}".format(color, title, Colors.NORMAL, msg), new_line)

  @classmethod
  def msg(cls, msg, new_line = True):
    Log.print_msg("Message", msg, Colors.MAGENTA_FG, new_line)

  @classmethod
  def info(cls, msg, new_line = True):
    Log.print_msg("Info", msg, Colors.CYAN_FG, new_line)

  @classmethod
  def warn(cls, msg, new_line = True):
    Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)

  @classmethod
  def err(cls, msg, new_line = True):
    Log.print_msg("Error", msg, Colors.RED_FG, new_line)

  @classmethod
  def raw(cls, msg, new_line = True):
    if new_line and msg[-1:] != "\n":
      msg += "\n"
    sys.stdout.write("{0}".format(msg))

<|edits_diff|>
--- util/log.py
+++ util/log.py
@@ -20,6 +20,10 @@
     Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)

   @classmethod
+  def note(cls, msg, new_line = True):
+    Log.print_msg("Note", msg, Colors.YELLOW_FG, new_line)
+
+  @classmethod
   def err(cls, msg, new_line = True):
     Log.print_msg("Error", msg, Colors.RED_FG, new_line)

<|current_version|>
import sys
from colors import Colors

class Log:

  @classmethod
  def print_msg(cls, title, msg, color, new_line = True):
    Log.raw("{0}{1}{2}: {3}".format(color, title, Colors.NORMAL, msg), new_line)

  @classmethod
  def msg(cls, msg, new_line = True):
    Log.print_msg("Message", msg, Colors.MAGENTA_FG, new_line)

  @classmethod
  def info(cls, msg, new_line = True):
    Log.print_msg("Info", msg, Colors.CYAN_FG, new_line)

  @classmethod
  def warn(cls, msg, new_line = True):
    Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)

  @classmethod
  def note(cls, msg, new_line = True):
    Log.print_msg("Note", msg, Colors.YELLOW_FG, new_line)

  @classmethod
  def err(cls, msg, new_line = True):
    Log.print_msg("Error", msg, Colors.RED_FG, new_line)

  @classmethod
  def raw(cls, msg, new_line = True):
    if new_line and msg[-1:] != "\n":
      msg += "\n"
    sys.stdout.write("{0}".format(msg))

<|next_version|>
import sys
from colors import Colors

class Log:

  @classmethod
  def print_msg(cls, title, msg, color, new_line = True):
    Log.raw("{0}{1}{2}: {3}".format(color, title, Colors.NORMAL, msg), new_line)

  @classmethod
  def msg(cls, msg, new_line = True):
    Log.print_msg("Message", msg, Colors.MAGENTA_FG, new_line)

  @classmethod
  def info(cls, msg, new_line = True):
    Log.print_msg("Info", msg, Colors.CYAN_FG, new_line)

  @classmethod
  def warn(cls, msg, new_line = True):
    Log.print_msg("Warning", msg, Colors.YELLOW_FG, new_line)

  @classmethod
  def note(cls, msg, new_line = True):
    Log.print_msg("Note", msg, Colors.YELLOW_FG, new_line)

  @classmethod
  def err(cls, msg, new_line = True):
    Log.print_msg("Error", msg, Colors.RED_FG, new_line)

  @classmethod
  def fatal(cls, msg, new_line = True):
    Log.print_msg("Fatal", msg, Colors.RED_FG, new_line)
    exit(1)

  @classmethod
  def raw(cls, msg, new_line = True):
    if new_line and msg[-1:] != "\n":
      msg += "\n"
    sys.stdout.write("{0}".format(msg))


Add logging to Twitch emotes module

Add logging to Twitch emotes module

--- app/cogs/twitch_emotes.py
+++ app/cogs/twitch_emotes.py
@@ -1,10 +1,14 @@
 from io import BytesIO
+import logging
 import requests

 from discord.ext import commands
 from discord.ext.commands import Bot

 TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'
+
+
+logger = logging.getLogger(__name__)

 class TwitchEmotes:
@@ -19,6 +23,8 @@
         emote_ids = {name: info['image_id'] for name, info in
                      emote_data['emotes'].items()}
         emote_cache = {}
+        logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids))
+        logger.info('Using template: %s' % emote_template)

         @bot.listen('on_message')
         async def respond(message):
@@ -31,6 +37,7 @@
                 if text not in emote_cache:
                     url = emote_template.replace('{image_id}',
                                                  str(emote_ids[text]))
+                    logger.info('Fetching emote %s from %s' % (text, url))

                     emote_img = requests.get(url).content
                     emote_cache[text] = emote_img

<|original_code|>
from io import BytesIO
import requests

from discord.ext import commands
from discord.ext.commands import Bot

TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'

class TwitchEmotes:

    def __init__(self, bot: Bot):
        self.bot = bot

        r = requests.get(TWITCH_EMOTES_API)
        emote_data = r.json()

        emote_template = emote_data['template']['small']
        emote_ids = {name: info['image_id'] for name, info in
                     emote_data['emotes'].items()}
        emote_cache = {}

        @bot.listen('on_message')
        async def respond(message):
            if message.author == bot.user:
                return

            text = message.content

            if text in emote_ids:
                if text not in emote_cache:
                    url = emote_template.replace('{image_id}',
                                                 str(emote_ids[text]))

                    emote_img = requests.get(url).content
                    emote_cache[text] = emote_img

                data = BytesIO(emote_cache[text])
                filename = '%s.png' % text
                await bot.send_file(message.channel, data, filename=filename)

def setup(bot: Bot):
    bot.add_cog(TwitchEmotes(bot))

<|edits_diff|>
--- app/cogs/twitch_emotes.py
+++ app/cogs/twitch_emotes.py
@@ -1,10 +1,14 @@
 from io import BytesIO
+import logging
 import requests

 from discord.ext import commands
 from discord.ext.commands import Bot

 TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'
+
+
+logger = logging.getLogger(__name__)

 class TwitchEmotes:
@@ -19,6 +23,8 @@
         emote_ids = {name: info['image_id'] for name, info in
                      emote_data['emotes'].items()}
         emote_cache = {}
+        logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids))
+        logger.info('Using template: %s' % emote_template)

         @bot.listen('on_message')
         async def respond(message):
<|current_version|>
from io import BytesIO
import logging
import requests

from discord.ext import commands
from discord.ext.commands import Bot

TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'

logger = logging.getLogger(__name__)

class TwitchEmotes:

    def __init__(self, bot: Bot):
        self.bot = bot

        r = requests.get(TWITCH_EMOTES_API)
        emote_data = r.json()

        emote_template = emote_data['template']['small']
        emote_ids = {name: info['image_id'] for name, info in
                     emote_data['emotes'].items()}
        emote_cache = {}
        logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids))
        logger.info('Using template: %s' % emote_template)

        @bot.listen('on_message')
        async def respond(message):
            if message.author == bot.user:
                return

            text = message.content

            if text in emote_ids:
                if text not in emote_cache:
                    url = emote_template.replace('{image_id}',
                                                 str(emote_ids[text]))

                    emote_img = requests.get(url).content
                    emote_cache[text] = emote_img

                data = BytesIO(emote_cache[text])
                filename = '%s.png' % text
                await bot.send_file(message.channel, data, filename=filename)

def setup(bot: Bot):
    bot.add_cog(TwitchEmotes(bot))

<|next_version|>
from io import BytesIO
import logging
import requests

from discord.ext import commands
from discord.ext.commands import Bot

TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json'

logger = logging.getLogger(__name__)

class TwitchEmotes:

    def __init__(self, bot: Bot):
        self.bot = bot

        r = requests.get(TWITCH_EMOTES_API)
        emote_data = r.json()

        emote_template = emote_data['template']['small']
        emote_ids = {name: info['image_id'] for name, info in
                     emote_data['emotes'].items()}
        emote_cache = {}
        logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids))
        logger.info('Using template: %s' % emote_template)

        @bot.listen('on_message')
        async def respond(message):
            if message.author == bot.user:
                return

            text = message.content

            if text in emote_ids:
                if text not in emote_cache:
                    url = emote_template.replace('{image_id}',
                                                 str(emote_ids[text]))
                    logger.info('Fetching emote %s from %s' % (text, url))

                    emote_img = requests.get(url).content
                    emote_cache[text] = emote_img

                data = BytesIO(emote_cache[text])
                filename = '%s.png' % text
                await bot.send_file(message.channel, data, filename=filename)

def setup(bot: Bot):
    bot.add_cog(TwitchEmotes(bot))


Fix background color on OS X for histogram widget of ray.

--- ui/widgets/histogram/TrackingHistogramWidget.py
+++ ui/widgets/histogram/TrackingHistogramWidget.py
@@ -8,6 +8,7 @@
 from PySide.QtCore import *
 from HistogramWidget import HistogramWidget
 from TrackingNodeItem import TrackingNodeItem
+from ui.widgets import Style

 class TrackingHistogramWidget(HistogramWidget):
@@ -19,6 +20,7 @@
 	def __init__(self):
 		super(TrackingHistogramWidget, self).__init__()
 		self.nodeItem = None
+		Style.styleWidgetForTab(self)

 	def update(self):
 		super(TrackingHistogramWidget, self).update()

<|original_code|>
"""
TrackingHistogramWidget

:Authors:
	Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem

class TrackingHistogramWidget(HistogramWidget):
	"""
	TrackingHistogramWidget
	"""
	updatePosition = Signal(float)

	def __init__(self):
		super(TrackingHistogramWidget, self).__init__()
		self.nodeItem = None

	def update(self):
		super(TrackingHistogramWidget, self).update()
		if not self.nodeItem:
			return

		self.nodeItem.update()

	def setHistogram(self, histogram):
		super(TrackingHistogramWidget, self).setHistogram(histogram)
		if not self.nodeItem:
			self.nodeItem = TrackingNodeItem()
			self.scene().addItem(self.nodeItem)
		self.nodeItem.setHistogramItem(self._histogramItem)
		self.nodeItem.setPos(QPoint(0, 0))
		self.nodeItem.setZValue(300)
		self.nodeItem.delegate = self

	def updatePos(self, position):
		self.updatePosition.emit(position)

<|edits_diff|>
--- ui/widgets/histogram/TrackingHistogramWidget.py
+++ ui/widgets/histogram/TrackingHistogramWidget.py
@@ -8,6 +8,7 @@
 from PySide.QtCore import *
 from HistogramWidget import HistogramWidget
 from TrackingNodeItem import TrackingNodeItem
+from ui.widgets import Style

 class TrackingHistogramWidget(HistogramWidget):
<|current_version|>
"""
TrackingHistogramWidget

:Authors:
	Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
from ui.widgets import Style

class TrackingHistogramWidget(HistogramWidget):
	"""
	TrackingHistogramWidget
	"""
	updatePosition = Signal(float)

	def __init__(self):
		super(TrackingHistogramWidget, self).__init__()
		self.nodeItem = None

	def update(self):
		super(TrackingHistogramWidget, self).update()
		if not self.nodeItem:
			return

		self.nodeItem.update()

	def setHistogram(self, histogram):
		super(TrackingHistogramWidget, self).setHistogram(histogram)
		if not self.nodeItem:
			self.nodeItem = TrackingNodeItem()
			self.scene().addItem(self.nodeItem)
		self.nodeItem.setHistogramItem(self._histogramItem)
		self.nodeItem.setPos(QPoint(0, 0))
		self.nodeItem.setZValue(300)
		self.nodeItem.delegate = self

	def updatePos(self, position):
		self.updatePosition.emit(position)

<|next_version|>
"""
TrackingHistogramWidget

:Authors:
	Berend Klein Haneveld
"""
from PySide.QtGui import *
from PySide.QtCore import *
from HistogramWidget import HistogramWidget
from TrackingNodeItem import TrackingNodeItem
from ui.widgets import Style

class TrackingHistogramWidget(HistogramWidget):
	"""
	TrackingHistogramWidget
	"""
	updatePosition = Signal(float)

	def __init__(self):
		super(TrackingHistogramWidget, self).__init__()
		self.nodeItem = None
		Style.styleWidgetForTab(self)

	def update(self):
		super(TrackingHistogramWidget, self).update()
		if not self.nodeItem:
			return

		self.nodeItem.update()

	def setHistogram(self, histogram):
		super(TrackingHistogramWidget, self).setHistogram(histogram)
		if not self.nodeItem:
			self.nodeItem = TrackingNodeItem()
			self.scene().addItem(self.nodeItem)
		self.nodeItem.setHistogramItem(self._histogramItem)
		self.nodeItem.setPos(QPoint(0, 0))
		self.nodeItem.setZValue(300)
		self.nodeItem.delegate = self

	def updatePos(self, position):
		self.updatePosition.emit(position)


Use django json encoder for models manger params

--- custom/icds_reports/models/manager.py
+++ custom/icds_reports/models/manager.py
@@ -1,7 +1,9 @@
 from __future__ import absolute_import, unicode_literals

+import json
 import uuid

+from django.core.serializers.json import DjangoJSONEncoder
 from django.db.models.manager import BaseManager
 from django.db.models.query import QuerySet

@@ -13,6 +15,7 @@
         from custom.icds_reports.tasks import run_citus_experiment_raw_sql
         if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER):
             query, params = self.query.sql_with_params()
+            params = json.loads(json.dumps(params, cls=DjangoJSONEncoder))
             run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__)
         super(CitusComparisonQuerySet, self)._fetch_all()

<|original_code|>
from __future__ import absolute_import, unicode_literals

import uuid

from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet

from corehq.toggles import ICDS_COMPARE_QUERIES_AGAINST_CITUS, NAMESPACE_OTHER

class CitusComparisonQuerySet(QuerySet):
    def _fetch_all(self):
        from custom.icds_reports.tasks import run_citus_experiment_raw_sql
        if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER):
            query, params = self.query.sql_with_params()
            run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__)
        super(CitusComparisonQuerySet, self)._fetch_all()

class CitusComparisonManager(BaseManager.from_queryset(CitusComparisonQuerySet)):
    pass

<|edits_diff|>
--- custom/icds_reports/models/manager.py
+++ custom/icds_reports/models/manager.py
@@ -1,7 +1,9 @@
 from __future__ import absolute_import, unicode_literals

+import json
 import uuid

+from django.core.serializers.json import DjangoJSONEncoder
 from django.db.models.manager import BaseManager
 from django.db.models.query import QuerySet

<|current_version|>
from __future__ import absolute_import, unicode_literals

import json
import uuid

from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet

from corehq.toggles import ICDS_COMPARE_QUERIES_AGAINST_CITUS, NAMESPACE_OTHER

class CitusComparisonQuerySet(QuerySet):
    def _fetch_all(self):
        from custom.icds_reports.tasks import run_citus_experiment_raw_sql
        if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER):
            query, params = self.query.sql_with_params()
            run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__)
        super(CitusComparisonQuerySet, self)._fetch_all()

class CitusComparisonManager(BaseManager.from_queryset(CitusComparisonQuerySet)):
    pass

<|next_version|>
from __future__ import absolute_import, unicode_literals

import json
import uuid

from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.manager import BaseManager
from django.db.models.query import QuerySet

from corehq.toggles import ICDS_COMPARE_QUERIES_AGAINST_CITUS, NAMESPACE_OTHER

class CitusComparisonQuerySet(QuerySet):
    def _fetch_all(self):
        from custom.icds_reports.tasks import run_citus_experiment_raw_sql
        if ICDS_COMPARE_QUERIES_AGAINST_CITUS.enabled(uuid.uuid4().hex, NAMESPACE_OTHER):
            query, params = self.query.sql_with_params()
            params = json.loads(json.dumps(params, cls=DjangoJSONEncoder))
            run_citus_experiment_raw_sql.delay(query, params, data_source=self.model.__name__)
        super(CitusComparisonQuerySet, self)._fetch_all()

class CitusComparisonManager(BaseManager.from_queryset(CitusComparisonQuerySet)):
    pass


Add date and social media fields to proposal

--- pyconcz_2016/cfp/models.py
+++ pyconcz_2016/cfp/models.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.utils.timezone import now

 from pyconcz_2016.conferences.models import Conference

@@ -40,3 +41,4 @@

     # Private notes (for reviewers only)
     note = models.TextField()
+    date = models.DateTimeField(default=now)

<|original_code|>
from django.db import models

from pyconcz_2016.conferences.models import Conference

class Cfp(models.Model):
    conference = models.ForeignKey(Conference, related_name="cfps")
    title = models.CharField(max_length=200)

    date_start = models.DateTimeField()
    date_end = models.DateTimeField()

    class Meta:
        ordering = ['date_start']

    def __str__(self):
        return self.title

class Proposal(models.Model):
    DIFFICULTY = (
        ('all', 'All'),
        ('beginner', 'Beginner'),
        ('advanced', 'Advanced'),
    )

    cfp = models.ForeignKey(Cfp, related_name='proposals')

    # Public speaker info
    full_name = models.CharField(max_length=200)
    bio = models.TextField()
    twitter = models.CharField(max_length=20, blank=True)
    github = models.CharField(max_length=20, blank=True)

    # Public talk info
    title = models.CharField(max_length=200)
    abstract = models.TextField()
    difficulty = models.CharField(
        max_length=10, choices=DIFFICULTY, default='all')

    # Private notes (for reviewers only)
    note = models.TextField()

<|edits_diff|>
--- pyconcz_2016/cfp/models.py
+++ pyconcz_2016/cfp/models.py
@@ -1,4 +1,5 @@
 from django.db import models
+from django.utils.timezone import now

 from pyconcz_2016.conferences.models import Conference

<|current_version|>
from django.db import models
from django.utils.timezone import now

from pyconcz_2016.conferences.models import Conference

class Cfp(models.Model):
    conference = models.ForeignKey(Conference, related_name="cfps")
    title = models.CharField(max_length=200)

    date_start = models.DateTimeField()
    date_end = models.DateTimeField()

    class Meta:
        ordering = ['date_start']

    def __str__(self):
        return self.title

class Proposal(models.Model):
    DIFFICULTY = (
        ('all', 'All'),
        ('beginner', 'Beginner'),
        ('advanced', 'Advanced'),
    )

    cfp = models.ForeignKey(Cfp, related_name='proposals')

    # Public speaker info
    full_name = models.CharField(max_length=200)
    bio = models.TextField()
    twitter = models.CharField(max_length=20, blank=True)
    github = models.CharField(max_length=20, blank=True)

    # Public talk info
    title = models.CharField(max_length=200)
    abstract = models.TextField()
    difficulty = models.CharField(
        max_length=10, choices=DIFFICULTY, default='all')

    # Private notes (for reviewers only)
    note = models.TextField()

<|next_version|>
from django.db import models
from django.utils.timezone import now

from pyconcz_2016.conferences.models import Conference

class Cfp(models.Model):
    conference = models.ForeignKey(Conference, related_name="cfps")
    title = models.CharField(max_length=200)

    date_start = models.DateTimeField()
    date_end = models.DateTimeField()

    class Meta:
        ordering = ['date_start']

    def __str__(self):
        return self.title

class Proposal(models.Model):
    DIFFICULTY = (
        ('all', 'All'),
        ('beginner', 'Beginner'),
        ('advanced', 'Advanced'),
    )

    cfp = models.ForeignKey(Cfp, related_name='proposals')

    # Public speaker info
    full_name = models.CharField(max_length=200)
    bio = models.TextField()
    twitter = models.CharField(max_length=20, blank=True)
    github = models.CharField(max_length=20, blank=True)

    # Public talk info
    title = models.CharField(max_length=200)
    abstract = models.TextField()
    difficulty = models.CharField(
        max_length=10, choices=DIFFICULTY, default='all')

    # Private notes (for reviewers only)
    note = models.TextField()
    date = models.DateTimeField(default=now)


Add support for rendering with a URL prefix

This adds an optional MEDUSA_URL_PREFIX setting option that causes Django's URL
reversing to render URLS prefixed with this string. This is necessary when
hosting Django projects on a URI path other than /, as a proper WSGI environment
is not present to tell Django what URL prefix to use.

--- django_medusa/management/commands/staticsitegen.py
+++ django_medusa/management/commands/staticsitegen.py
@@ -1,4 +1,6 @@
+from django.conf import settings
 from django.core.management.base import BaseCommand
+from django.core.urlresolvers import set_script_prefix
 from django_medusa.renderers import StaticSiteRenderer
 from django_medusa.utils import get_static_renderers

@@ -12,6 +14,10 @@
     def handle(self, *args, **options):
         StaticSiteRenderer.initialize_output()

+        url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX')
+        if url_prefix is not None:
+            set_script_prefix(url_prefix)
+
         for Renderer in get_static_renderers():
             r = Renderer()
             r.generate()

<|original_code|>
from django.core.management.base import BaseCommand
from django_medusa.renderers import StaticSiteRenderer
from django_medusa.utils import get_static_renderers

class Command(BaseCommand):
    can_import_settings = True

    help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\
           'a class for processing one or more URL paths into static files.'

    def handle(self, *args, **options):
        StaticSiteRenderer.initialize_output()

        for Renderer in get_static_renderers():
            r = Renderer()
            r.generate()

        StaticSiteRenderer.finalize_output()

<|edits_diff|>
--- django_medusa/management/commands/staticsitegen.py
+++ django_medusa/management/commands/staticsitegen.py
@@ -1,4 +1,6 @@
+from django.conf import settings
 from django.core.management.base import BaseCommand
+from django.core.urlresolvers import set_script_prefix
 from django_medusa.renderers import StaticSiteRenderer
 from django_medusa.utils import get_static_renderers

<|current_version|>
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.urlresolvers import set_script_prefix
from django_medusa.renderers import StaticSiteRenderer
from django_medusa.utils import get_static_renderers

class Command(BaseCommand):
    can_import_settings = True

    help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\
           'a class for processing one or more URL paths into static files.'

    def handle(self, *args, **options):
        StaticSiteRenderer.initialize_output()

        for Renderer in get_static_renderers():
            r = Renderer()
            r.generate()

        StaticSiteRenderer.finalize_output()

<|next_version|>
from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.urlresolvers import set_script_prefix
from django_medusa.renderers import StaticSiteRenderer
from django_medusa.utils import get_static_renderers

class Command(BaseCommand):
    can_import_settings = True

    help = 'Looks for \'renderers.py\' in each INSTALLED_APP, which defines '\
           'a class for processing one or more URL paths into static files.'

    def handle(self, *args, **options):
        StaticSiteRenderer.initialize_output()

        url_prefix = getattr(settings, 'MEDUSA_URL_PREFIX')
        if url_prefix is not None:
            set_script_prefix(url_prefix)

        for Renderer in get_static_renderers():
            r = Renderer()
            r.generate()

        StaticSiteRenderer.finalize_output()


Set up Flask-User to provide user auth

Set up Flask-User to provide user auth

--- app/__init__.py
+++ app/__init__.py
@@ -2,6 +2,7 @@
 from flask_sqlalchemy import SQLAlchemy
 from flask_migrate import Migrate
 from flask_mail import Mail
+from flask_user import UserManager, SQLAlchemyAdapter

 app = Flask(__name__)
 app.config.from_object('config')
@@ -12,6 +13,11 @@
 # Load Flask-Mail
 mail = Mail(app)

+# Configure user model for Flask-User
+from app.models import User
+
+db_adapter = SQLAlchemyAdapter(db, User)
+user_manager = UserManager(db_adapter, app)

 from app import views, models

<|original_code|>
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail

app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Load Flask-Mail
mail = Mail(app)

from app import views, models

<|edits_diff|>
--- app/__init__.py
+++ app/__init__.py
@@ -2,6 +2,7 @@
 from flask_sqlalchemy import SQLAlchemy
 from flask_migrate import Migrate
 from flask_mail import Mail
+from flask_user import UserManager, SQLAlchemyAdapter

 app = Flask(__name__)
 app.config.from_object('config')
<|current_version|>
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_user import UserManager, SQLAlchemyAdapter

app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Load Flask-Mail
mail = Mail(app)

from app import views, models

<|next_version|>
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_mail import Mail
from flask_user import UserManager, SQLAlchemyAdapter

app = Flask(__name__)
app.config.from_object('config')

db = SQLAlchemy(app)
migrate = Migrate(app, db)

# Load Flask-Mail
mail = Mail(app)

# Configure user model for Flask-User
from app.models import User

db_adapter = SQLAlchemyAdapter(db, User)
user_manager = UserManager(db_adapter, app)

from app import views, models


Delete manual Pipeline before creating

fix: Delete manual Pipeline before creating

See also: #72

--- src/foremast/pipeline/create_pipeline_manual.py
+++ src/foremast/pipeline/create_pipeline_manual.py
@@ -15,6 +15,7 @@
 #   limitations under the License.
 """Create manual Pipeline for Spinnaker."""
 from ..utils.lookups import FileLookup
+from .clean_pipelines import delete_pipeline
 from .create_pipeline import SpinnakerPipeline

@@ -27,6 +28,8 @@
         lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

         for json_file in self.settings['pipeline']['pipeline_files']:
+            delete_pipeline(app=self.app_name, pipeline_name=json_file)
+
             json_dict = lookup.json(filename=json_file)
             json_dict['name'] = json_file
             self.post_pipeline(json_dict)

<|original_code|>
#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True

<|edits_diff|>
--- src/foremast/pipeline/create_pipeline_manual.py
+++ src/foremast/pipeline/create_pipeline_manual.py
@@ -15,6 +15,7 @@
 #   limitations under the License.
 """Create manual Pipeline for Spinnaker."""
 from ..utils.lookups import FileLookup
+from .clean_pipelines import delete_pipeline
 from .create_pipeline import SpinnakerPipeline

<|current_version|>
#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True

<|next_version|>
#   Foremast - Pipeline Tooling
#
#   Copyright 2016 Gogo, LLC
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
"""Create manual Pipeline for Spinnaker."""
from ..utils.lookups import FileLookup
from .clean_pipelines import delete_pipeline
from .create_pipeline import SpinnakerPipeline

class SpinnakerPipelineManual(SpinnakerPipeline):
    """Manual JSON configured Spinnaker Pipelines."""

    def create_pipeline(self):
        """Use JSON files to create Pipelines."""
        self.log.info('Uploading manual Pipelines: %s')
        lookup = FileLookup(git_short=self.generated.gitlab()['main'], runway_dir=self.runway_dir)

        for json_file in self.settings['pipeline']['pipeline_files']:
            delete_pipeline(app=self.app_name, pipeline_name=json_file)

            json_dict = lookup.json(filename=json_file)
            json_dict['name'] = json_file
            self.post_pipeline(json_dict)

        return True


Make test environment use CNOT_CR implementation of CNOT.

At least for the test_pulse_types tests.

--- tests/test_pulse_types.py
+++ tests/test_pulse_types.py
@@ -2,11 +2,13 @@

 from QGL import *
 from QGL.PulseSequencer import *
+import QGL.config
 from .helpers import setup_test_lib

 class PulseTypes(unittest.TestCase):
     def setUp(self):
         setup_test_lib()
+        QGL.config.cnot_implementation = 'CNOT_CR'
         self.q1 = QubitFactory('q1')
         self.q2 = QubitFactory('q2')
         self.q3 = QubitFactory('q3')

<|original_code|>
import unittest

from QGL import *
from QGL.PulseSequencer import *
from .helpers import setup_test_lib

class PulseTypes(unittest.TestCase):
    def setUp(self):
        setup_test_lib()
        self.q1 = QubitFactory('q1')
        self.q2 = QubitFactory('q2')
        self.q3 = QubitFactory('q3')
        self.q4 = QubitFactory('q4')

    def test_promotion_rules(self):
        q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4

        assert( type(X(q1)) == Pulse )
        assert( type(X(q1) + Y(q1)) == CompositePulse )
        assert( type(X(q1) * X(q2)) == PulseBlock )
        assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock )

        assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate )
        assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )

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

 from QGL import *
 from QGL.PulseSequencer import *
+import QGL.config
 from .helpers import setup_test_lib

 class PulseTypes(unittest.TestCase):
<|current_version|>
import unittest

from QGL import *
from QGL.PulseSequencer import *
import QGL.config
from .helpers import setup_test_lib

class PulseTypes(unittest.TestCase):
    def setUp(self):
        setup_test_lib()
        self.q1 = QubitFactory('q1')
        self.q2 = QubitFactory('q2')
        self.q3 = QubitFactory('q3')
        self.q4 = QubitFactory('q4')

    def test_promotion_rules(self):
        q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4

        assert( type(X(q1)) == Pulse )
        assert( type(X(q1) + Y(q1)) == CompositePulse )
        assert( type(X(q1) * X(q2)) == PulseBlock )
        assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock )

        assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate )
        assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )

<|next_version|>
import unittest

from QGL import *
from QGL.PulseSequencer import *
import QGL.config
from .helpers import setup_test_lib

class PulseTypes(unittest.TestCase):
    def setUp(self):
        setup_test_lib()
        QGL.config.cnot_implementation = 'CNOT_CR'
        self.q1 = QubitFactory('q1')
        self.q2 = QubitFactory('q2')
        self.q3 = QubitFactory('q3')
        self.q4 = QubitFactory('q4')

    def test_promotion_rules(self):
        q1, q2, q3, q4 = self.q1, self.q2, self.q3, self.q4

        assert( type(X(q1)) == Pulse )
        assert( type(X(q1) + Y(q1)) == CompositePulse )
        assert( type(X(q1) * X(q2)) == PulseBlock )
        assert( type((X(q1) + Y(q1)) * X(q2)) == PulseBlock )

        assert( type(CNOT(q1, q2) * X(q3)) == CompoundGate )
        assert( type(CNOT(q1, q2) * CNOT(q3, q4)) == CompoundGate )