import json

from candidates.models import PopItPerson
from candidates.popit import PopItApiMixin, get_base_url

from django.core.management.base import BaseCommand

class Command(PopItApiMixin, BaseCommand):

    def handle(self, **options):
        message = "WARNING: this will delete all people, posts, " \
            "organizations and\nmemberships from the PopIt instance:" + \
            "\n\n  " + get_base_url() + "\n\nIf you really want to do " + \
            "this, type 'YES':"
        self.stdout.write(message)
        user_response = raw_input()
        if user_response != 'YES':
            self.stdout.write("Aborting, since you didn't type 'YES'.")
            return
        for collection in (
                'memberships',
                'posts',
                'organizations',
                'persons',
        ):
            self.stdout.write("Deleting from collection: " + collection)
            api_collection = getattr(self.api, collection)
            # We have to be careful here - if you try to step to page
            # 2 after deleting everything on page 1, then lots of
            # objects will be missed. Instead, just get the first page
            # until there's nothing left.
            while True:
                results = api_collection.get()
                for o in results['result']:
                    object_id = o['id']
                    api_collection(object_id).delete()
                if not results.get('has_more'):
                    break

Add a command to delete all objects from PopIt

Response:
import json

from candidates.models import PopItPerson
from candidates.popit import PopItApiMixin, get_base_url

from django.core.management.base import BaseCommand

class Command(PopItApiMixin, BaseCommand):

    def handle(self, **options):
        message = "WARNING: this will delete all people, posts, " \
            "organizations and\nmemberships from the PopIt instance:" + \
            "\n\n  " + get_base_url() + "\n\nIf you really want to do " + \
            "this, type 'YES':"
        self.stdout.write(message)
        user_response = raw_input()
        if user_response != 'YES':
            self.stdout.write("Aborting, since you didn't type 'YES'.")
            return
        for collection in (
                'memberships',
                'posts',
                'organizations',
                'persons',
        ):
            self.stdout.write("Deleting from collection: " + collection)
            api_collection = getattr(self.api, collection)
            # We have to be careful here - if you try to step to page
            # 2 after deleting everything on page 1, then lots of
            # objects will be missed. Instead, just get the first page
            # until there's nothing left.
            while True:
                results = api_collection.get()
                for o in results['result']:
                    object_id = o['id']
                    api_collection(object_id).delete()
                if not results.get('has_more'):
                    break

Prompt: Add a command to delete all objects from PopIt


from setuptools import setup, find_packages
setup(
    name = 'CommonModules',
    packages = find_packages(where = '.'), # this must be the same as the name above
    version = '0.1.13',
    description = 'Common Python modules/functionalities used in practice.',
    author = 'Wang Hewen',
    author_email = 'wanghewen2@sina.com',
    url = 'https://github.com/wanghewen/CommonModules', # use the URL to the github repo
    keywords = ['library'], # arbitrary keywords
    license='MIT',
    install_requires=[],
	extras_require = {
        'Advance DataStructureOperations':  ['scipy', 'numpy'],
		'Advance DataStructure IO':  ['networkx', 'numpy', 'scipy']
    }
)

Response:
from setuptools import setup, find_packages
setup(
    name = 'CommonModules',
    packages = find_packages(where = '.'), # this must be the same as the name above
    version = '0.1.13',
    description = 'Common Python modules/functionalities used in practice.',
    author = 'Wang Hewen',
    author_email = 'wanghewen2@sina.com',
    url = 'https://github.com/wanghewen/CommonModules', # use the URL to the github repo
    keywords = ['library'], # arbitrary keywords
    license='MIT',
    install_requires=[],
	extras_require = {
        'Advance DataStructureOperations':  ['scipy', 'numpy'],
		'Advance DataStructure IO':  ['networkx', 'numpy', 'scipy']
    }
)

Prompt:
Fix version number. Will check the file in another machine and fix the conflict

from setuptools import setup, find_packages
setup(
    name = 'CommonModules',
    packages = find_packages(where = '.'), # this must be the same as the name above
    version = '0.1.11',
    description = 'Common Python modules/functionalities used in practice.',
    author = 'Wang Hewen',
    author_email = 'wanghewen2@sina.com',
    url = 'https://github.com/wanghewen/CommonModules', # use the URL to the github repo
    keywords = ['library'], # arbitrary keywords
    license='MIT',
    install_requires=[],
	extras_require = {
        'Advance DataStructureOperations':  ['scipy', 'numpy'],
		'Advance DataStructure IO':  ['networkx', 'numpy', 'scipy']
    }
)


# Generated by Django 2.2.17 on 2020-11-29 10:58

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('workshops', '0222_workshoprequest_workshop_listed'),
    ]

    operations = [
        migrations.AddField(
            model_name='membership',
            name='agreement_link',
            field=models.URLField(blank=True, default='', help_text='Link to member agreement document or folder in Google Drive', null=True, verbose_name='Link to member agreement'),
        ),
    ]

Update help text in migration

Update help text in migration

Response:
# Generated by Django 2.2.17 on 2020-11-29 10:58

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('workshops', '0222_workshoprequest_workshop_listed'),
    ]

    operations = [
        migrations.AddField(
            model_name='membership',
            name='agreement_link',
            field=models.URLField(blank=True, default='', help_text='Link to member agreement document or folder in Google Drive', null=True, verbose_name='Link to member agreement'),
        ),
    ]

Prompt:
Update help text in migration

# Generated by Django 2.2.13 on 2020-11-18 20:58

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('workshops', '0222_workshoprequest_workshop_listed'),
    ]

    operations = [
        migrations.AddField(
            model_name='membership',
            name='agreement_link',
            field=models.URLField(blank=True, default='', help_text='Link to member agreement or folder in Google Drive', null=True, verbose_name='Link to member agreement'),
        ),
    ]


# This script should be copied into the Run Script trigger of an Xcode Bot

# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson

#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH

# Set unique Build Number prior to TestFlight upload
cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist

# Set internal Apptentive API Key and App ID for TestFlight builds
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey

echo "Finished running Before Integration script"

Response:
# This script should be copied into the Run Script trigger of an Xcode Bot

# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson

#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH

# Set unique Build Number prior to TestFlight upload
cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist

# Set internal Apptentive API Key and App ID for TestFlight builds
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist --value 980430089 --key ATTestFlightAppIDKey

echo "Finished running Before Integration script"

Prompt:
Use the correct Info.plist in the new version of FeedbackDemo

# This script should be copied into the Run Script trigger of an Xcode Bot

# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson

#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH

# Set unique Build Number prior to TestFlight upload
cavejohnson setBuildNumber --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist

# Set internal Apptentive API Key and App ID for TestFlight builds
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value INSERT_TESTFLIGHT_API_KEY --key ATTestFlightAPIKey
cavejohnson setPlistValueForKey --plist-path ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist --value 980430089 --key ATTestFlightAppIDKey

echo "Finished running Before Integration script"


# -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles

def simple_plot(stylename):
    """Generate a simple plot using a given matplotlib style."""
    if stylename == 'typhon-dark':
        # TODO: Sphinx build is broken for non-white figure facecolor.
        return

    x = np.linspace(0, np.pi, 20)

    fig, ax = plt.subplots()
    for s in np.linspace(0, np.pi / 2, 12):
        ax.plot(x, np.sin(x+s),
                label=r'$\Delta\omega = {:.2f}$'.format(s),
                marker='.',
                )
    ax.set_ylabel('y-axis')
    ax.set_xlabel('x-axis')
    ax.set_title(stylename)
    ax.grid()
    ax.legend()

# Create plot using default styles.
simple_plot('matplotlib 2.0')

# Create a plot for each available typhon style.
for style_name in styles.available:
    with plt.style.context(styles(style_name)):
        simple_plot(style_name)

plt.show()

Response:
# -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles

def simple_plot(stylename):
    """Generate a simple plot using a given matplotlib style."""
    if stylename == 'typhon-dark':
        # TODO: Sphinx build is broken for non-white figure facecolor.
        return

    x = np.linspace(0, np.pi, 20)

    fig, ax = plt.subplots()
    for s in np.linspace(0, np.pi / 2, 12):
        ax.plot(x, np.sin(x+s),
                label=r'$\Delta\omega = {:.2f}$'.format(s),
                marker='.',
                )
    ax.set_ylabel('y-axis')
    ax.set_xlabel('x-axis')
    ax.set_title(stylename)
    ax.grid()
    ax.legend()

# Create plot using default styles.
simple_plot('matplotlib 2.0')

# Create a plot for each available typhon style.
for style_name in styles.available:
    with plt.style.context(styles(style_name)):
        simple_plot(style_name)

plt.show()

Prompt:
Exclude dark-colored theme from stylesheet gallery.

# -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles

def simple_plot(stylename):
    """Generate a simple plot using a given matplotlib style."""
    x = np.linspace(0, np.pi, 20)

    fig, ax = plt.subplots()
    for s in np.linspace(0, np.pi / 2, 12):
        ax.plot(x, np.sin(x+s),
                label=r'$\Delta\omega = {:.2f}$'.format(s),
                marker='.',
                )
    ax.set_ylabel('y-axis')
    ax.set_xlabel('x-axis')
    ax.set_title(stylename)
    ax.grid()
    ax.legend()

# Create plot using default styles.
simple_plot('matplotlib 2.0')

# Create a plot for each available typhon style.
for style_name in styles.available:
    with plt.style.context(styles(style_name)):
        simple_plot(style_name)

plt.show()


# -*- coding: utf-8 -*-

import time
import json
import sys
import pika
import os
from tweepy.streaming import StreamListener

class Listener(StreamListener):
    def __init__(self):
        #setup rabbitMQ Connection
        host = os.environ['CLOUDAMQP_URL']
        connection = pika.BlockingConnection(pika.ConnectionParameters(host=host))

    	self.channel = connection.channel()

    	#set max queue size
    	args = {"x-max-length": 2000}

    	self.channel.queue_declare(queue='social_data', arguments=args)

    def on_data(self, data):
        try:
            data = json.loads(data)
            if data["text"]:
                self.verify(data)
                time.sleep(5)
                return True

        except BaseException, e:
            print("failed in ondata, ", str(e))
            time.sleep(5)
            pass

    def on_error(self, status):
        print(status)

    def verify(self, data):
        print "Incoming tweet from " + data["user"]["screen_name"]
        tweet = data["text"]

        # enqueue the tweet
        self.channel.basic_publish(exchange='',
                                   routing_key='social_data',
                                   body=data["text"])

Response:
# -*- coding: utf-8 -*-

import time
import json
import sys
import pika
import os
from tweepy.streaming import StreamListener

class Listener(StreamListener):
    def __init__(self):
        #setup rabbitMQ Connection
        host = os.environ['CLOUDAMQP_URL']
        connection = pika.BlockingConnection(pika.ConnectionParameters(host=host))

    	self.channel = connection.channel()

    	#set max queue size
    	args = {"x-max-length": 2000}

    	self.channel.queue_declare(queue='social_data', arguments=args)

    def on_data(self, data):
        try:
            data = json.loads(data)
            if data["text"]:
                self.verify(data)
                time.sleep(5)
                return True

        except BaseException, e:
            print("failed in ondata, ", str(e))
            time.sleep(5)
            pass

    def on_error(self, status):
        print(status)

    def verify(self, data):
        print "Incoming tweet from " + data["user"]["screen_name"]
        tweet = data["text"]

        # enqueue the tweet
        self.channel.basic_publish(exchange='',
                                   routing_key='social_data',
                                   body=data["text"])

Prompt:
Set up environment specific connection to rabbitmq

# -*- coding: utf-8 -*-

import time
import json
import sys
import pika
from tweepy.streaming import StreamListener

class Listener(StreamListener):
    def __init__(self):
        #setup rabbitMQ Connection
    	connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))

    	self.channel = connection.channel()

    	#set max queue size
    	args = {"x-max-length": 2000}

    	self.channel.queue_declare(queue='social_data', arguments=args)

    def on_data(self, data):
        try:
            data = json.loads(data)
            if data["text"]:
                self.verify(data)
                time.sleep(5)
                return True

        except BaseException, e:
            print("failed in ondata, ", str(e))
            time.sleep(5)
            pass

    def on_error(self, status):
        print(status)

    def verify(self, data):
        print "Incoming tweet from " + data["user"]["screen_name"]
        tweet = data["text"]

        # enqueue the tweet
        self.channel.basic_publish(exchange='',
                                   routing_key='social_data',
                                   body=data["text"])


# Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

"""Top-level presubmit script for Dart.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""

def CheckChangeOnCommit(input_api, output_api):
  results = []
  status_check = input_api.canned_checks.CheckTreeIsOpen(
      input_api,
      output_api,
      json_url='http://dart-status.appspot.com/current?format=json')
  results.extend(status_check)
  return results

Add gcl presubmit script to the dart src tree.

Currently I just added a tree status check but we can extend this over time.
Review URL: https://chromiumcodereview.appspot.com//10891021

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@11575 260f80e4-7a28-3924-810f-c04153c831b5

Response:
# Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

"""Top-level presubmit script for Dart.

See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into gcl.
"""

def CheckChangeOnCommit(input_api, output_api):
  results = []
  status_check = input_api.canned_checks.CheckTreeIsOpen(
      input_api,
      output_api,
      json_url='http://dart-status.appspot.com/current?format=json')
  results.extend(status_check)
  return results

Prompt:
Add gcl presubmit script to the dart src tree.

Currently I just added a tree status check but we can extend this over time.
Review URL: https://chromiumcodereview.appspot.com//10891021

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@11575 260f80e4-7a28-3924-810f-c04153c831b5


import dbus

bus = dbus.SystemBus()

dummy = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.freedesktop.DBus.Introspectable')

#print dummy.Introspect()

manager = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.bluez.Manager')

try:
	adapter = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.Adapter')
except:
	pass

Remove old 3.x API cruft

Remove old 3.x API cruft

Response:
import dbus

bus = dbus.SystemBus()

dummy = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.freedesktop.DBus.Introspectable')

#print dummy.Introspect()

manager = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.bluez.Manager')

try:
	adapter = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.Adapter')
except:
	pass

Prompt:
Remove old 3.x API cruft

import dbus

bus = dbus.SystemBus()

dummy = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.freedesktop.DBus.Introspectable')

#print dummy.Introspect()

manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager')

database = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Database')

try:
	adapter = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.Adapter')

	test = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.Test')

	rfcomm = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()), 'org.bluez.RFCOMM')
except:
	adapter = ""

	test = ""

	rfcomm = ""

def create_service(identifier):
	try:
		path = manager.FindService(identifier)
	except:
		path = ""

	if (path != ""):
		return dbus.Interface(bus.get_object('org.bluez', path), 'org.bluez.Service')

echo = create_service("echo")

transfer = create_service("transfer")

network = create_service("network")

input = create_service("input")

audio = create_service("audio")

headset = create_service("headset")

def connect_service(identifier):
	try:
		conn = manager.ActivateService(identifier)
	except:
		conn = ""

	if (conn != ""):
		return dbus.Interface(bus.get_object(conn, "/org/bluez/" + identifier), 'org.bluez.' + identifier + '.Manager')


"""Setuptools configuration for interfaces."""

from setuptools import setup
from setuptools import find_packages

with open('README.rst', 'r') as readmefile:

    README = readmefile.read()

setup(
    name='asyncdef.interfaces',
    version='0.1.3',
    url='https://github.com/asyncdef/interfaces',
    description='Public APIs for the core asyncdef components.',
    author="Kevin Conway",
    author_email="kevinjacobconway@gmail.com",
    long_description=README,
    license='Apache 2.0',
    packages=[
        'asyncdef',
        'asyncdef.interfaces',
        'asyncdef.interfaces.engine',
    ],
    install_requires=[
        'iface',
    ],
    extras_require={
        'testing': [
            'pep257',
            'pep8',
            'pyenchant',
            'pyflakes',
            'pylint',
        ],
    },
    entry_points={
        'console_scripts': [

        ],
    },
    include_package_data=True,
    zip_safe=False,
)

Response:
"""Setuptools configuration for interfaces."""

from setuptools import setup
from setuptools import find_packages

with open('README.rst', 'r') as readmefile:

    README = readmefile.read()

setup(
    name='asyncdef.interfaces',
    version='0.1.3',
    url='https://github.com/asyncdef/interfaces',
    description='Public APIs for the core asyncdef components.',
    author="Kevin Conway",
    author_email="kevinjacobconway@gmail.com",
    long_description=README,
    license='Apache 2.0',
    packages=[
        'asyncdef',
        'asyncdef.interfaces',
        'asyncdef.interfaces.engine',
    ],
    install_requires=[
        'iface',
    ],
    extras_require={
        'testing': [
            'pep257',
            'pep8',
            'pyenchant',
            'pyflakes',
            'pylint',
        ],
    },
    entry_points={
        'console_scripts': [

        ],
    },
    include_package_data=True,
    zip_safe=False,
)

Prompt:
Fix packaging to resolve the PEP420 namespace

Setuptools is still lacking support for PEP480 namespace packages
when using the find_packages function. Until it does all packages,
including the namespace, must be registered in the packages list.

"""Setuptools configuration for interfaces."""

from setuptools import setup
from setuptools import find_packages

with open('README.rst', 'r') as readmefile:

    README = readmefile.read()

setup(
    name='asyncdef.interfaces',
    version='0.1.0',
    url='https://github.com/asyncdef/interfaces',
    description='Public APIs for the core asyncdef components.',
    author="Kevin Conway",
    author_email="kevinjacobconway@gmail.com",
    long_description=README,
    license='Apache 2.0',
    packages=find_packages(exclude=['build', 'dist', 'docs']),
    install_requires=[
        'iface',
    ],
    extras_require={
        'testing': [
            'pep257',
            'pep8',
            'pyenchant',
            'pyflakes',
            'pylint',
        ],
    },
    entry_points={
        'console_scripts': [

        ],
    },
    include_package_data=True,
    zip_safe=False,
)


import functools
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
tf.app.flags.DEFINE_string("float-type", "float32", "")

@functools.lru_cache()
def words():
  with open(tf.app.flags.FLAGS.word_file) as file_:
    return sorted([line.strip() for line in file_.readlines()])

@functools.lru_cache()
def word_indices():
  # 0 -> null, 1 -> unknown
  return { word: index + 2 for index, word in enumerate(flags.words()) }

@functools.lru_cache()
def word_space_size():
  return len(words())

def rnn_cell():
  from .rnn import cell
  return getattr(cell, FLAGS.rnn_cell)

def float_type():
  return getattr(tf, FLAGS.float_type)

Fix float type flag definition

Fix float type flag definition

Response:
import functools
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
tf.app.flags.DEFINE_string("float-type", "float32", "")

@functools.lru_cache()
def words():
  with open(tf.app.flags.FLAGS.word_file) as file_:
    return sorted([line.strip() for line in file_.readlines()])

@functools.lru_cache()
def word_indices():
  # 0 -> null, 1 -> unknown
  return { word: index + 2 for index, word in enumerate(flags.words()) }

@functools.lru_cache()
def word_space_size():
  return len(words())

def rnn_cell():
  from .rnn import cell
  return getattr(cell, FLAGS.rnn_cell)

def float_type():
  return getattr(tf, FLAGS.float_type)

Prompt:
Fix float type flag definition

import functools
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
tf.app.flags.DEFINE_string("float32", "", "")

@functools.lru_cache()
def words():
  with open(tf.app.flags.FLAGS.word_file) as file_:
    return sorted([line.strip() for line in file_.readlines()])

@functools.lru_cache()
def word_indices():
  # 0 -> null, 1 -> unknown
  return { word: index + 2 for index, word in enumerate(flags.words()) }

@functools.lru_cache()
def word_space_size():
  return len(words())

def rnn_cell():
  from .rnn import cell
  return getattr(cell, FLAGS.rnn_cell)

def float_type():
  return getattr(tf, FLAGS.float_type)


import argparse

from alerta.app import app
from alerta.app import db
from alerta.version import __version__

LOG = app.logger

def main():

    parser = argparse.ArgumentParser(
        prog='alertad',
        description='Alerta server (for development purposes only)',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        '-H',
        '--host',
        type=str,
        default='0.0.0.0',
        help='Bind host'
    )
    parser.add_argument(
        '-P',
        '--port',
        type=int,
        default=8080,
        help='Listen port'
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help='Debug output'
    )
    args = parser.parse_args()

    LOG.info('Starting alerta version %s ...', __version__)
    app.run(host=args.host, port=args.port, debug=args.debug, threaded=True, use_reloader=False)

Disable auto-reloader in debug mode

Response:
import argparse

from alerta.app import app
from alerta.app import db
from alerta.version import __version__

LOG = app.logger

def main():

    parser = argparse.ArgumentParser(
        prog='alertad',
        description='Alerta server (for development purposes only)',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        '-H',
        '--host',
        type=str,
        default='0.0.0.0',
        help='Bind host'
    )
    parser.add_argument(
        '-P',
        '--port',
        type=int,
        default=8080,
        help='Listen port'
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help='Debug output'
    )
    args = parser.parse_args()

    LOG.info('Starting alerta version %s ...', __version__)
    app.run(host=args.host, port=args.port, debug=args.debug, threaded=True, use_reloader=False)

Prompt:
Disable auto-reloader in debug mode

This was causing issues with plugin initialisation happening twice
and was getting rate limited by Telegram Bot API.

import argparse

from alerta.app import app
from alerta.app import db
from alerta.version import __version__

LOG = app.logger

def main():

    parser = argparse.ArgumentParser(
        prog='alertad',
        description='Alerta server (for development purposes only)',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        '-H',
        '--host',
        type=str,
        default='0.0.0.0',
        help='Bind host'
    )
    parser.add_argument(
        '-P',
        '--port',
        type=int,
        default=8080,
        help='Listen port'
    )
    parser.add_argument(
        '--debug',
        action='store_true',
        default=False,
        help='Debug output'
    )
    args = parser.parse_args()

    LOG.info('Starting alerta version %s ...', __version__)
    app.run(host=args.host, port=args.port, debug=args.debug, threaded=True)


from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _

class Excerpt(models.Model):
    name = models.CharField(max_length=128, verbose_name=_('name'))
    is_public = models.BooleanField(default=False, verbose_name=_('is public'))
    is_active = models.BooleanField(default=True, verbose_name=_('is active'))

    owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner'))
    bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry'))

    @property
    def type_of_geometry(self):
        return self.bounding_geometry.type_of_geometry

    @property
    def extent(self):
        return self.bounding_geometry.extent

    def __str__(self):
        return self.name

def _active_excerpts():
    return Excerpt.objects.filter(is_active=True).filter(
        bounding_geometry__bboxboundinggeometry__isnull=False
    )

def private_user_excerpts(user):
    return _active_excerpts().filter(is_public=False, owner=user)

def public_user_excerpts(user):
    return _active_excerpts().filter(is_public=True, owner=user)

def other_users_public_excerpts(user):
    return _active_excerpts().filter(is_public=True).exclude(owner=user)

Remove value which is already default

Remove value which is already default

Response:
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _

class Excerpt(models.Model):
    name = models.CharField(max_length=128, verbose_name=_('name'))
    is_public = models.BooleanField(default=False, verbose_name=_('is public'))
    is_active = models.BooleanField(default=True, verbose_name=_('is active'))

    owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner'))
    bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry'))

    @property
    def type_of_geometry(self):
        return self.bounding_geometry.type_of_geometry

    @property
    def extent(self):
        return self.bounding_geometry.extent

    def __str__(self):
        return self.name

def _active_excerpts():
    return Excerpt.objects.filter(is_active=True).filter(
        bounding_geometry__bboxboundinggeometry__isnull=False
    )

def private_user_excerpts(user):
    return _active_excerpts().filter(is_public=False, owner=user)

def public_user_excerpts(user):
    return _active_excerpts().filter(is_public=True, owner=user)

def other_users_public_excerpts(user):
    return _active_excerpts().filter(is_public=True).exclude(owner=user)

Prompt:
Remove value which is already default

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _

class Excerpt(models.Model):
    name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)
    is_public = models.BooleanField(default=False, verbose_name=_('is public'))
    is_active = models.BooleanField(default=True, verbose_name=_('is active'))

    owner = models.ForeignKey(User, related_name='excerpts', verbose_name=_('owner'))
    bounding_geometry = models.OneToOneField('BoundingGeometry', verbose_name=_('bounding geometry'))

    @property
    def type_of_geometry(self):
        return self.bounding_geometry.type_of_geometry

    @property
    def extent(self):
        return self.bounding_geometry.extent

    def __str__(self):
        return self.name

def _active_excerpts():
    return Excerpt.objects.filter(is_active=True).filter(
        bounding_geometry__bboxboundinggeometry__isnull=False
    )

def private_user_excerpts(user):
    return _active_excerpts().filter(is_public=False, owner=user)

def public_user_excerpts(user):
    return _active_excerpts().filter(is_public=True, owner=user)

def other_users_public_excerpts(user):
    return _active_excerpts().filter(is_public=True).exclude(owner=user)


from __future__ import unicode_literals

from django.core.urlresolvers import NoReverseMatch, reverse

def local_site_reverse(viewname, request=None, local_site_name=None,
                       local_site=None, args=None, kwargs=None,
                       *func_args, **func_kwargs):
    """Reverses a URL name, returning a working URL.

    This works much like Django's reverse(), but handles returning a
    localsite version of a URL when invoked with a request within a localsite.
    """
    assert not (local_site_name and local_site)

    if request or local_site_name or local_site:
        if local_site:
            local_site_name = local_site.name
        elif request and not local_site_name:
            local_site_name = getattr(request, '_local_site_name', None)

        if local_site_name:
            if args:
                new_args = [local_site_name] + args
                new_kwargs = kwargs
            else:
                new_args = args
                new_kwargs = {
                    'local_site_name': local_site_name,
                }

                if kwargs:
                    new_kwargs.update(kwargs)

            try:
                return reverse(viewname, args=new_args, kwargs=new_kwargs,
                               *func_args, **func_kwargs)
            except NoReverseMatch:
                # We'll try it again without those arguments.
                pass

    return reverse(viewname, args=args, kwargs=kwargs,
                   *func_args, **func_kwargs)

Response:
from __future__ import unicode_literals

from django.core.urlresolvers import NoReverseMatch, reverse

def local_site_reverse(viewname, request=None, local_site_name=None,
                       local_site=None, args=None, kwargs=None,
                       *func_args, **func_kwargs):
    """Reverses a URL name, returning a working URL.

    This works much like Django's reverse(), but handles returning a
    localsite version of a URL when invoked with a request within a localsite.
    """
    assert not (local_site_name and local_site)

    if request or local_site_name or local_site:
        if local_site:
            local_site_name = local_site.name
        elif request and not local_site_name:
            local_site_name = getattr(request, '_local_site_name', None)

        if local_site_name:
            if args:
                new_args = [local_site_name] + args
                new_kwargs = kwargs
            else:
                new_args = args
                new_kwargs = {
                    'local_site_name': local_site_name,
                }

                if kwargs:
                    new_kwargs.update(kwargs)

            try:
                return reverse(viewname, args=new_args, kwargs=new_kwargs,
                               *func_args, **func_kwargs)
            except NoReverseMatch:
                # We'll try it again without those arguments.
                pass

    return reverse(viewname, args=args, kwargs=kwargs,
                   *func_args, **func_kwargs)

Prompt:
Allow local_site_reverse to take an actual LocalSite.

local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.

Now, local_site_reverse can take a LocalSite. This saves a database
query, if one is already available, and simplifies calling code.

Reviewed at https://reviews.reviewboard.org/r/6302/

from __future__ import unicode_literals

from django.core.urlresolvers import NoReverseMatch, reverse

def local_site_reverse(viewname, request=None, local_site_name=None,
                       args=None, kwargs=None, *func_args, **func_kwargs):
    """Reverses a URL name, returning a working URL.

    This works much like Django's reverse(), but handles returning a
    localsite version of a URL when invoked with a request within a localsite.
    """
    if request or local_site_name:
        if request and not local_site_name:
            local_site_name = getattr(request, '_local_site_name', None)

        if local_site_name:
            if args:
                new_args = [local_site_name] + args
                new_kwargs = kwargs
            else:
                new_args = args
                new_kwargs = {
                    'local_site_name': local_site_name,
                }

                if kwargs:
                    new_kwargs.update(kwargs)

            try:
                return reverse(viewname, args=new_args, kwargs=new_kwargs,
                               *func_args, **func_kwargs)
            except NoReverseMatch:
                # We'll try it again without those arguments.
                pass

    return reverse(viewname, args=args, kwargs=kwargs,
                   *func_args, **func_kwargs)


class Symbol(str):
    pass

# lists
class List(list):
    def __add__(self, rhs):
        return List(list.__add__(self, rhs))

    def __getitem__(self, i):
        if type(i) == slice:
            return List(list.__getitem__(self, i))
        elif i >= len(self):
            return None
        else:
            return list.__getitem__(self, i)

    def __getslice__(self, *a):
        return List(self.__getslice__(self, *a))

    @classmethod
    def is_list(cls, obj):
        return isinstance(obj, cls)

class Boolean(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_true(cls, exp):
        return isinstance(exp, cls) and bool(exp)

    @classmethod
    def is_false(cls, exp):
        return isinstance(exp, cls) and not bool(exp)

class Nil(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_nil(cls, exp):
        return isinstance(exp, cls)

class Atom(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_atom(cls, exp):
        return isinstance(exp, Atom)

Create Symbol, List, Boolean, Nil and Atom types.

Response:
class Symbol(str):
    pass

# lists
class List(list):
    def __add__(self, rhs):
        return List(list.__add__(self, rhs))

    def __getitem__(self, i):
        if type(i) == slice:
            return List(list.__getitem__(self, i))
        elif i >= len(self):
            return None
        else:
            return list.__getitem__(self, i)

    def __getslice__(self, *a):
        return List(self.__getslice__(self, *a))

    @classmethod
    def is_list(cls, obj):
        return isinstance(obj, cls)

class Boolean(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_true(cls, exp):
        return isinstance(exp, cls) and bool(exp)

    @classmethod
    def is_false(cls, exp):
        return isinstance(exp, cls) and not bool(exp)

class Nil(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_nil(cls, exp):
        return isinstance(exp, cls)

class Atom(object):
    def __init__(self, val):
        self.val = val

    @classmethod
    def is_atom(cls, exp):
        return isinstance(exp, Atom)

Prompt: Create Symbol, List, Boolean, Nil and Atom types.


import os
from setuptools import setup, find_packages
import uuid

from jirafs_list_table import __version__ as version_string

requirements_path = os.path.join(
    os.path.dirname(__file__),
    'requirements.txt',
)
try:
    from pip.req import parse_requirements
    requirements = [
        str(req.req) for req in parse_requirements(
            requirements_path,
            session=uuid.uuid1()
        )
    ]
except (ImportError, AttributeError, ValueError, TypeError):
    requirements = []
    with open(requirements_path, 'r') as in_:
        requirements = [
            req for req in in_.readlines()
            if not req.startswith('-')
            and not req.startswith('#')
        ]

setup(
    name='jirafs_list_table',
    version=version_string,
    url='https://github.com/coddingtonbear/jirafs-list-table',
    description="Make simple tables in JIRA more easily by using a simple list-based syntax.",
    author='Adam Coddington',
    author_email='me@adamcoddington.net',
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
    ],
    install_requires=requirements,
    include_package_data=True,
    packages=find_packages(),
    entry_points={
        'jirafs_plugins': [
            'list_table = jirafs_list_table.plugin:Plugin',
        ]
    },
)

Use the proper entry point name.

Use the proper entry point name.

Response:
import os
from setuptools import setup, find_packages
import uuid

from jirafs_list_table import __version__ as version_string

requirements_path = os.path.join(
    os.path.dirname(__file__),
    'requirements.txt',
)
try:
    from pip.req import parse_requirements
    requirements = [
        str(req.req) for req in parse_requirements(
            requirements_path,
            session=uuid.uuid1()
        )
    ]
except (ImportError, AttributeError, ValueError, TypeError):
    requirements = []
    with open(requirements_path, 'r') as in_:
        requirements = [
            req for req in in_.readlines()
            if not req.startswith('-')
            and not req.startswith('#')
        ]

setup(
    name='jirafs_list_table',
    version=version_string,
    url='https://github.com/coddingtonbear/jirafs-list-table',
    description="Make simple tables in JIRA more easily by using a simple list-based syntax.",
    author='Adam Coddington',
    author_email='me@adamcoddington.net',
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
    ],
    install_requires=requirements,
    include_package_data=True,
    packages=find_packages(),
    entry_points={
        'jirafs_plugins': [
            'list_table = jirafs_list_table.plugin:Plugin',
        ]
    },
)

Prompt:
Use the proper entry point name.

import os
from setuptools import setup, find_packages
import uuid

from jirafs_list_table import __version__ as version_string

requirements_path = os.path.join(
    os.path.dirname(__file__),
    'requirements.txt',
)
try:
    from pip.req import parse_requirements
    requirements = [
        str(req.req) for req in parse_requirements(
            requirements_path,
            session=uuid.uuid1()
        )
    ]
except (ImportError, AttributeError, ValueError, TypeError):
    requirements = []
    with open(requirements_path, 'r') as in_:
        requirements = [
            req for req in in_.readlines()
            if not req.startswith('-')
            and not req.startswith('#')
        ]

setup(
    name='jirafs_list_table',
    version=version_string,
    url='https://github.com/coddingtonbear/jirafs-list-table',
    description="Make simple tables in JIRA more easily by using a simple list-based syntax.",
    author='Adam Coddington',
    author_email='me@adamcoddington.net',
    classifiers=[
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3',
    ],
    install_requires=requirements,
    include_package_data=True,
    packages=find_packages(),
    entry_points={
        'jirafs_list_table': [
            'list_table = jirafs_list_table.plugin:Plugin',
        ]
    },
)


#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'

import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen

from shell_quoting import ShellQuoted

# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
    return {
        'depends_on': [folly, proxygen, fbthrift],
        'steps': [
            builder.fb_github_project_workdir('bistro/bistro'),
            builder.step('Build bistro', [
                # Future: should this share some code with `cmake_install()`?
                builder.run(ShellQuoted(
                    'PATH="$PATH:"{p}/bin '
                    'TEMPLATES_PATH={p}/include/thrift/templates '
                    './cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
                ).format(p=builder.option('prefix'))),
                builder.workdir('cmake/Debug'),
                builder.parallel_make(),
            ]),
            builder.step('Run bistro tests', [
                builder.run(ShellQuoted('ctest')),
            ]),
        ]
    }

config = {
    'github_project': 'facebook/bistro',
    'fbcode_builder_spec': fbcode_builder_spec,
}

Fix overquoting of thrift paths

Response:
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'

import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen

from shell_quoting import ShellQuoted

# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
    return {
        'depends_on': [folly, proxygen, fbthrift],
        'steps': [
            builder.fb_github_project_workdir('bistro/bistro'),
            builder.step('Build bistro', [
                # Future: should this share some code with `cmake_install()`?
                builder.run(ShellQuoted(
                    'PATH="$PATH:"{p}/bin '
                    'TEMPLATES_PATH={p}/include/thrift/templates '
                    './cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
                ).format(p=builder.option('prefix'))),
                builder.workdir('cmake/Debug'),
                builder.parallel_make(),
            ]),
            builder.step('Run bistro tests', [
                builder.run(ShellQuoted('ctest')),
            ]),
        ]
    }

config = {
    'github_project': 'facebook/bistro',
    'fbcode_builder_spec': fbcode_builder_spec,
}

Prompt:
oss: Fix overquoting of thrift paths

Summary: This overquotes the paths in travis builds. This will fix the opensource broken builds

Reviewed By: snarkmaster

Differential Revision: D5923131

fbshipit-source-id: 1ff3e864107b0074fc85e8a45a37455430cf4ba3

#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'

import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen

from shell_quoting import ShellQuoted

# Since Bistro doesn't presently have an "install" target, there is no
# point in having its spec in the shared spec directory.
def fbcode_builder_spec(builder):
    return {
        'depends_on': [folly, proxygen, fbthrift],
        'steps': [
            builder.fb_github_project_workdir('bistro/bistro'),
            builder.step('Build bistro', [
                # Future: should this share some code with `cmake_install()`?
                builder.run(ShellQuoted(
                    'PATH="$PATH:{p}/bin" '
                    'TEMPLATES_PATH="{p}/include/thrift/templates" '
                    './cmake/run-cmake.sh Debug -DCMAKE_INSTALL_PREFIX={p}'
                ).format(p=builder.option('prefix'))),
                builder.workdir('cmake/Debug'),
                builder.parallel_make(),
            ]),
            builder.step('Run bistro tests', [
                builder.run(ShellQuoted('ctest')),
            ]),
        ]
    }

config = {
    'github_project': 'facebook/bistro',
    'fbcode_builder_spec': fbcode_builder_spec,
}


from django.db import models
from django.utils.translation import gettext_lazy as _

class Currency(models.Model):
    code = models.CharField(_('code'), max_length=3)
    name = models.CharField(_('name'), max_length=35)
    symbol = models.CharField(_('symbol'), max_length=4, blank=True)
    factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4,
        help_text=_('Specifies the difference of the currency to default one.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('The currency will be available.'))
    is_base = models.BooleanField(_('base'), default=False,
        help_text=_('Make this the base currency against which rates are calculated.'))
    is_default = models.BooleanField(_('default'), default=False,
        help_text=_('Make this the default user currency.'))

    class Meta:
        ordering = ('name', )
        verbose_name = _('currency')
        verbose_name_plural = _('currencies')

    def __unicode__(self):
        return self.code

    def save(self, **kwargs):
        # Make sure the base and default currencies are unique
        if self.is_base:
            Currency.objects.filter(is_base=True).update(is_base=False)
        if self.is_default:
            Currency.objects.filter(is_default=True).update(is_default=False)
        super(Currency, self).save(**kwargs)

Order currencies by name by default

Order currencies by name by default

Response:
from django.db import models
from django.utils.translation import gettext_lazy as _

class Currency(models.Model):
    code = models.CharField(_('code'), max_length=3)
    name = models.CharField(_('name'), max_length=35)
    symbol = models.CharField(_('symbol'), max_length=4, blank=True)
    factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4,
        help_text=_('Specifies the difference of the currency to default one.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('The currency will be available.'))
    is_base = models.BooleanField(_('base'), default=False,
        help_text=_('Make this the base currency against which rates are calculated.'))
    is_default = models.BooleanField(_('default'), default=False,
        help_text=_('Make this the default user currency.'))

    class Meta:
        ordering = ('name', )
        verbose_name = _('currency')
        verbose_name_plural = _('currencies')

    def __unicode__(self):
        return self.code

    def save(self, **kwargs):
        # Make sure the base and default currencies are unique
        if self.is_base:
            Currency.objects.filter(is_base=True).update(is_base=False)
        if self.is_default:
            Currency.objects.filter(is_default=True).update(is_default=False)
        super(Currency, self).save(**kwargs)

Prompt:
Order currencies by name by default

from django.db import models
from django.utils.translation import gettext_lazy as _

class Currency(models.Model):
    code = models.CharField(_('code'), max_length=3)
    name = models.CharField(_('name'), max_length=35)
    symbol = models.CharField(_('symbol'), max_length=4, blank=True)
    factor = models.DecimalField(_('factor'), max_digits=10, decimal_places=4,
        help_text=_('Specifies the difference of the currency to default one.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('The currency will be available.'))
    is_base = models.BooleanField(_('base'), default=False,
        help_text=_('Make this the base currency against which rates are calculated.'))
    is_default = models.BooleanField(_('default'), default=False,
        help_text=_('Make this the default user currency.'))

    class Meta:
        verbose_name = _('currency')
        verbose_name_plural = _('currencies')

    def __unicode__(self):
        return self.code

    def save(self, **kwargs):
        # Make sure the base and default currencies are unique
        if self.is_base:
            Currency.objects.filter(is_base=True).update(is_base=False)
        if self.is_default:
            Currency.objects.filter(is_default=True).update(is_default=False)
        super(Currency, self).save(**kwargs)


#!/usr/bin/env python

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist bdist_wininst upload -r pypi')
    sys.exit()

with open('README.rst') as f:
    readme = f.read()
with open('LICENSE') as f:
    license = f.read()

setup(
    name='django-rest-surveys',
    version='0.1.0',
    description='A RESTful backend for giving surveys.',
    long_description=readme,
    author='Designlab',
    author_email='hello@trydesignlab.com',
    url='https://github.com/danxshap/django-rest-surveys',
    packages=['rest_surveys'],
    package_data={'': ['LICENSE']},
    package_dir={'rest_surveys': 'rest_surveys'},
    install_requires=['Django', 'django-inline-ordering'],
    license=license,
)

Response:
#!/usr/bin/env python

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist bdist_wininst upload -r pypi')
    sys.exit()

with open('README.rst') as f:
    readme = f.read()
with open('LICENSE') as f:
    license = f.read()

setup(
    name='django-rest-surveys',
    version='0.1.0',
    description='A RESTful backend for giving surveys.',
    long_description=readme,
    author='Designlab',
    author_email='hello@trydesignlab.com',
    url='https://github.com/danxshap/django-rest-surveys',
    packages=['rest_surveys'],
    package_data={'': ['LICENSE']},
    package_dir={'rest_surveys': 'rest_surveys'},
    install_requires=['Django', 'django-inline-ordering'],
    license=license,
)

Prompt:
Remove Django REST Framework from dependencies

#!/usr/bin/env python

import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist bdist_wininst upload -r pypi')
    sys.exit()

with open('README.rst') as f:
    readme = f.read()
with open('LICENSE') as f:
    license = f.read()

setup(
    name='django-rest-surveys',
    version='0.1.0',
    description='A RESTful backend for giving surveys.',
    long_description=readme,
    author='Designlab',
    author_email='hello@trydesignlab.com',
    url='https://github.com/danxshap/django-rest-surveys',
    packages=['rest_surveys'],
    package_data={'': ['LICENSE']},
    package_dir={'rest_surveys': 'rest_surveys'},
    install_requires=['Django', 'djangorestframework', 'django-inline-ordering'],
    license=license,
)


"""
Create an ANDS RIF-CS XML file.

Links
-----

- http://ands.org.au/guides/cpguide/cpgrifcs.html

- http://ands.org.au/resource/rif-cs.html

- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
"""

import logging
import os

from settings import (
	ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_XML_START, ANDS_XML_STOP
)

logger = logging.getLogger(__name__)

def main():
	with open(ANDS_XML_FILE_NAME, 'w') as w:
		w.write(ANDS_XML_START)

		for file_path in os.listdir(ANDS_XML_FOLDER_PATH):
			with open(file_path) as r:
				w.write(r.read())

		w.write(ANDS_XML_STOP)

if '__main__' == __name__:
	logging.basicConfig(level=logging.DEBUG)

	main()

Fix links in ANDS RIF-CS script

Fix links in ANDS RIF-CS script

Response:
"""
Create an ANDS RIF-CS XML file.

Links
-----

- http://ands.org.au/guides/cpguide/cpgrifcs.html

- http://ands.org.au/resource/rif-cs.html

- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
"""

import logging
import os

from settings import (
	ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_XML_START, ANDS_XML_STOP
)

logger = logging.getLogger(__name__)

def main():
	with open(ANDS_XML_FILE_NAME, 'w') as w:
		w.write(ANDS_XML_START)

		for file_path in os.listdir(ANDS_XML_FOLDER_PATH):
			with open(file_path) as r:
				w.write(r.read())

		w.write(ANDS_XML_STOP)

if '__main__' == __name__:
	logging.basicConfig(level=logging.DEBUG)

	main()

Prompt:
Fix links in ANDS RIF-CS script

"""
Create an ANDS RIF-CS XML file.

Links
-----

- http://ands.org.au/guides/cpguide/cpgrifcs.html

- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html

- http://www.ands.org.au/resource/rif-cs.html
"""

import logging
import os

from settings import (
	ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_XML_START, ANDS_XML_STOP
)

logger = logging.getLogger(__name__)

def main():
	with open(ANDS_XML_FILE_NAME, 'w') as w:
		w.write(ANDS_XML_START)

		for file_path in os.listdir(ANDS_XML_FOLDER_PATH):
			with open(file_path) as r:
				w.write(r.read())

		w.write(ANDS_XML_STOP)

if '__main__' == __name__:
	logging.basicConfig(level=logging.DEBUG)

	main()


from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
    url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
    url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
    url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)

Response:
from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
    url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
    url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
    url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)

Prompt:
Change url and views for login/logout to django Defaults

from django.conf.urls import patterns, url
from django.contrib import auth

urlpatterns = patterns('',
    url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
    url(r'^search/(?P<name>.*)/$', 'members.views.search', name='search'),
    url(r'^archive/$', 'members.views.archive_student_council', name='archive_student_council'),
    url(r'^profile/$', 'members.views.user_projects', name='user-projects'),
)


# Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
#    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.

FIREWALL = 'FIREWALL'
FIREWALL_V2 = 'FIREWALL_V2'

# Constants for "topics"
FIREWALL_PLUGIN = 'q-firewall-plugin'
FW_AGENT = 'firewall_agent'
FIREWALL_RULE_LIST = 'firewall_rule_list'

Remove unused constant for topics

Response:
# Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
#    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.

FIREWALL = 'FIREWALL'
FIREWALL_V2 = 'FIREWALL_V2'

# Constants for "topics"
FIREWALL_PLUGIN = 'q-firewall-plugin'
FW_AGENT = 'firewall_agent'
FIREWALL_RULE_LIST = 'firewall_rule_list'

Prompt:
Remove unused constant for topics

While reading the code, I found "L3_AGENT" topic is defined
but never be used.

Change-Id: I9b6da61f9fe5224d2c25bbe7cc55fd508b4e240f

# Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
#    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.

FIREWALL = 'FIREWALL'
FIREWALL_V2 = 'FIREWALL_V2'

# Constants for "topics"
FIREWALL_PLUGIN = 'q-firewall-plugin'
L3_AGENT = 'l3_agent'
FW_AGENT = 'firewall_agent'
FIREWALL_RULE_LIST = 'firewall_rule_list'


# Copyright (c) 2017, CNRS-LAAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Simple demo showcasing how to use the fire propagation module and how to display the result"""
import matplotlib.pyplot as plt

from fire_rs.firemodel import propagation
from fire_rs.geodata.display import GeoDataDisplay, plot_ignition_point
from fire_rs.geodata.geo_data import TimedPoint

if __name__ == "__main__":
    area = ((480060.0, 485060.0), (6210074.0, 6215074.0))
    env = propagation.Environment(area, wind_speed=5., wind_dir=0.)
    ignition_point = TimedPoint(area[0][0] + 1000.0, area[1][0] + 2000.0, 0)
    fire = propagation.propagate_from_points(env, ignition_point, 3000)

    gdd = GeoDataDisplay.pyplot_figure(env.raster.combine(fire.ignitions().slice(["ignition"])))
    gdd.draw_elevation_shade(with_colorbar=False)
    gdd.draw_wind_quiver()
    gdd.draw_ignition_contour(with_labels=True)
    plot_ignition_point(gdd.axis, ignition_point)
    plt.plot(block=True)

Add python script that plots the results of a fire propagation

Response:
# Copyright (c) 2017, CNRS-LAAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Simple demo showcasing how to use the fire propagation module and how to display the result"""
import matplotlib.pyplot as plt

from fire_rs.firemodel import propagation
from fire_rs.geodata.display import GeoDataDisplay, plot_ignition_point
from fire_rs.geodata.geo_data import TimedPoint

if __name__ == "__main__":
    area = ((480060.0, 485060.0), (6210074.0, 6215074.0))
    env = propagation.Environment(area, wind_speed=5., wind_dir=0.)
    ignition_point = TimedPoint(area[0][0] + 1000.0, area[1][0] + 2000.0, 0)
    fire = propagation.propagate_from_points(env, ignition_point, 3000)

    gdd = GeoDataDisplay.pyplot_figure(env.raster.combine(fire.ignitions().slice(["ignition"])))
    gdd.draw_elevation_shade(with_colorbar=False)
    gdd.draw_wind_quiver()
    gdd.draw_ignition_contour(with_labels=True)
    plot_ignition_point(gdd.axis, ignition_point)
    plt.plot(block=True)

Prompt: Add python script that plots the results of a fire propagation


#!/usr/bin/env

from pupa.core import db

for orga in db.organizations.find({"classification": "committee"}):
    memberships = db.memberships.find({
        "organization_id": orga['_id'],
        "end_date": None
    }).count()
    print memberships, orga['jurisdiction_id'], orga['name']

Add a counter to help with debugging.

Add a counter to help with debugging.

Response:
#!/usr/bin/env

from pupa.core import db

for orga in db.organizations.find({"classification": "committee"}):
    memberships = db.memberships.find({
        "organization_id": orga['_id'],
        "end_date": None
    }).count()
    print memberships, orga['jurisdiction_id'], orga['name']

Prompt: Add a counter to help with debugging.


from nose.tools import *
from exercises import ex12
try:
    from io import StringIO
except:
    from StringIO import StringIO
import sys

def test_histogram():
    '''
    Test our histogram output is correct
    '''

    std_out = sys.stdout
    result = StringIO()
    sys.stdout = result

    test_histogram = ex12.histogram([1, 2, 3])
    sys.stdout = std_out

    result_string = result.getvalue()

    assert_equal(result_string, '*\n**\n***\n')

Response:
from nose.tools import *
from exercises import ex12
try:
    from io import StringIO
except:
    from StringIO import StringIO
import sys

def test_histogram():
    '''
    Test our histogram output is correct
    '''

    std_out = sys.stdout
    result = StringIO()
    sys.stdout = result

    test_histogram = ex12.histogram([1, 2, 3])
    sys.stdout = std_out

    result_string = result.getvalue()

    assert_equal(result_string, '*\n**\n***\n')

Prompt:
Update ex12 test so it actually reads output.

from nose.tools import *
from exercises import ex12

def test_histogram():
    '''
    Test our histogram output is correct
    '''

    test_histogram = ex12.histogram([1, 2, 3])
#    assert_equal(test_histogram, '*\n**\n***\n')


"""use jsonb for strokes

Revision ID: 4e1d46e710a2
Revises: 5a7ec3d139df
Create Date: 2015-05-25 19:47:45.924915

"""
from alembic.op import execute

# revision identifiers, used by Alembic.
revision = '4e1d46e710a2'
down_revision = '5a7ec3d139df'
branch_labels = None
depends_on = None

def upgrade():
    execute('ALTER TABLE canvases ALTER strokes TYPE JSONB USING strokes::JSONB')

def downgrade():
    execute('ALTER TABLE canvases ALTER strokes TYPE JSON USING strokes::JSON')

Use JSONB for storing strokes

Use JSONB for storing strokes

Response:
"""use jsonb for strokes

Revision ID: 4e1d46e710a2
Revises: 5a7ec3d139df
Create Date: 2015-05-25 19:47:45.924915

"""
from alembic.op import execute

# revision identifiers, used by Alembic.
revision = '4e1d46e710a2'
down_revision = '5a7ec3d139df'
branch_labels = None
depends_on = None

def upgrade():
    execute('ALTER TABLE canvases ALTER strokes TYPE JSONB USING strokes::JSONB')

def downgrade():
    execute('ALTER TABLE canvases ALTER strokes TYPE JSON USING strokes::JSON')

Prompt: Use JSONB for storing strokes


# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import itertools

import numpy as np

def make_feature_vec(state_ranges, order):
    """

    Arguments:
        state_ranges – (2, n_dims) minima and maxima of possible state values
        n_acts – int, number of actions that can happen
        order – int, order of the Fourier basis

    Credits:
     - http://psthomas.com/papers/Konidaris2011a.pdf
     - https://github.com/amarack/python-rl/blob/master/pyrl/basis/fourier.py
    """
    n_dims    = state_ranges[1]
    n_entries = (n_dims + 1)**order

    # All entries from cartesian product {0, …, order+1}^n_dims.
    c_matrix = np.array(
                   list( itertools.product(range(order+1), repeat=n_dims) ),
                   dtype=np.int32)

    def feature_vec_dot_inner(state, action, weights):
        """

        Arguments:
            action - int in {0, …, number of possible actions}
        """

        # Note: With the default C/row-major format it should be faster to put
        # the c₁, c₂, … in the rows of the matrix.

        # Bring all state input into the range [0, 1], the input range of the
        # Fourier basis functions.
        normalized_state = (state - state_ranges[0]) \
                               / np.diff(state_ranges, axis=1)

        # Dot products of the feature vector with every c. → shape (n_entries,)
        dot_prods = np.dot(c_matrix, normalized_state.transpose())[:,0]

        # Apply Fourier basis functions.
        feature_v = np.cos(np.pi * dot_prods)

        # Sum up results, weighted, to give Fourier val.
        return np.dot(weights[action * n_entries:(action + 1) * n_entries - 1],\
                      feature_v)

    return feature_vec_dot_inner

Add untested Fourier linear function approximator

Response:
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import itertools

import numpy as np

def make_feature_vec(state_ranges, order):
    """

    Arguments:
        state_ranges – (2, n_dims) minima and maxima of possible state values
        n_acts – int, number of actions that can happen
        order – int, order of the Fourier basis

    Credits:
     - http://psthomas.com/papers/Konidaris2011a.pdf
     - https://github.com/amarack/python-rl/blob/master/pyrl/basis/fourier.py
    """
    n_dims    = state_ranges[1]
    n_entries = (n_dims + 1)**order

    # All entries from cartesian product {0, …, order+1}^n_dims.
    c_matrix = np.array(
                   list( itertools.product(range(order+1), repeat=n_dims) ),
                   dtype=np.int32)

    def feature_vec_dot_inner(state, action, weights):
        """

        Arguments:
            action - int in {0, …, number of possible actions}
        """

        # Note: With the default C/row-major format it should be faster to put
        # the c₁, c₂, … in the rows of the matrix.

        # Bring all state input into the range [0, 1], the input range of the
        # Fourier basis functions.
        normalized_state = (state - state_ranges[0]) \
                               / np.diff(state_ranges, axis=1)

        # Dot products of the feature vector with every c. → shape (n_entries,)
        dot_prods = np.dot(c_matrix, normalized_state.transpose())[:,0]

        # Apply Fourier basis functions.
        feature_v = np.cos(np.pi * dot_prods)

        # Sum up results, weighted, to give Fourier val.
        return np.dot(weights[action * n_entries:(action + 1) * n_entries - 1],\
                      feature_v)

    return feature_vec_dot_inner

Prompt: Add untested Fourier linear function approximator


from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView

class QuoteCreateView(CreateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self):
        form = super(QuoteCreateView, self).get_form()
        # form.fields['category'].queryset = Category.objects.all()
        # form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteCreateView, self).form_valid(form)

class QuoteEditView(UpdateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self):
        form = super(QuoteEditView, self).get_form()
        form.fields['category'].queryset = Category.objects.all()
        form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteEditView, self).form_valid(form)

Update view for basic quote form.

Update view for basic quote form.

Response:
from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView

class QuoteCreateView(CreateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self):
        form = super(QuoteCreateView, self).get_form()
        # form.fields['category'].queryset = Category.objects.all()
        # form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteCreateView, self).form_valid(form)

class QuoteEditView(UpdateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self):
        form = super(QuoteEditView, self).get_form()
        form.fields['category'].queryset = Category.objects.all()
        form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteEditView, self).form_valid(form)

Prompt:
Update view for basic quote form.

from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView

class QuoteCreateView(CreateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self, form):
        form = super(QuoteCreateView, self).get_form()
        form.fields['category'].queryset = Category.objects.all()
        form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteCreateView, self).form_valid(form)

class QuoteEditView(UpdateView):
    model = Quote
    fields = ['name']
    template_name = 'quote.html'
    success_url = '/'

    def get_form(self, form):
        form = super(QuoteEditView, self).get_form()
        form.fields['category'].queryset = Category.objects.all()
        form.fields['products'].queryset = Product.objects.all()
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(QuoteEditView, self).form_valid(form)


#!/usr/bin/env python

import pygst
pygst.require("0.10")
import gst
import gtk

class Pipeline(object):
    def __init__(self):
        self.pipeline = gst.Pipeline("pipe")
        self.webcam = gst.element_factory_make("v4l2src", "webcam")
        self.webcam.set_property("device", "/dev/video0")
        self.pipeline.add(self.webcam)
        self.caps_filter = gst.element_factory_make("capsfilter", "caps_filter")
        caps = gst.Caps("video/x-raw-yuv,width=640,height=480,framerate=30/1")
        self.caps_filter.set_property("caps", caps)
        self.pipeline.add(self.caps_filter)

        self.sink = gst.element_factory_make("xvimagesink", "sink")
        self.pipeline.add(self.sink)

        self.webcam.link(self.caps_filter)
        self.caps_filter.link(self.sink)
        self.pipeline.set_state(gst.STATE_PLAYING)

start = Pipeline()
gtk.main()

Add a video pipeline example.

Add a video pipeline example.

Response:
#!/usr/bin/env python

import pygst
pygst.require("0.10")
import gst
import gtk

class Pipeline(object):
    def __init__(self):
        self.pipeline = gst.Pipeline("pipe")
        self.webcam = gst.element_factory_make("v4l2src", "webcam")
        self.webcam.set_property("device", "/dev/video0")
        self.pipeline.add(self.webcam)
        self.caps_filter = gst.element_factory_make("capsfilter", "caps_filter")
        caps = gst.Caps("video/x-raw-yuv,width=640,height=480,framerate=30/1")
        self.caps_filter.set_property("caps", caps)
        self.pipeline.add(self.caps_filter)

        self.sink = gst.element_factory_make("xvimagesink", "sink")
        self.pipeline.add(self.sink)

        self.webcam.link(self.caps_filter)
        self.caps_filter.link(self.sink)
        self.pipeline.set_state(gst.STATE_PLAYING)

start = Pipeline()
gtk.main()

Prompt: Add a video pipeline example.


import os
import logging
from socket import gethostbyname, gethostname

from kaa.base import ipc
from client import *
from server import *

__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]

# connected client object
_client = None

def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
    """
    """
    global _client

    if _client:
        return _client

    if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
       address.split(':')[0] != gethostbyname(gethostname()):
        # epg is remote:  host:port
        if address.find(':') >= 0:
            host, port = address.split(':', 1)
        else:
            host = address
            port = DEFAULT_EPG_PORT

        # create socket, pass it to client
        _client = GuideClient((host, int(port)))

    else:
        # EPG is local, only use unix socket

        # get server filename
        server = os.path.join(os.path.dirname(__file__), 'server.py')

        _client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
                              2, GuideClient, "epg")

    return _client

Response:
import os
import logging
from socket import gethostbyname, gethostname

from kaa.base import ipc
from client import *
from server import *

__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]

# connected client object
_client = None

def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
    """
    """
    global _client

    if _client:
        return _client

    if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
       address.split(':')[0] != gethostbyname(gethostname()):
        # epg is remote:  host:port
        if address.find(':') >= 0:
            host, port = address.split(':', 1)
        else:
            host = address
            port = DEFAULT_EPG_PORT

        # create socket, pass it to client
        _client = GuideClient((host, int(port)))

    else:
        # EPG is local, only use unix socket

        # get server filename
        server = os.path.join(os.path.dirname(__file__), 'server.py')

        _client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
                              2, GuideClient, "epg")

    return _client

Prompt:
Fix starting inet client when should use unix socket instead.
Fix port to be int.

git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e

import os
import logging
from socket import gethostbyname, gethostname

from kaa.base import ipc
from client import *
from server import *

__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]

# connected client object
_client = None

def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.log', loglevel=logging.INFO):
    """
    """
    global _client

    if _client:
        return _client

    if address.split(':')[0] not in ['127.0.0.1', '0.0.0.0'] and \
       address != gethostbyname(gethostname()):
        # epg is remote:  host:port
        if address.find(':') >= 0:
            host, port = address.split(':', 1)
        else:
            host = address
            port = DEFAULT_EPG_PORT

        # create socket, pass it to client
        _client = GuideClient((host, port))

    else:
        # EPG is local, only use unix socket

        # get server filename
        server = os.path.join(os.path.dirname(__file__), 'server.py')

        _client = ipc.launch([server, logfile, str(loglevel), epgdb, address],
                              2, GuideClient, "epg")

    return _client


#!/usr/bin/env python
import argparse
import os
import logging
import pprint
import sys
import yaml

# HACK
_file = os.path.abspath(__file__)
_dir = os.path.dirname(os.path.dirname(_file))
sys.path.insert(0, _dir)
from BoogieRunner.ResultType import ResultType

def main(args):
    resultTypes = [ r.name for r in list(ResultType)] # Get list of ResultTypes as strings
    logging.basicConfig(level=logging.DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument('result_yml', type=argparse.FileType('r'), default='-')
    parser.add_argument('result_type', choices=resultTypes)
    pargs = parser.parse_args(args)

    results = yaml.load(pargs.result_yml)

    assert isinstance(results, list)

    # Get out of requested type
    resultCode = ResultType[pargs.result_type].value

    count = 0
    collected = [ ]
    for r in results:
        if r['result'] == resultCode:
            count += 1
            collected.append(r)

    logging.info('Count of type {} : {}'.format(pargs.result_type, count))

    print(yaml.dump(collected, default_flow_style=False))

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Add script to filter result by result type.

Response:
#!/usr/bin/env python
import argparse
import os
import logging
import pprint
import sys
import yaml

# HACK
_file = os.path.abspath(__file__)
_dir = os.path.dirname(os.path.dirname(_file))
sys.path.insert(0, _dir)
from BoogieRunner.ResultType import ResultType

def main(args):
    resultTypes = [ r.name for r in list(ResultType)] # Get list of ResultTypes as strings
    logging.basicConfig(level=logging.DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument('result_yml', type=argparse.FileType('r'), default='-')
    parser.add_argument('result_type', choices=resultTypes)
    pargs = parser.parse_args(args)

    results = yaml.load(pargs.result_yml)

    assert isinstance(results, list)

    # Get out of requested type
    resultCode = ResultType[pargs.result_type].value

    count = 0
    collected = [ ]
    for r in results:
        if r['result'] == resultCode:
            count += 1
            collected.append(r)

    logging.info('Count of type {} : {}'.format(pargs.result_type, count))

    print(yaml.dump(collected, default_flow_style=False))

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

Prompt: Add script to filter result by result type.


import sys

import progressbar
from django.core.paginator import Paginator

from website.app import setup_django
setup_django()

from website.search.search import update_file
from osf.models import QuickFilesNode

PAGE_SIZE = 50

def reindex_quickfiles(dry):
    qs = QuickFilesNode.objects.all().order_by('id')
    count = qs.count()
    paginator = Paginator(qs, PAGE_SIZE)

    progress_bar = progressbar.ProgressBar(maxval=count).start()
    n_processed = 0
    for page_num in paginator.page_range:
        page = paginator.page(page_num)
        for quickfiles in page.object_list:
            for file_ in quickfiles.files.all():
                if not dry:
                    update_file(file_)
        n_processed += len(page.object_list)
        progress_bar.update(n_processed)

if __name__ == '__main__':
    dry = '--dry' in sys.argv
    reindex_quickfiles(dry=dry)

Add script to re-index users' files in quickfiles nodes

Response:
import sys

import progressbar
from django.core.paginator import Paginator

from website.app import setup_django
setup_django()

from website.search.search import update_file
from osf.models import QuickFilesNode

PAGE_SIZE = 50

def reindex_quickfiles(dry):
    qs = QuickFilesNode.objects.all().order_by('id')
    count = qs.count()
    paginator = Paginator(qs, PAGE_SIZE)

    progress_bar = progressbar.ProgressBar(maxval=count).start()
    n_processed = 0
    for page_num in paginator.page_range:
        page = paginator.page(page_num)
        for quickfiles in page.object_list:
            for file_ in quickfiles.files.all():
                if not dry:
                    update_file(file_)
        n_processed += len(page.object_list)
        progress_bar.update(n_processed)

if __name__ == '__main__':
    dry = '--dry' in sys.argv
    reindex_quickfiles(dry=dry)

Prompt: Add script to re-index users' files in quickfiles nodes


#  IATI Data Quality, tools for Data QA on IATI-formatted  publications
#  by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
#  Copyright (C) 2013  Publish What You Fund
#
#  This programme is free software; you may redistribute and/or modify
#  it under the terms of the GNU Affero General Public License v3.0

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)

import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey

Add survey controller to routes

Add survey controller to routes

Response:
#  IATI Data Quality, tools for Data QA on IATI-formatted  publications
#  by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
#  Copyright (C) 2013  Publish What You Fund
#
#  This programme is free software; you may redistribute and/or modify
#  it under the terms of the GNU Affero General Public License v3.0

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)

import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey

Prompt:
Add survey controller to routes

#  IATI Data Quality, tools for Data QA on IATI-formatted  publications
#  by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
#  Copyright (C) 2013  Publish What You Fund
#
#  This programme is free software; you may redistribute and/or modify
#  it under the terms of the GNU Affero General Public License v3.0

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)

import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes


from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup

class PersonIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    url = indexes.CharField(model_attr='url')

    def get_model(self):
        return Person

class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    homepage_url = indexes.CharField(model_attr='homepage_url')
    mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
    sourcecode_url = indexes.CharField(model_attr='sourcecode_url')

    def get_model(self):
        return Project

class WorkingGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    incubation = indexes.BooleanField(model_attr='incubation')

    def get_model(self):
        return WorkingGroup

class NetworkGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    homepage_url = indexes.CharField(model_attr='homepage_url')
    mailinglist_url = indexes.CharField(model_attr='mailinglist_url')

    def get_model(self):
        return NetworkGroup

Fix references to old model fields

Response:
from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup

class PersonIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    url = indexes.CharField(model_attr='url')

    def get_model(self):
        return Person

class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    homepage_url = indexes.CharField(model_attr='homepage_url')
    mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
    sourcecode_url = indexes.CharField(model_attr='sourcecode_url')

    def get_model(self):
        return Project

class WorkingGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    incubation = indexes.BooleanField(model_attr='incubation')

    def get_model(self):
        return WorkingGroup

class NetworkGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    homepage_url = indexes.CharField(model_attr='homepage_url')
    mailinglist_url = indexes.CharField(model_attr='mailinglist_url')

    def get_model(self):
        return NetworkGroup

Prompt:
organisation: Fix references to old model fields

from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup

class PersonIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    url = indexes.CharField(model_attr='url')

    def get_model(self):
        return Person

class ProjectIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    twitter = indexes.CharField(model_attr='twitter')
    homepage_url = indexes.CharField(model_attr='homepage_url')
    mailinglist_url = indexes.CharField(model_attr='mailinglist_url')
    sourcecode_url = indexes.CharField(model_attr='sourcecode_url')

    def get_model(self):
        return Project

class WorkingGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    incubation = indexes.BooleanField(model_attr='incubation')

    def get_model(self):
        return WorkingGroup

class NetworkGroupIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    mailinglist = indexes.CharField(model_attr='mailinglist')
    homepage = indexes.CharField(model_attr='homepage')
    twitter = indexes.CharField(model_attr='twitter')

    def get_model(self):
        return NetworkGroup


from six import add_metaclass

from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException

class CheckedObserver(Observer):
    def __init__(self, observer):
        self._observer = observer
        self._state = 0 # 0 - idle, 1 - busy, 2 - done

    def on_next(self, value):
        self.check_access()
        try:
            self._observer.on_next(value)
        finally:
            self._state = 0

    def on_error(self, err):
        self.check_access()
        try:
            self._observer.on_error(err)
        finally:
            self._state = 2

    def on_completed(self):
        self.check_access()
        try:
            self._observer.on_completed()
        finally:
            self._state = 2

    def check_access(self):
        if self._state == 1:
            raise ReEntracyException()
        if self._state == 2:
            raise CompletedException()
        if self._state == 0:
            self._state = 1

@add_metaclass(ExtensionMethod)
class ObserverChecked(Observer):
    """Uses a meta class to extend Observable with the methods in this class"""

    def checked(self):
        """Checks access to the observer for grammar violations. This includes
        checking for multiple OnError or OnCompleted calls, as well as
        reentrancy in any of the observer methods. If a violation is detected,
        an Error is thrown from the offending observer method call.

        Returns an observer that checks callbacks invocations against the
        observer grammar and, if the checks pass, forwards those to the
        specified observer."""

        return CheckedObserver(self)

Response:
from six import add_metaclass

from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException

class CheckedObserver(Observer):
    def __init__(self, observer):
        self._observer = observer
        self._state = 0 # 0 - idle, 1 - busy, 2 - done

    def on_next(self, value):
        self.check_access()
        try:
            self._observer.on_next(value)
        finally:
            self._state = 0

    def on_error(self, err):
        self.check_access()
        try:
            self._observer.on_error(err)
        finally:
            self._state = 2

    def on_completed(self):
        self.check_access()
        try:
            self._observer.on_completed()
        finally:
            self._state = 2

    def check_access(self):
        if self._state == 1:
            raise ReEntracyException()
        if self._state == 2:
            raise CompletedException()
        if self._state == 0:
            self._state = 1

@add_metaclass(ExtensionMethod)
class ObserverChecked(Observer):
    """Uses a meta class to extend Observable with the methods in this class"""

    def checked(self):
        """Checks access to the observer for grammar violations. This includes
        checking for multiple OnError or OnCompleted calls, as well as
        reentrancy in any of the observer methods. If a violation is detected,
        an Error is thrown from the offending observer method call.

        Returns an observer that checks callbacks invocations against the
        observer grammar and, if the checks pass, forwards those to the
        specified observer."""

        return CheckedObserver(self)

Prompt:
Use extension method for Observer.checked

from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException

class CheckedObserver(Observer):
    def __init__(self, observer):
        self._observer = observer
        self._state = 0 # 0 - idle, 1 - busy, 2 - done

    def on_next(self, value):
        self.check_access()
        try:
            self._observer.on_next(value)
        finally:
            self._state = 0

    def on_error(self, err):
        self.check_access()
        try:
            self._observer.on_error(err)
        finally:
            self._state = 2

    def on_completed(self):
        self.check_access()
        try:
            self._observer.on_completed()
        finally:
            self._state = 2

    def check_access(self):
        if self._state == 1:
            raise ReEntracyException()
        if self._state == 2:
            raise CompletedException()
        if self._state == 0:
            self._state = 1

def checked(self):
    """Checks access to the observer for grammar violations. This includes
    checking for multiple OnError or OnCompleted calls, as well as
    reentrancy in any of the observer methods. If a violation is detected,
    an Error is thrown from the offending observer method call.

    Returns an observer that checks callbacks invocations against the
    observer grammar and, if the checks pass, forwards those to the
    specified observer.
    """
    return CheckedObserver(self)

CheckedObserver.checked = checked
Observer.checked = checked