"""The Adventure game."""

def load_advent_dat(data):
    import os
    from .data import parse

    datapath = os.path.join(os.path.dirname(__file__), 'advent.dat')
    with open(datapath, 'r', encoding='ascii') as datafile:
        parse(data, datafile)

def play(seed=None):
    """Turn the Python prompt into an Adventure game.

    With optional the `seed` argument the caller can supply an integer
    to start the Python random number generator at a known state.

    """
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game(seed)
    load_advent_dat(_game)
    install_words(_game)
    _game.start()
    print(_game.output[:-1])

def resume(savefile, quiet=False):
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game.resume(savefile)
    install_words(_game)
    if not quiet:
        print('GAME RESTORED\n')

Response:
<INSERT> optional the <INSERT_END> <INSERT> argument <INSERT_END> <REPLACE_OLD> integer <REPLACE_NEW> integer
    <REPLACE_END> <REPLACE_OLD> random
    <REPLACE_NEW> Python random <REPLACE_END> <REPLACE_OLD> state.  When `quiet` is true, no output
    is printed as the game is played; the caller of a command has to
    manually check `_game.output` for the result, which makes it
    possible to write very quiet tests.

 <REPLACE_NEW> state.

 <REPLACE_END> <|endoftext|> """The Adventure game."""

def load_advent_dat(data):
    import os
    from .data import parse

    datapath = os.path.join(os.path.dirname(__file__), 'advent.dat')
    with open(datapath, 'r', encoding='ascii') as datafile:
        parse(data, datafile)

def play(seed=None):
    """Turn the Python prompt into an Adventure game.

    With optional the `seed` argument the caller can supply an integer
    to start the Python random number generator at a known state.

    """
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game(seed)
    load_advent_dat(_game)
    install_words(_game)
    _game.start()
    print(_game.output[:-1])

def resume(savefile, quiet=False):
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game.resume(savefile)
    install_words(_game)
    if not quiet:
        print('GAME RESTORED\n')

Prompt:
Remove outdated parameter from docstring

"""The Adventure game."""

def load_advent_dat(data):
    import os
    from .data import parse

    datapath = os.path.join(os.path.dirname(__file__), 'advent.dat')
    with open(datapath, 'r', encoding='ascii') as datafile:
        parse(data, datafile)

def play(seed=None):
    """Turn the Python prompt into an Adventure game.

    With `seed` the caller can supply an integer to start the random
    number generator at a known state.  When `quiet` is true, no output
    is printed as the game is played; the caller of a command has to
    manually check `_game.output` for the result, which makes it
    possible to write very quiet tests.

    """
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game(seed)
    load_advent_dat(_game)
    install_words(_game)
    _game.start()
    print(_game.output[:-1])

def resume(savefile, quiet=False):
    global _game

    from .game import Game
    from .prompt import install_words

    _game = Game.resume(savefile)
    install_words(_game)
    if not quiet:
        print('GAME RESTORED\n')


#: A list of the permission strings used by Virtool.
PERMISSIONS = [
    "add_virus",
    "modify_virus",
    "remove_virus",
    "modify_hmm",
    "create_sample",
    "add_host",
    "remove_host",
    "cancel_job",
    "remove_job",
    "archive_job",
    "rebuild_index",
    "modify_options",
    "manage_users"
]

Response:
<REPLACE_OLD> "add_sample",
 <REPLACE_NEW> "create_sample",
 <REPLACE_END> <|endoftext|> #: A list of the permission strings used by Virtool.
PERMISSIONS = [
    "add_virus",
    "modify_virus",
    "remove_virus",
    "modify_hmm",
    "create_sample",
    "add_host",
    "remove_host",
    "cancel_job",
    "remove_job",
    "archive_job",
    "rebuild_index",
    "modify_options",
    "manage_users"
]

Prompt:
Change 'add_sample' permission to 'create_sample'

#: A list of the permission strings used by Virtool.
PERMISSIONS = [
    "add_virus",
    "modify_virus",
    "remove_virus",
    "modify_hmm",
    "add_sample",
    "add_host",
    "remove_host",
    "cancel_job",
    "remove_job",
    "archive_job",
    "rebuild_index",
    "modify_options",
    "manage_users"
]


from django.conf.urls import patterns, url
from cms_shiny.views import ShinyAppListView, ShinyAppDetailView

urlpatterns = patterns('',
    url(r'^$', ShinyAppListView.as_view(), name='shiny_list'),
    url(r'^(?P<slug>[^/]+)/$', ShinyAppDetailView.as_view(), name='shiny_detail'),
)

Append trailing slash to detail URL

Append trailing slash to detail URL

Response:
<REPLACE_OLD> url(r'^(?P<slug>[^/]+)$', <REPLACE_NEW> url(r'^(?P<slug>[^/]+)/$', <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url
from cms_shiny.views import ShinyAppListView, ShinyAppDetailView

urlpatterns = patterns('',
    url(r'^$', ShinyAppListView.as_view(), name='shiny_list'),
    url(r'^(?P<slug>[^/]+)/$', ShinyAppDetailView.as_view(), name='shiny_detail'),
)

Prompt:
Append trailing slash to detail URL

from django.conf.urls import patterns, url
from cms_shiny.views import ShinyAppListView, ShinyAppDetailView

urlpatterns = patterns('',
    url(r'^$', ShinyAppListView.as_view(), name='shiny_list'),
    url(r'^(?P<slug>[^/]+)$', ShinyAppDetailView.as_view(), name='shiny_detail'),
)


import sys
import sh

from fabric import api as fab

sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'

def is_dirty():
    return "" != sh.git.status(porcelain=True).strip()

def release(language, message):
    if is_dirty():
        sys.exit("Repo must be in clean state before deploying. Please commit changes.")
    sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
    if is_dirty():
        sh.git.add(TRAVIS_YAML)
    sh.git.commit(m=message, allow_empty=True)
    sh.git.pull(rebase=True)
    sh.git.push()

@fab.task
def release_osx():
    release('objective-c', "Release OS X")

@fab.task
def release_linux():
    release('python', "Release Linux")

Allow empty so we can force new build

Allow empty so we can force new build

Response:
<REPLACE_OLD>     sh.git.commit(m=message)
 <REPLACE_NEW> sh.git.commit(m=message, allow_empty=True)
 <REPLACE_END> <|endoftext|> import sys
import sh

from fabric import api as fab

sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'

def is_dirty():
    return "" != sh.git.status(porcelain=True).strip()

def release(language, message):
    if is_dirty():
        sys.exit("Repo must be in clean state before deploying. Please commit changes.")
    sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
    if is_dirty():
        sh.git.add(TRAVIS_YAML)
    sh.git.commit(m=message, allow_empty=True)
    sh.git.pull(rebase=True)
    sh.git.push()

@fab.task
def release_osx():
    release('objective-c', "Release OS X")

@fab.task
def release_linux():
    release('python', "Release Linux")

Prompt:
Allow empty so we can force new build

import sys
import sh

from fabric import api as fab

sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'

def is_dirty():
    return "" != sh.git.status(porcelain=True).strip()

def release(language, message):
    if is_dirty():
        sys.exit("Repo must be in clean state before deploying. Please commit changes.")
    sed(REPLACE_LANGUAGE.format(language), TRAVIS_YAML)
    if is_dirty():
        sh.git.add(TRAVIS_YAML)
        sh.git.commit(m=message)
    sh.git.pull(rebase=True)
    sh.git.push()

@fab.task
def release_osx():
    release('objective-c', "Release OS X")

@fab.task
def release_linux():
    release('python', "Release Linux")


import json
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import sys

def main():
    raw = requests.get("http://norvig.com/mayzner.html")
    if not raw:
        print >>sys.stderr, "Request failed with code %d" % (raw.status_code)
        return 1

    tree = lxml.html.fromstring(raw.text)

    sel = CSSSelector("td")

    freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))}

    print json.dumps(freq)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Add a script to generate JSON bigram frequencies for English

Response:
<INSERT> import json
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import sys

def main():
 <INSERT_END> <INSERT>   raw = requests.get("http://norvig.com/mayzner.html")
    if not raw:
        print >>sys.stderr, "Request failed with code %d" % (raw.status_code)
        return 1

    tree = lxml.html.fromstring(raw.text)

    sel = CSSSelector("td")

    freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))}

    print json.dumps(freq)
    return 0

if __name__ == "__main__":
    sys.exit(main())
 <INSERT_END> <|endoftext|> import json
import lxml.html
from lxml.cssselect import CSSSelector
import requests
import sys

def main():
    raw = requests.get("http://norvig.com/mayzner.html")
    if not raw:
        print >>sys.stderr, "Request failed with code %d" % (raw.status_code)
        return 1

    tree = lxml.html.fromstring(raw.text)

    sel = CSSSelector("td")

    freq = {key[:-1].lower(): float(value[:-2]) / 100 for key, value, _ in map(lambda x: x.get("title").split(), filter(lambda y: y.get("title") is not None, sel(tree)))}

    print json.dumps(freq)
    return 0

if __name__ == "__main__":
    sys.exit(main())

Prompt: Add a script to generate JSON bigram frequencies for English


from flask import Flask, render_template, redirect
from setup_cardsets import CardOperations

co = CardOperations()

app = Flask(__name__)

@app.route('/')
def home():
	return render_template('home.html')

@app.route('/rules')
def rules():
	return render_template('rules.html')

@app.route('/setup')
def setup():
	return render_template('setup.html')

@app.route('/toss/<int:cardcount>')
def toss(cardcount):
	co.cardset(cardcount)
	return render_template('toss.html')

@app.route('/begin')
def begin():
	try:
		co.toss_result()
		return render_template('pages/begin.html')
	except Exception as detail:
		print detail

@app.route('/game')
def game():
	co.update_page()
	co.page_no = 1
	return render_template('pages/game.html')

@app.route('/game/<statval>')
def game_move(statval):
	try:
		completed = co.compare(int(statval))
		if not completed:
			co.update_page()
			return render_template('pages/game.html')
		else:
			return redirect('/result')
	except Exception as detail:
		print detail

@app.route('/result')
def result():
	co.update_completion()
	return render_template('pages/result.html')

if __name__ == '__main__':
	app.run()

Response:
<REPLACE_OLD> render_template
from <REPLACE_NEW> render_template, redirect
from <REPLACE_END> <REPLACE_OLD> render_template('pages/game.html')
		else:
			co.update_completion()
			return render_template('pages/result.html')
	except <REPLACE_NEW> render_template('pages/game.html')
		else:
			return redirect('/result')
	except <REPLACE_END> <REPLACE_OLD> detail

if <REPLACE_NEW> detail

@app.route('/result')
def result():
	co.update_completion()
	return render_template('pages/result.html')

if <REPLACE_END> <|endoftext|> from flask import Flask, render_template, redirect
from setup_cardsets import CardOperations

co = CardOperations()

app = Flask(__name__)

@app.route('/')
def home():
	return render_template('home.html')

@app.route('/rules')
def rules():
	return render_template('rules.html')

@app.route('/setup')
def setup():
	return render_template('setup.html')

@app.route('/toss/<int:cardcount>')
def toss(cardcount):
	co.cardset(cardcount)
	return render_template('toss.html')

@app.route('/begin')
def begin():
	try:
		co.toss_result()
		return render_template('pages/begin.html')
	except Exception as detail:
		print detail

@app.route('/game')
def game():
	co.update_page()
	co.page_no = 1
	return render_template('pages/game.html')

@app.route('/game/<statval>')
def game_move(statval):
	try:
		completed = co.compare(int(statval))
		if not completed:
			co.update_page()
			return render_template('pages/game.html')
		else:
			return redirect('/result')
	except Exception as detail:
		print detail

@app.route('/result')
def result():
	co.update_completion()
	return render_template('pages/result.html')

if __name__ == '__main__':
	app.run()

Prompt:
Use flask's redirect() method to go to result link

from flask import Flask, render_template
from setup_cardsets import CardOperations

co = CardOperations()

app = Flask(__name__)

@app.route('/')
def home():
	return render_template('home.html')

@app.route('/rules')
def rules():
	return render_template('rules.html')

@app.route('/setup')
def setup():
	return render_template('setup.html')

@app.route('/toss/<int:cardcount>')
def toss(cardcount):
	co.cardset(cardcount)
	return render_template('toss.html')

@app.route('/begin')
def begin():
	try:
		co.toss_result()
		return render_template('pages/begin.html')
	except Exception as detail:
		print detail

@app.route('/game')
def game():
	co.update_page()
	co.page_no = 1
	return render_template('pages/game.html')

@app.route('/game/<statval>')
def game_move(statval):
	try:
		completed = co.compare(int(statval))
		if not completed:
			co.update_page()
			return render_template('pages/game.html')
		else:
			co.update_completion()
			return render_template('pages/result.html')
	except Exception as detail:
		print detail

if __name__ == '__main__':
	app.run()


#!/usr/bin/env python

from distutils.core import setup
setup(name='Spiff',
    version='0.1',
    description="API to Spaceman Spiff",
    author='Trever Fischer',
    author_email='wm161@wm161.net',
    url='http://github.com/synhak/spiff',
    py_modules=['spiff'],
    requires=['requests'],
)

Add deps for python lib

Add deps for python lib

Response:
<REPLACE_OLD> py_modules=['spiff']
)
 <REPLACE_NEW> py_modules=['spiff'],
    requires=['requests'],
)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from distutils.core import setup
setup(name='Spiff',
    version='0.1',
    description="API to Spaceman Spiff",
    author='Trever Fischer',
    author_email='wm161@wm161.net',
    url='http://github.com/synhak/spiff',
    py_modules=['spiff'],
    requires=['requests'],
)

Prompt:
Add deps for python lib

#!/usr/bin/env python

from distutils.core import setup
setup(name='Spiff',
    version='0.1',
    description="API to Spaceman Spiff",
    author='Trever Fischer',
    author_email='wm161@wm161.net',
    url='http://github.com/synhak/spiff',
    py_modules=['spiff']
)


#!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Run the webpages_playback automation script."""

import os
import sys

from build_step import BuildStep
from utils import shell_utils

class SKPsCapture(BuildStep):
  """BuildStep that captures the buildbot SKPs."""

  def __init__(self, timeout=10800, **kwargs):
    super(SKPsCapture, self).__init__(timeout=timeout, **kwargs)

  def _Run(self):
    webpages_playback_cmd = [
      'python', os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             'webpages_playback.py'),
      '--page_sets', self._args['page_sets'],
      '--skia_tools', self._args['skia_tools'],
      '--browser_executable', self._args['browser_executable'],
      '--non-interactive'
    ]
    if not self._is_try:
      webpages_playback_cmd.append('--upload_to_gs')
    shell_utils.Bash(webpages_playback_cmd)

    # Clean up any leftover browser instances. This can happen if there are
    # telemetry crashes, processes are not always cleaned up appropriately by
    # the webpagereplay and telemetry frameworks.
    cleanup_cmd = [
      'pkill', '-9', '-f', self._args['browser_executable']
    ]
    shell_utils.Bash(cleanup_cmd)

if '__main__' == __name__:
  sys.exit(BuildStep.RunBuildStep(SKPsCapture))

Response:
<DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <REPLACE_OLD> shell_utils.Bash(webpages_playback_cmd)

if <REPLACE_NEW> shell_utils.Bash(webpages_playback_cmd)

    # Clean up any leftover browser instances. This can happen if there are
    # telemetry crashes, processes are not always cleaned up appropriately by
    # the webpagereplay and telemetry frameworks.
    cleanup_cmd = [
      'pkill', '-9', '-f', self._args['browser_executable']
    ]
    shell_utils.Bash(cleanup_cmd)

if <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Run the webpages_playback automation script."""

import os
import sys

from build_step import BuildStep
from utils import shell_utils

class SKPsCapture(BuildStep):
  """BuildStep that captures the buildbot SKPs."""

  def __init__(self, timeout=10800, **kwargs):
    super(SKPsCapture, self).__init__(timeout=timeout, **kwargs)

  def _Run(self):
    webpages_playback_cmd = [
      'python', os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             'webpages_playback.py'),
      '--page_sets', self._args['page_sets'],
      '--skia_tools', self._args['skia_tools'],
      '--browser_executable', self._args['browser_executable'],
      '--non-interactive'
    ]
    if not self._is_try:
      webpages_playback_cmd.append('--upload_to_gs')
    shell_utils.Bash(webpages_playback_cmd)

    # Clean up any leftover browser instances. This can happen if there are
    # telemetry crashes, processes are not always cleaned up appropriately by
    # the webpagereplay and telemetry frameworks.
    cleanup_cmd = [
      'pkill', '-9', '-f', self._args['browser_executable']
    ]
    shell_utils.Bash(cleanup_cmd)

if '__main__' == __name__:
  sys.exit(BuildStep.RunBuildStep(SKPsCapture))

Prompt:
Clean up any left over browser processes in the RecreateSKPs buildstep.

BUG=skia:2055
R=borenet@google.com

Review URL: https://codereview.chromium.org/140003003

#!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Run the webpages_playback automation script."""

import os
import sys

from build_step import BuildStep
from utils import shell_utils

class SKPsCapture(BuildStep):
  """BuildStep that captures the buildbot SKPs."""

  def __init__(self, timeout=10800, **kwargs):
    super(SKPsCapture, self).__init__(timeout=timeout, **kwargs)

  def _Run(self):
    webpages_playback_cmd = [
        'python', os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               'webpages_playback.py'),
        '--page_sets', self._args['page_sets'],
        '--skia_tools', self._args['skia_tools'],
        '--browser_executable', self._args['browser_executable'],
        '--non-interactive'
    ]
    if not self._is_try:
      webpages_playback_cmd.append('--upload_to_gs')
    shell_utils.Bash(webpages_playback_cmd)

if '__main__' == __name__:
  sys.exit(BuildStep.RunBuildStep(SKPsCapture))


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

import botocore
import boto3
from datetime import datetime

class s3Uploader():

    def __init__(self, bucketName, objectName, filePath):
        self.__bucketName = bucketName
        self.__objectName = objectName
        self.__filePath = filePath
        self.__s3 = boto3.client('s3')

    def upload(self):

        if self.isExistObjectFor():
            print("{name} already exist.".format(name=self.__objectName))

            # Need refactoring...
            print("Delete {objectName}.".format(objectName=self.__objectName))
            self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName)

            print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

        else:
            print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

    def uploadObject(self, path):
        with open(path, 'rb') as fh:
            self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName)

    def isExistObjectFor(self):
        try:
            self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName)
            return True

        except botocore.exceptions.ClientError as e:
            print(e)
            return False

    def isExistBucketFor(self):
        try:
            response = self.__s3.head_bucket(Bucket=self.__bucketName)
            # response = s3.head_bucket(Bucket='test-lambda-on-java')
            print(response)
            return True

        except botocore.exceptions.ClientError as e:
            print("The {bucketName} does not found".format(bucketName=self.__bucketName))
            print(e)

            return False

Add s3 uploader class from awsSample repository.

Response:
<REPLACE_OLD>  <REPLACE_NEW> # -*- coding: utf-8 -*-

import botocore
import boto3
from datetime import datetime

class s3Uploader():

    def __init__(self, bucketName, objectName, filePath):
        self.__bucketName = bucketName
        self.__objectName = objectName
        self.__filePath = filePath
        self.__s3 = boto3.client('s3')

    def upload(self):

        if self.isExistObjectFor():
            print("{name} already exist.".format(name=self.__objectName))

            # Need refactoring...
            print("Delete {objectName}.".format(objectName=self.__objectName))
            self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName)

            print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

        else:
            print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

    def uploadObject(self, path):
        with open(path, 'rb') as fh:
            self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName)

    def isExistObjectFor(self):
        try:
            self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName)
            return True

        except botocore.exceptions.ClientError as e:
            print(e)
            return False

    def isExistBucketFor(self):
        try:
            response = self.__s3.head_bucket(Bucket=self.__bucketName)
            # response = s3.head_bucket(Bucket='test-lambda-on-java')
            print(response)
            return True

        except botocore.exceptions.ClientError as e:
            print("The {bucketName} does not found".format(bucketName=self.__bucketName))
            print(e)

            return False
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

import botocore
import boto3
from datetime import datetime

class s3Uploader():

    def __init__(self, bucketName, objectName, filePath):
        self.__bucketName = bucketName
        self.__objectName = objectName
        self.__filePath = filePath
        self.__s3 = boto3.client('s3')

    def upload(self):

        if self.isExistObjectFor():
            print("{name} already exist.".format(name=self.__objectName))

            # Need refactoring...
            print("Delete {objectName}.".format(objectName=self.__objectName))
            self.__s3.delete_object(Bucket=self.__bucketName, Key=self.__objectName)

            print("Re-Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

        else:
            print("Upload {objectName} to {bucketName}.".format(bucketName=self.__bucketName, objectName=self.__objectName))
            self.uploadObject(self.__filePath)

    def uploadObject(self, path):
        with open(path, 'rb') as fh:
            self.__s3.put_object(Body=fh, Bucket=self.__bucketName, Key=self.__objectName)

    def isExistObjectFor(self):
        try:
            self.__s3.head_object(Bucket=self.__bucketName, Key=self.__objectName)
            return True

        except botocore.exceptions.ClientError as e:
            print(e)
            return False

    def isExistBucketFor(self):
        try:
            response = self.__s3.head_bucket(Bucket=self.__bucketName)
            # response = s3.head_bucket(Bucket='test-lambda-on-java')
            print(response)
            return True

        except botocore.exceptions.ClientError as e:
            print("The {bucketName} does not found".format(bucketName=self.__bucketName))
            print(e)

            return False

Prompt: Add s3 uploader class from awsSample repository.


from __future__ import print_function

import rx
import concurrent.futures
import time

seconds = [5, 1, 2, 4, 3]

def sleep(t):
    time.sleep(t)
    return t

def output(result):
    print('%d seconds' % result)

with concurrent.futures.ProcessPoolExecutor(5) as executor:
    rx.Observable.from_(seconds).flat_map(
        lambda s: executor.submit(sleep, s)
    ).subscribe(output)

# 1 seconds
# 2 seconds
# 3 seconds
# 4 seconds
# 5 seconds

Fix parallel example for Python 3

Fix parallel example for Python 3

Response:
<INSERT> from __future__ <INSERT_END> <INSERT> print_function

import <INSERT_END> <REPLACE_OLD> print '%d <REPLACE_NEW> print('%d <REPLACE_END> <REPLACE_OLD> result

with <REPLACE_NEW> result)

with <REPLACE_END> <|endoftext|> from __future__ import print_function

import rx
import concurrent.futures
import time

seconds = [5, 1, 2, 4, 3]

def sleep(t):
    time.sleep(t)
    return t

def output(result):
    print('%d seconds' % result)

with concurrent.futures.ProcessPoolExecutor(5) as executor:
    rx.Observable.from_(seconds).flat_map(
        lambda s: executor.submit(sleep, s)
    ).subscribe(output)

# 1 seconds
# 2 seconds
# 3 seconds
# 4 seconds
# 5 seconds

Prompt:
Fix parallel example for Python 3

import rx
import concurrent.futures
import time

seconds = [5, 1, 2, 4, 3]

def sleep(t):
    time.sleep(t)
    return t

def output(result):
    print '%d seconds' % result

with concurrent.futures.ProcessPoolExecutor(5) as executor:
    rx.Observable.from_(seconds).flat_map(
        lambda s: executor.submit(sleep, s)
    ).subscribe(output)

# 1 seconds
# 2 seconds
# 3 seconds
# 4 seconds
# 5 seconds


import hoomd.integrate

class Operations:
    def __init__(self, simulation=None):
        self.simulation = simulation
        self._compute = list()
        self._auto_schedule = False
        self._scheduled = False

    def add(self, op):
        if isinstance(op, hoomd.integrate._integrator):
            self._integrator = op
        else:
            raise ValueError("Operation is not of the correct type to add to"
                             " Operations.")

    @property
    def _operations(self):
        op = list()
        if hasattr(self, '_integrator'):
            op.append(self._integrator)
        return op

    @property
    def _sys_init(self):
        if self.simulation is None or self.simulation.state is None:
            return False
        else:
            return True

    def schedule(self):
        if not self._sys_init:
            raise RuntimeError("System not initialized yet")
        sim = self.simulation
        for op in self._operations:
            new_objs = op.attach(sim)
            if isinstance(op, hoomd.integrate._integrator):
                sim._cpp_sys.setIntegrator(op._cpp_obj)
            if new_objs is not None:
                self._compute.extend(new_objs)
        self._scheduled = True

    def _store_reader(self, reader):
        # TODO
        pass

    @property
    def scheduled(self):
        return self._scheduled

    @property
    def integrator(self):
        try:
            return self._integrator
        except AttributeError:
            return None

Add integrator property for Operations

Add integrator property for Operations

Response:
<REPLACE_OLD> self._scheduled
 <REPLACE_NEW> self._scheduled

    @property
    def integrator(self):
        try:
            return self._integrator
        except AttributeError:
            return None
 <REPLACE_END> <|endoftext|> import hoomd.integrate

class Operations:
    def __init__(self, simulation=None):
        self.simulation = simulation
        self._compute = list()
        self._auto_schedule = False
        self._scheduled = False

    def add(self, op):
        if isinstance(op, hoomd.integrate._integrator):
            self._integrator = op
        else:
            raise ValueError("Operation is not of the correct type to add to"
                             " Operations.")

    @property
    def _operations(self):
        op = list()
        if hasattr(self, '_integrator'):
            op.append(self._integrator)
        return op

    @property
    def _sys_init(self):
        if self.simulation is None or self.simulation.state is None:
            return False
        else:
            return True

    def schedule(self):
        if not self._sys_init:
            raise RuntimeError("System not initialized yet")
        sim = self.simulation
        for op in self._operations:
            new_objs = op.attach(sim)
            if isinstance(op, hoomd.integrate._integrator):
                sim._cpp_sys.setIntegrator(op._cpp_obj)
            if new_objs is not None:
                self._compute.extend(new_objs)
        self._scheduled = True

    def _store_reader(self, reader):
        # TODO
        pass

    @property
    def scheduled(self):
        return self._scheduled

    @property
    def integrator(self):
        try:
            return self._integrator
        except AttributeError:
            return None

Prompt:
Add integrator property for Operations

import hoomd.integrate

class Operations:
    def __init__(self, simulation=None):
        self.simulation = simulation
        self._compute = list()
        self._auto_schedule = False
        self._scheduled = False

    def add(self, op):
        if isinstance(op, hoomd.integrate._integrator):
            self._integrator = op
        else:
            raise ValueError("Operation is not of the correct type to add to"
                             " Operations.")

    @property
    def _operations(self):
        op = list()
        if hasattr(self, '_integrator'):
            op.append(self._integrator)
        return op

    @property
    def _sys_init(self):
        if self.simulation is None or self.simulation.state is None:
            return False
        else:
            return True

    def schedule(self):
        if not self._sys_init:
            raise RuntimeError("System not initialized yet")
        sim = self.simulation
        for op in self._operations:
            new_objs = op.attach(sim)
            if isinstance(op, hoomd.integrate._integrator):
                sim._cpp_sys.setIntegrator(op._cpp_obj)
            if new_objs is not None:
                self._compute.extend(new_objs)
        self._scheduled = True

    def _store_reader(self, reader):
        # TODO
        pass

    @property
    def scheduled(self):
        return self._scheduled


from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages=['cmsplugin_biography', ],
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True
)

Convert `packages` to a list

Convert `packages` to a list

Response:
<REPLACE_OLD> packages='cmsplugin_biography',
 <REPLACE_NEW> packages=['cmsplugin_biography', ],
 <REPLACE_END> <|endoftext|> from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages=['cmsplugin_biography', ],
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True
)

Prompt:
Convert `packages` to a list

from setuptools import setup

setup(
    name='cmsplugin-biography',
    version='0.0.1',
    packages='cmsplugin_biography',
    install_requires=[
        'django-cms',
        'djangocms-text-ckeditor==1.0.9',
        'easy-thumbnails==1.2',
    ],
    author='Kevin Richardson',
    author_email='kevin@magically.us',
    description='A Django CMS plugin that manages and displays biographical information',
    long_description=open('README.rst').read(),
    license='MIT',
    url='http://github.com/kfr2/cmsplugin-biography',
    include_package_data=True
)


# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

import atexit
from os import remove
from tempfile import mkstemp

MAX_SOURCES_LENGTH = 8000  # Windows CLI has limit with command length to 8192

def _remove_tmpfile(path):
    try:
        remove(path)
    except WindowsError:  # pylint: disable=E0602
        pass

def _huge_sources_hook(sources):
    if len(str(sources)) < MAX_SOURCES_LENGTH:
        return sources

    _, tmp_file = mkstemp()
    with open(tmp_file, "w") as f:
        f.write(str(sources).replace("\\", "/"))

    atexit.register(_remove_tmpfile, tmp_file)

    return "@%s" % tmp_file

def exists(_):
    return True

def generate(env):

    env.Replace(
        _huge_sources_hook=_huge_sources_hook,
        ARCOM=env.get("ARCOM", "").replace(
            "$SOURCES", "${_huge_sources_hook(SOURCES)}"))

    return env

Response:
<REPLACE_OLD> WindowsError:
 <REPLACE_NEW> WindowsError:  # pylint: disable=E0602
 <REPLACE_END> <|endoftext|> # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

import atexit
from os import remove
from tempfile import mkstemp

MAX_SOURCES_LENGTH = 8000  # Windows CLI has limit with command length to 8192

def _remove_tmpfile(path):
    try:
        remove(path)
    except WindowsError:  # pylint: disable=E0602
        pass

def _huge_sources_hook(sources):
    if len(str(sources)) < MAX_SOURCES_LENGTH:
        return sources

    _, tmp_file = mkstemp()
    with open(tmp_file, "w") as f:
        f.write(str(sources).replace("\\", "/"))

    atexit.register(_remove_tmpfile, tmp_file)

    return "@%s" % tmp_file

def exists(_):
    return True

def generate(env):

    env.Replace(
        _huge_sources_hook=_huge_sources_hook,
        ARCOM=env.get("ARCOM", "").replace(
            "$SOURCES", "${_huge_sources_hook(SOURCES)}"))

    return env

Prompt:
Hide PyLint warning with undefined WindowsError exception

# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.

import atexit
from os import remove
from tempfile import mkstemp

MAX_SOURCES_LENGTH = 8000  # Windows CLI has limit with command length to 8192

def _remove_tmpfile(path):
    try:
        remove(path)
    except WindowsError:
        pass

def _huge_sources_hook(sources):
    if len(str(sources)) < MAX_SOURCES_LENGTH:
        return sources

    _, tmp_file = mkstemp()
    with open(tmp_file, "w") as f:
        f.write(str(sources).replace("\\", "/"))

    atexit.register(_remove_tmpfile, tmp_file)

    return "@%s" % tmp_file

def exists(_):
    return True

def generate(env):

    env.Replace(
        _huge_sources_hook=_huge_sources_hook,
        ARCOM=env.get("ARCOM", "").replace(
            "$SOURCES", "${_huge_sources_hook(SOURCES)}"))

    return env


from __future__ import unicode_literals

from django.conf.urls import patterns, url

from reviewboard.accounts.views import MyAccountView

urlpatterns = patterns(
    "reviewboard.accounts.views",

    url(r'^register/$', 'account_register',
        {'next_url': 'dashboard'}, name="register"),
    url(r'^preferences/$',
        MyAccountView.as_view(),
        name="user-preferences"),
)

urlpatterns += patterns(
    "django.contrib.auth.views",

    url(r'^login/$', 'login',
        {'template_name': 'accounts/login.html'},
        name='login'),
    url(r'^logout/$', 'logout_then_login', name='logout'),

    url(r'^recover/$',
        'password_reset',
        {
            'template_name': 'accounts/password_reset.html',
            'email_template_name': 'accounts/password_reset_email.txt'
        },
        name='recover'),
    url(r'^recover/done/$',
        'password_reset_complete',
        {'template_name': 'accounts/password_reset_done.html'},
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
        'password_reset_confirm',
        {'template_name': 'accounts/password_reset_confirm.html'},
        name='password-reset-confirm'),
    url(r'^reset/done/$',
        'password_reset_complete',
        {'template_name': 'accounts/password_reset_complete.html'}),
)

Response:
<REPLACE_OLD> 'password_reset_done',
 <REPLACE_NEW> 'password_reset_complete',
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

from django.conf.urls import patterns, url

from reviewboard.accounts.views import MyAccountView

urlpatterns = patterns(
    "reviewboard.accounts.views",

    url(r'^register/$', 'account_register',
        {'next_url': 'dashboard'}, name="register"),
    url(r'^preferences/$',
        MyAccountView.as_view(),
        name="user-preferences"),
)

urlpatterns += patterns(
    "django.contrib.auth.views",

    url(r'^login/$', 'login',
        {'template_name': 'accounts/login.html'},
        name='login'),
    url(r'^logout/$', 'logout_then_login', name='logout'),

    url(r'^recover/$',
        'password_reset',
        {
            'template_name': 'accounts/password_reset.html',
            'email_template_name': 'accounts/password_reset_email.txt'
        },
        name='recover'),
    url(r'^recover/done/$',
        'password_reset_complete',
        {'template_name': 'accounts/password_reset_done.html'},
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
        'password_reset_confirm',
        {'template_name': 'accounts/password_reset_confirm.html'},
        name='password-reset-confirm'),
    url(r'^reset/done/$',
        'password_reset_complete',
        {'template_name': 'accounts/password_reset_complete.html'}),
)

Prompt:
Change 'password_reset_done' URL name to 'password_reset_complete'

The built-in password reset views use a different name for the last page in the
flow than we did before, and somehow we never noticed this until recently.
Trivial fix.

Fixes bug 3345.

from __future__ import unicode_literals

from django.conf.urls import patterns, url

from reviewboard.accounts.views import MyAccountView

urlpatterns = patterns(
    "reviewboard.accounts.views",

    url(r'^register/$', 'account_register',
        {'next_url': 'dashboard'}, name="register"),
    url(r'^preferences/$',
        MyAccountView.as_view(),
        name="user-preferences"),
)

urlpatterns += patterns(
    "django.contrib.auth.views",

    url(r'^login/$', 'login',
        {'template_name': 'accounts/login.html'},
        name='login'),
    url(r'^logout/$', 'logout_then_login', name='logout'),

    url(r'^recover/$',
        'password_reset',
        {
            'template_name': 'accounts/password_reset.html',
            'email_template_name': 'accounts/password_reset_email.txt'
        },
        name='recover'),
    url(r'^recover/done/$',
        'password_reset_done',
        {'template_name': 'accounts/password_reset_done.html'},
        name='password_reset_done'),
    url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)-(?P<token>.+)/$',
        'password_reset_confirm',
        {'template_name': 'accounts/password_reset_confirm.html'},
        name='password-reset-confirm'),
    url(r'^reset/done/$',
        'password_reset_complete',
        {'template_name': 'accounts/password_reset_complete.html'}),
)


import rumps
import threading

from server import CamsketchServer

class CamsketchStatusBarApp(rumps.App):
    def __init__(self, address):
        super(CamsketchStatusBarApp, self).__init__("Camsketch")
        self.menu = [address]

if __name__ == "__main__":
    server = CamsketchServer()
    threading.Thread(target=server.serve_forever).start()
    app = CamsketchStatusBarApp(server.address)
    app.run()
    server.shutdown()

Add status bar module to server.

Add status bar module to server.

Response:
<INSERT> import rumps
import threading

from server import CamsketchServer

class CamsketchStatusBarApp(rumps.App):
 <INSERT_END> <INSERT>   def __init__(self, address):
        super(CamsketchStatusBarApp, self).__init__("Camsketch")
        self.menu = [address]

if __name__ == "__main__":
    server = CamsketchServer()
    threading.Thread(target=server.serve_forever).start()
    app = CamsketchStatusBarApp(server.address)
    app.run()
    server.shutdown()
 <INSERT_END> <|endoftext|> import rumps
import threading

from server import CamsketchServer

class CamsketchStatusBarApp(rumps.App):
    def __init__(self, address):
        super(CamsketchStatusBarApp, self).__init__("Camsketch")
        self.menu = [address]

if __name__ == "__main__":
    server = CamsketchServer()
    threading.Thread(target=server.serve_forever).start()
    app = CamsketchStatusBarApp(server.address)
    app.run()
    server.shutdown()

Prompt: Add status bar module to server.


# Copyright 2014 Mirantis 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.

import oslo_i18n

_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')

# The primary translation function using the well-known name "_"
_ = _translators.primary

# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical

Drop use of namespaced oslo.i18n

Response:
<REPLACE_OLD> License.

from oslo import i18n

_translators <REPLACE_NEW> License.

import oslo_i18n

_translators <REPLACE_END> <REPLACE_OLD> i18n.TranslatorFactory(domain='oslo.concurrency')

# <REPLACE_NEW> oslo_i18n.TranslatorFactory(domain='oslo.concurrency')

# <REPLACE_END> <|endoftext|> # Copyright 2014 Mirantis 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.

import oslo_i18n

_translators = oslo_i18n.TranslatorFactory(domain='oslo.concurrency')

# The primary translation function using the well-known name "_"
_ = _translators.primary

# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical

Prompt:
Drop use of namespaced oslo.i18n

Related-blueprint: drop-namespace-packages

Change-Id: Ic8247cb896ba6337932d7a74618debd698584fa0

# Copyright 2014 Mirantis 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.

from oslo import i18n

_translators = i18n.TranslatorFactory(domain='oslo.concurrency')

# The primary translation function using the well-known name "_"
_ = _translators.primary

# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical


import os
import flickr
from flask import Flask, jsonify, abort, make_response, request

app = Flask(__name__)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)

Add the helper to the default

Add the helper to the default

Response:
<REPLACE_OLD> requests
import json
from <REPLACE_NEW> flickr
from <REPLACE_END> <REPLACE_OLD> request

FLICKR_BASE = "http://api.flickr.com/services/rest/"

app <REPLACE_NEW> request

app <REPLACE_END> <|endoftext|> import os
import flickr
from flask import Flask, jsonify, abort, make_response, request

app = Flask(__name__)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)

Prompt:
Add the helper to the default

import os
import requests
import json
from flask import Flask, jsonify, abort, make_response, request

FLICKR_BASE = "http://api.flickr.com/services/rest/"

app = Flask(__name__)

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)


"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui

class QuickRefWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(QuickRefWidget, self).__init__(parent)
        self.ui = quick_ref_ui.Ui_Form()
        self.ui.setupUi(self)
        self._fix_default_font_size()
        self.ui.textEditQuickRef.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.ui.textEditQuickRef.customContextMenuRequested.connect(
            self._show_context_menu)
        self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
        self.context_menu.addSeparator()
        action = self.context_menu.addAction('Zoom in')
        action.setShortcut('Ctrl+i')
        action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
        self.addAction(action)
        action = self.context_menu.addAction('Zoom out')
        action.setShortcut('Ctrl+o')
        self.addAction(action)
        action.triggered.connect(self.ui.textEditQuickRef.zoomOut)

    def _show_context_menu(self, pos):
        self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))

    def _fix_default_font_size(self):
        # remove fixed font size to allow the user to zoom in/out using
        # Ctrl+Mouse Wheel
        # Note: Zooming into HTML documents only works if the font-size is not
        # set to a fixed size.
        # (source: http://qt-project.org/doc/qt-5/qtextedit.html)
        html = self.ui.textEditQuickRef.toHtml()
        html = re.sub('font-size:\d+pt;', '', html)
        self.ui.textEditQuickRef.setHtml(html)

Response:
<INSERT> QtCore, <INSERT_END> <REPLACE_OLD> self._fix_default_font_size()

 <REPLACE_NEW> self._fix_default_font_size()
        self.ui.textEditQuickRef.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.ui.textEditQuickRef.customContextMenuRequested.connect(
            self._show_context_menu)
        self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
        self.context_menu.addSeparator()
        action = self.context_menu.addAction('Zoom in')
        action.setShortcut('Ctrl+i')
        action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
        self.addAction(action)
        action = self.context_menu.addAction('Zoom out')
        action.setShortcut('Ctrl+o')
        self.addAction(action)
        action.triggered.connect(self.ui.textEditQuickRef.zoomOut)

    def _show_context_menu(self, pos):
        self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))

 <REPLACE_END> <|endoftext|> """
Contains the quick reference widget
"""
import re
from pyqode.qt import QtCore, QtWidgets
from .forms import quick_ref_ui

class QuickRefWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(QuickRefWidget, self).__init__(parent)
        self.ui = quick_ref_ui.Ui_Form()
        self.ui.setupUi(self)
        self._fix_default_font_size()
        self.ui.textEditQuickRef.setContextMenuPolicy(
            QtCore.Qt.CustomContextMenu)
        self.ui.textEditQuickRef.customContextMenuRequested.connect(
            self._show_context_menu)
        self.context_menu = self.ui.textEditQuickRef.createStandardContextMenu()
        self.context_menu.addSeparator()
        action = self.context_menu.addAction('Zoom in')
        action.setShortcut('Ctrl+i')
        action.triggered.connect(self.ui.textEditQuickRef.zoomIn)
        self.addAction(action)
        action = self.context_menu.addAction('Zoom out')
        action.setShortcut('Ctrl+o')
        self.addAction(action)
        action.triggered.connect(self.ui.textEditQuickRef.zoomOut)

    def _show_context_menu(self, pos):
        self.context_menu.exec_(self.ui.textEditQuickRef.mapToGlobal(pos))

    def _fix_default_font_size(self):
        # remove fixed font size to allow the user to zoom in/out using
        # Ctrl+Mouse Wheel
        # Note: Zooming into HTML documents only works if the font-size is not
        # set to a fixed size.
        # (source: http://qt-project.org/doc/qt-5/qtextedit.html)
        html = self.ui.textEditQuickRef.toHtml()
        html = re.sub('font-size:\d+pt;', '', html)
        self.ui.textEditQuickRef.setHtml(html)

Prompt:
Add zoom in/out action to the text edit context menu

Fix #5

"""
Contains the quick reference widget
"""
import re
from pyqode.qt import QtWidgets
from .forms import quick_ref_ui

class QuickRefWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(QuickRefWidget, self).__init__(parent)
        self.ui = quick_ref_ui.Ui_Form()
        self.ui.setupUi(self)
        self._fix_default_font_size()

    def _fix_default_font_size(self):
        # remove fixed font size to allow the user to zoom in/out using
        # Ctrl+Mouse Wheel
        # Note: Zooming into HTML documents only works if the font-size is not
        # set to a fixed size.
        # (source: http://qt-project.org/doc/qt-5/qtextedit.html)
        html = self.ui.textEditQuickRef.toHtml()
        html = re.sub('font-size:\d+pt;', '', html)
        self.ui.textEditQuickRef.setHtml(html)


from ..queues import QueueTtS
from ..components import _BaseComponent
from gtts import gTTS
from .playsound import playsound

import os

class TextToSpeech(_BaseComponent):

    def __init__(self):
        super().__init__()
        self.queue_tts = QueueTtS()

    def run(self):
        sentence = self.queue_tts.get()
        print('To say out loud : {}'.format(sentence))
        # TODO change the language to match user's settings
        tts = gTTS(text=sentence, lang='en')
        tts.save("tts.mp3")
        playsound("tts.mp3")
        os.remove("tts.mp3")
        self.queue_tts.task_done()

Add use of local playsoud.py

Add use of local playsoud.py

Response:
<REPLACE_OLD> playsound <REPLACE_NEW> .playsound <REPLACE_END> <|endoftext|> from ..queues import QueueTtS
from ..components import _BaseComponent
from gtts import gTTS
from .playsound import playsound

import os

class TextToSpeech(_BaseComponent):

    def __init__(self):
        super().__init__()
        self.queue_tts = QueueTtS()

    def run(self):
        sentence = self.queue_tts.get()
        print('To say out loud : {}'.format(sentence))
        # TODO change the language to match user's settings
        tts = gTTS(text=sentence, lang='en')
        tts.save("tts.mp3")
        playsound("tts.mp3")
        os.remove("tts.mp3")
        self.queue_tts.task_done()

Prompt:
Add use of local playsoud.py

from ..queues import QueueTtS
from ..components import _BaseComponent
from gtts import gTTS
from playsound import playsound

import os

class TextToSpeech(_BaseComponent):

    def __init__(self):
        super().__init__()
        self.queue_tts = QueueTtS()

    def run(self):
        sentence = self.queue_tts.get()
        print('To say out loud : {}'.format(sentence))
        # TODO change the language to match user's settings
        tts = gTTS(text=sentence, lang='en')
        tts.save("tts.mp3")
        playsound("tts.mp3")
        os.remove("tts.mp3")
        self.queue_tts.task_done()


import statsd

from . import compat

class Gauge(statsd.Client):
    '''Class to implement a statsd gauge

    '''

    def send(self, subname, value):
        '''Send the data to statsd via self.connection

        :keyword subname: The subname to report the data to (appended to the
            client name)
        :keyword value: The gauge value to send
        '''
        assert isinstance(value, compat.NUM_TYPES)
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})

Response:
<REPLACE_OLD> statsd
import decimal

class <REPLACE_NEW> statsd

from . import compat

class <REPLACE_END> <REPLACE_OLD> (int, long, float, decimal.Decimal))
 <REPLACE_NEW> compat.NUM_TYPES)
 <REPLACE_END> <|endoftext|> import statsd

from . import compat

class Gauge(statsd.Client):
    '''Class to implement a statsd gauge

    '''

    def send(self, subname, value):
        '''Send the data to statsd via self.connection

        :keyword subname: The subname to report the data to (appended to the
            client name)
        :keyword value: The gauge value to send
        '''
        assert isinstance(value, compat.NUM_TYPES)
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})

Prompt:
Use compat.NUM_TYPES due to removal of long in py3k

import statsd
import decimal

class Gauge(statsd.Client):
    '''Class to implement a statsd gauge

    '''

    def send(self, subname, value):
        '''Send the data to statsd via self.connection

        :keyword subname: The subname to report the data to (appended to the
            client name)
        :keyword value: The gauge value to send
        '''
        assert isinstance(value, (int, long, float, decimal.Decimal))
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})


# -*- coding: utf-8 -*-
from django.db import migrations

app = 'model_logging'
model = 'LogEntry'

def move_data(apps, schema_editor):
    try:
        from pgcrypto.fields import TextPGPPublicKeyField
    except ImportError:
        raise ImportError('Please install django-pgcrypto-fields to perform migration')

    LogEntry = apps.get_model(app, model)
    for entry in LogEntry.objects.all():
        entry.data_temp = entry.data
        entry.save()

class Migration(migrations.Migration):

    dependencies = [
        ('model_logging', '0002_add_new_data_field'),
    ]

    operations = [
        migrations.RunPython(move_data),
    ]

Response:
<INSERT>    try:
        from pgcrypto.fields import TextPGPPublicKeyField
    except ImportError:
        raise ImportError('Please install django-pgcrypto-fields to perform migration')

 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from django.db import migrations

app = 'model_logging'
model = 'LogEntry'

def move_data(apps, schema_editor):
    try:
        from pgcrypto.fields import TextPGPPublicKeyField
    except ImportError:
        raise ImportError('Please install django-pgcrypto-fields to perform migration')

    LogEntry = apps.get_model(app, model)
    for entry in LogEntry.objects.all():
        entry.data_temp = entry.data
        entry.save()

class Migration(migrations.Migration):

    dependencies = [
        ('model_logging', '0002_add_new_data_field'),
    ]

    operations = [
        migrations.RunPython(move_data),
    ]

Prompt:
Add try, catch statement to ensure data migration can be performed.

# -*- coding: utf-8 -*-
from django.db import migrations

app = 'model_logging'
model = 'LogEntry'

def move_data(apps, schema_editor):
    LogEntry = apps.get_model(app, model)
    for entry in LogEntry.objects.all():
        entry.data_temp = entry.data
        entry.save()

class Migration(migrations.Migration):

    dependencies = [
        ('model_logging', '0002_add_new_data_field'),
    ]

    operations = [
        migrations.RunPython(move_data),
    ]


# -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-19 05:30
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('proposals', '0002_add_under_represented_population_questions'),
    ]

    operations = [
        migrations.AlterField(
            model_name='proposal',
            name='under_represented_population',
            field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."),
        ),
    ]

Add missing migration from proposals application.

See e4b9588275dda17a70ba13fc3997b7dc20f66f57.

Response:
<INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-19 05:30
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [
        ('proposals', '0002_add_under_represented_population_questions'),
    ]

    operations = [
        migrations.AlterField(
            model_name='proposal',
            name='under_represented_population',
            field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."),
        ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Generated by Django 1.9.12 on 2017-01-19 05:30
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('proposals', '0002_add_under_represented_population_questions'),
    ]

    operations = [
        migrations.AlterField(
            model_name='proposal',
            name='under_represented_population',
            field=models.CharField(choices=[(b'', b'----'), (b'Y', b'Yes'), (b'N', b'No'), (b'O', b'I would prefer not to answer')], default=b'', max_length=1, verbose_name=b"Do you feel that you or your talk represent a population under-represented in the Python and/or Data community? In no way will this data be used as part of your proposal. This will only be used to gather diversity statistics in order to further NumFOCUS' mission."),
        ),
    ]

Prompt:
Add missing migration from proposals application.

See e4b9588275dda17a70ba13fc3997b7dc20f66f57.


from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from corehq.feature_previews import LOCATIONS
from corehq.toggles import NAMESPACE_DOMAIN
from toggle.shortcuts import update_toggle_cache, namespaced_item
from toggle.models import Toggle

class Command(BaseCommand):
    def handle(self, *args, **options):
        domains = Domain.get_all()

        for domain in domains:
            if domain.commtrack_enabled:
                toggle = Toggle.get(LOCATIONS.slug)
                toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN)

                if toggle_user_key not in toggle.enabled_users:
                    toggle.enabled_users.append(toggle_user_key)
                    toggle.save()
                    update_toggle_cache(LOCATIONS.slug, toggle_user_key, True)

                if not domain.locations_enabled:
                    domain.locations_enabled = True
                    domain.save()

Add command to turn on locations flag

Add command to turn on locations flag

Response:
<REPLACE_OLD>  <REPLACE_NEW> from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from corehq.feature_previews import LOCATIONS
from corehq.toggles import NAMESPACE_DOMAIN
from toggle.shortcuts import update_toggle_cache, namespaced_item
from toggle.models import Toggle

class Command(BaseCommand):
    def handle(self, *args, **options):
        domains = Domain.get_all()

        for domain in domains:
            if domain.commtrack_enabled:
                toggle = Toggle.get(LOCATIONS.slug)
                toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN)

                if toggle_user_key not in toggle.enabled_users:
                    toggle.enabled_users.append(toggle_user_key)
                    toggle.save()
                    update_toggle_cache(LOCATIONS.slug, toggle_user_key, True)

                if not domain.locations_enabled:
                    domain.locations_enabled = True
                    domain.save()
 <REPLACE_END> <|endoftext|> from django.core.management.base import BaseCommand
from corehq.apps.domain.models import Domain
from corehq.feature_previews import LOCATIONS
from corehq.toggles import NAMESPACE_DOMAIN
from toggle.shortcuts import update_toggle_cache, namespaced_item
from toggle.models import Toggle

class Command(BaseCommand):
    def handle(self, *args, **options):
        domains = Domain.get_all()

        for domain in domains:
            if domain.commtrack_enabled:
                toggle = Toggle.get(LOCATIONS.slug)
                toggle_user_key = namespaced_item(domain.name, NAMESPACE_DOMAIN)

                if toggle_user_key not in toggle.enabled_users:
                    toggle.enabled_users.append(toggle_user_key)
                    toggle.save()
                    update_toggle_cache(LOCATIONS.slug, toggle_user_key, True)

                if not domain.locations_enabled:
                    domain.locations_enabled = True
                    domain.save()

Prompt: Add command to turn on locations flag


from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError

from django.conf import settings

def upload(user, passwd, bucket, metadata, key, fd):
    conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)

    while bucket.endswith('-'):
        bucket = bucket[:-1]
    try:
        bucket = conn.get_bucket(bucket)
    except S3ResponseError:
        try:
            bucket = conn.create_bucket(bucket, headers=metadata)
        except (S3ResponseError, UnicodeDecodeError):
            bucket = conn.create_bucket(bucket)
        except S3CreateError as e:
            if e.status == 409:
                bucket = Bucket(conn, bucket)

    key = bucket.new_key(key)
    try:
        key.set_contents_from_file(fd)
    except S3ResponseError:
        key.set_contents_from_file(fd)

    return key.generate_url(0).split('?')[0]

Response:
<INSERT> boto.s3.bucket import Bucket
from <INSERT_END> <REPLACE_OLD> S3ResponseError

from <REPLACE_NEW> S3ResponseError, S3CreateError

from <REPLACE_END> <REPLACE_OLD> settings

def <REPLACE_NEW> settings

def <REPLACE_END> <REPLACE_OLD> conn.create_bucket(bucket)

 <REPLACE_NEW> conn.create_bucket(bucket)
        except S3CreateError as e:
            if e.status == 409:
                bucket = Bucket(conn, bucket)

 <REPLACE_END> <|endoftext|> from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3ResponseError, S3CreateError

from django.conf import settings

def upload(user, passwd, bucket, metadata, key, fd):
    conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)

    while bucket.endswith('-'):
        bucket = bucket[:-1]
    try:
        bucket = conn.get_bucket(bucket)
    except S3ResponseError:
        try:
            bucket = conn.create_bucket(bucket, headers=metadata)
        except (S3ResponseError, UnicodeDecodeError):
            bucket = conn.create_bucket(bucket)
        except S3CreateError as e:
            if e.status == 409:
                bucket = Bucket(conn, bucket)

    key = bucket.new_key(key)
    try:
        key.set_contents_from_file(fd)
    except S3ResponseError:
        key.set_contents_from_file(fd)

    return key.generate_url(0).split('?')[0]

Prompt:
Handle the case where the bucket already exists

from boto.s3.connection import S3Connection
from boto.exception import S3ResponseError

from django.conf import settings

def upload(user, passwd, bucket, metadata, key, fd):
    conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)

    while bucket.endswith('-'):
        bucket = bucket[:-1]
    try:
        bucket = conn.get_bucket(bucket)
    except S3ResponseError:
        try:
            bucket = conn.create_bucket(bucket, headers=metadata)
        except (S3ResponseError, UnicodeDecodeError):
            bucket = conn.create_bucket(bucket)

    key = bucket.new_key(key)
    try:
        key.set_contents_from_file(fd)
    except S3ResponseError:
        key.set_contents_from_file(fd)

    return key.generate_url(0).split('?')[0]


import sys
sys.path.append('.')
import pyDH

def test_pydh_keygen():
    d1 = pyDH.DiffieHellman()
    d2 = pyDH.DiffieHellman()
    d1_pubkey = d1.gen_public_key()
    d2_pubkey = d2.gen_public_key()
    d1_sharedkey = d1.gen_shared_key(d2_pubkey)
    d2_sharedkey = d2.gen_shared_key(d1_pubkey)
    assert d1_sharedkey == d2_sharedkey

Add current dir to Python path

Add current dir to Python path

Response:
<INSERT> sys
sys.path.append('.')
import <INSERT_END> <REPLACE_OLD> d2_sharedkey <REPLACE_NEW> d2_sharedkey
 <REPLACE_END> <|endoftext|> import sys
sys.path.append('.')
import pyDH

def test_pydh_keygen():
    d1 = pyDH.DiffieHellman()
    d2 = pyDH.DiffieHellman()
    d1_pubkey = d1.gen_public_key()
    d2_pubkey = d2.gen_public_key()
    d1_sharedkey = d1.gen_shared_key(d2_pubkey)
    d2_sharedkey = d2.gen_shared_key(d1_pubkey)
    assert d1_sharedkey == d2_sharedkey

Prompt:
Add current dir to Python path

import pyDH

def test_pydh_keygen():
    d1 = pyDH.DiffieHellman()
    d2 = pyDH.DiffieHellman()
    d1_pubkey = d1.gen_public_key()
    d2_pubkey = d2.gen_public_key()
    d1_sharedkey = d1.gen_shared_key(d2_pubkey)
    d2_sharedkey = d2.gen_shared_key(d1_pubkey)
    assert d1_sharedkey == d2_sharedkey


# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from MaKaC.webinterface.pages.admins import WPAdminsBase
from MaKaC.webinterface.pages.base import WPJinjaMixin
from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase

class WPReferenceTypes(WPJinjaMixin, WPAdminsBase):
    template_prefix = 'events/'
    sidemenu_option = 'reference_types'

class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase):
    template_prefix = 'events/'

    def _getBody(self, params):
        return WPJinjaMixin._getPageContent(self, params)

    def getCSSFiles(self):
        return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()

Response:
<REPLACE_OLD> 'events/'

class <REPLACE_NEW> 'events/'
    sidemenu_option = 'reference_types'

class <REPLACE_END> <|endoftext|> # This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from MaKaC.webinterface.pages.admins import WPAdminsBase
from MaKaC.webinterface.pages.base import WPJinjaMixin
from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase

class WPReferenceTypes(WPJinjaMixin, WPAdminsBase):
    template_prefix = 'events/'
    sidemenu_option = 'reference_types'

class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase):
    template_prefix = 'events/'

    def _getBody(self, params):
        return WPJinjaMixin._getPageContent(self, params)

    def getCSSFiles(self):
        return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()

Prompt:
Fix highlighting of "External ID Types" menu entry

# This file is part of Indico.
# Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

from MaKaC.webinterface.pages.admins import WPAdminsBase
from MaKaC.webinterface.pages.base import WPJinjaMixin
from MaKaC.webinterface.pages.conferences import WPConferenceDefaultDisplayBase

class WPReferenceTypes(WPJinjaMixin, WPAdminsBase):
    template_prefix = 'events/'

class WPEventDisplay(WPJinjaMixin, WPConferenceDefaultDisplayBase):
    template_prefix = 'events/'

    def _getBody(self, params):
        return WPJinjaMixin._getPageContent(self, params)

    def getCSSFiles(self):
        return WPConferenceDefaultDisplayBase.getCSSFiles(self) + self._asset_env['event_display_sass'].urls()


# -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
    try:
        from core.info.info import show_info, Pyslvs_Splash
        args = show_info()
        from PyQt5.QtWidgets import QApplication
        from core.main import MainWindow
        if args.fusion: QApplication.setStyle('fusion')
        app = QApplication(list(vars(args).values()))
        splash = Pyslvs_Splash()
        splash.show()
        run = MainWindow(args)
        run.show()
        splash.finish(run)
        exit(app.exec())
    except Exception as e:
        if e!=SystemExit:
            import logging
            logging.basicConfig(filename='PyslvsLogFile.log', filemode='w',
                format='%(asctime)s | %(message)s', level=logging.INFO)
            logging.exception("Exception Happened.")
            print('{}\n{}'.format(type(e), e))
            exit(1)

Response:
<REPLACE_OLD> print("Exception Happened. Please check the log file.")
 <REPLACE_NEW> print('{}\n{}'.format(type(e), e))
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
    try:
        from core.info.info import show_info, Pyslvs_Splash
        args = show_info()
        from PyQt5.QtWidgets import QApplication
        from core.main import MainWindow
        if args.fusion: QApplication.setStyle('fusion')
        app = QApplication(list(vars(args).values()))
        splash = Pyslvs_Splash()
        splash.show()
        run = MainWindow(args)
        run.show()
        splash.finish(run)
        exit(app.exec())
    except Exception as e:
        if e!=SystemExit:
            import logging
            logging.basicConfig(filename='PyslvsLogFile.log', filemode='w',
                format='%(asctime)s | %(message)s', level=logging.INFO)
            logging.exception("Exception Happened.")
            print('{}\n{}'.format(type(e), e))
            exit(1)

Prompt:
Change the Error show in command window.

# -*- coding: utf-8 -*-
##Pyslvs - Dimensional Synthesis of Planar Four-bar Linkages in PyQt5 GUI.
##Copyright (C) 2016 Yuan Chang [daan0014119@gmail.com]
from sys import exit
if __name__=='__main__':
    try:
        from core.info.info import show_info, Pyslvs_Splash
        args = show_info()
        from PyQt5.QtWidgets import QApplication
        from core.main import MainWindow
        if args.fusion: QApplication.setStyle('fusion')
        app = QApplication(list(vars(args).values()))
        splash = Pyslvs_Splash()
        splash.show()
        run = MainWindow(args)
        run.show()
        splash.finish(run)
        exit(app.exec())
    except Exception as e:
        if e!=SystemExit:
            import logging
            logging.basicConfig(filename='PyslvsLogFile.log', filemode='w',
                format='%(asctime)s | %(message)s', level=logging.INFO)
            logging.exception("Exception Happened.")
            print("Exception Happened. Please check the log file.")
            exit(1)


import pytest
from .._align import align

@pytest.mark.parametrize('string1,string2,cost', [
    (b'hello', b'hell', 1),
    (b'rat', b'cat', 1),
    (b'rat', b'rat', 0),
    (b'rat', b'catsie', 4),
    (b't', b'catsie', 5),
])
def test_align_costs(string1, string2, cost):
    output_cost, i2j, j2i, matrix = align(string1, string2)
    assert output_cost == cost

@pytest.mark.parametrize('string1,string2,i2j', [
    (b'hello', b'hell', [0,1,2,3,-1]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2]),
    (b't', b'catsie', [2]),
])
def test_align_i2j(string1, string2, i2j):
    output_cost, output_i2j, j2i, matrix = align(string1, string2)
    assert list(output_i2j) == i2j

@pytest.mark.parametrize('string1,string2,j2i', [
    (b'hello', b'hell', [0,1,2,3]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2, -1, -1, -1]),
    (b't', b'catsie', [-1, -1, 0, -1, -1, -1]),
])
def test_align_i2j(string1, string2, j2i):
    output_cost, output_i2j, output_j2i, matrix = align(string1, string2)
    assert list(output_j2i) == j2i

Add tests for new Levenshtein alignment

Add tests for new Levenshtein alignment

Response:
<INSERT> import pytest
from .._align import align

@pytest.mark.parametrize('string1,string2,cost', [
 <INSERT_END> <INSERT>   (b'hello', b'hell', 1),
    (b'rat', b'cat', 1),
    (b'rat', b'rat', 0),
    (b'rat', b'catsie', 4),
    (b't', b'catsie', 5),
])
def test_align_costs(string1, string2, cost):
    output_cost, i2j, j2i, matrix = align(string1, string2)
    assert output_cost == cost

@pytest.mark.parametrize('string1,string2,i2j', [
    (b'hello', b'hell', [0,1,2,3,-1]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2]),
    (b't', b'catsie', [2]),
])
def test_align_i2j(string1, string2, i2j):
    output_cost, output_i2j, j2i, matrix = align(string1, string2)
    assert list(output_i2j) == i2j

@pytest.mark.parametrize('string1,string2,j2i', [
    (b'hello', b'hell', [0,1,2,3]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2, -1, -1, -1]),
    (b't', b'catsie', [-1, -1, 0, -1, -1, -1]),
])
def test_align_i2j(string1, string2, j2i):
    output_cost, output_i2j, output_j2i, matrix = align(string1, string2)
    assert list(output_j2i) == j2i
 <INSERT_END> <|endoftext|> import pytest
from .._align import align

@pytest.mark.parametrize('string1,string2,cost', [
    (b'hello', b'hell', 1),
    (b'rat', b'cat', 1),
    (b'rat', b'rat', 0),
    (b'rat', b'catsie', 4),
    (b't', b'catsie', 5),
])
def test_align_costs(string1, string2, cost):
    output_cost, i2j, j2i, matrix = align(string1, string2)
    assert output_cost == cost

@pytest.mark.parametrize('string1,string2,i2j', [
    (b'hello', b'hell', [0,1,2,3,-1]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2]),
    (b't', b'catsie', [2]),
])
def test_align_i2j(string1, string2, i2j):
    output_cost, output_i2j, j2i, matrix = align(string1, string2)
    assert list(output_i2j) == i2j

@pytest.mark.parametrize('string1,string2,j2i', [
    (b'hello', b'hell', [0,1,2,3]),
    (b'rat', b'cat', [0,1,2]),
    (b'rat', b'rat', [0,1,2]),
    (b'rat', b'catsie', [0,1,2, -1, -1, -1]),
    (b't', b'catsie', [-1, -1, 0, -1, -1, -1]),
])
def test_align_i2j(string1, string2, j2i):
    output_cost, output_i2j, output_j2i, matrix = align(string1, string2)
    assert list(output_j2i) == j2i

Prompt: Add tests for new Levenshtein alignment


import os
import subprocess

__version__ = "0.1.0-1"

def _try_init_git_attrs():
    try:
        _init_git_commit()
    except (OSError, subprocess.CalledProcessError):
        pass
    else:
        try:
            _init_git_status()
        except (OSError, subprocess.CalledProcessError):
            pass

def _init_git_commit():
    commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1")
    globals()["__git_commit__"] = commit

def _init_git_status():
    raw = _git_cmd("git -C \"%(repo)s\" status -s")
    globals()["__git_status__"] = raw.split("\n") if raw else []

def _git_cmd(cmd, **kw):
    repo = os.path.dirname(__file__)
    cmd = cmd % dict(repo=repo, **kw)
    return subprocess.check_output(cmd, shell=True).strip()

def version():
    git_commit = globals().get("__git_commit__")
    if git_commit:
        git_status = globals().get("__git_status__", [])
        workspace_changed_marker = "*" if git_status else ""
        return "%s (dev %s%s)" % (__version__, git_commit,
                                 workspace_changed_marker)
    else:
        return __version__

_try_init_git_attrs()

Fix to git status info

Fix to git status info

Response:
<REPLACE_OLD> raw.split("\n")

def <REPLACE_NEW> raw.split("\n") if raw else []

def <REPLACE_END> <|endoftext|> import os
import subprocess

__version__ = "0.1.0-1"

def _try_init_git_attrs():
    try:
        _init_git_commit()
    except (OSError, subprocess.CalledProcessError):
        pass
    else:
        try:
            _init_git_status()
        except (OSError, subprocess.CalledProcessError):
            pass

def _init_git_commit():
    commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1")
    globals()["__git_commit__"] = commit

def _init_git_status():
    raw = _git_cmd("git -C \"%(repo)s\" status -s")
    globals()["__git_status__"] = raw.split("\n") if raw else []

def _git_cmd(cmd, **kw):
    repo = os.path.dirname(__file__)
    cmd = cmd % dict(repo=repo, **kw)
    return subprocess.check_output(cmd, shell=True).strip()

def version():
    git_commit = globals().get("__git_commit__")
    if git_commit:
        git_status = globals().get("__git_status__", [])
        workspace_changed_marker = "*" if git_status else ""
        return "%s (dev %s%s)" % (__version__, git_commit,
                                 workspace_changed_marker)
    else:
        return __version__

_try_init_git_attrs()

Prompt:
Fix to git status info

import os
import subprocess

__version__ = "0.1.0-1"

def _try_init_git_attrs():
    try:
        _init_git_commit()
    except (OSError, subprocess.CalledProcessError):
        pass
    else:
        try:
            _init_git_status()
        except (OSError, subprocess.CalledProcessError):
            pass

def _init_git_commit():
    commit = _git_cmd("git -C \"%(repo)s\" log -1 --oneline | cut -d' ' -f1")
    globals()["__git_commit__"] = commit

def _init_git_status():
    raw = _git_cmd("git -C \"%(repo)s\" status -s")
    globals()["__git_status__"] = raw.split("\n")

def _git_cmd(cmd, **kw):
    repo = os.path.dirname(__file__)
    cmd = cmd % dict(repo=repo, **kw)
    return subprocess.check_output(cmd, shell=True).strip()

def version():
    git_commit = globals().get("__git_commit__")
    if git_commit:
        git_status = globals().get("__git_status__", [])
        workspace_changed_marker = "*" if git_status else ""
        return "%s (dev %s%s)" % (__version__, git_commit,
                                 workspace_changed_marker)
    else:
        return __version__

_try_init_git_attrs()


# -*- coding: utf-8 -*-
import datetime
import pytest

from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol

pytestmark = pytest.mark.django_db

class TestIdols:
    @pytest.fixture
    def status(self):
        idols = []
        [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
        [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
        return idols

    def test_active_manager(self, status):
        assert len(Idol.objects.active()) == 3

    def test_inactive_manager(self, status):
        assert len(Idol.objects.inactive()) == 2

class TestGroups:
    @pytest.fixture
    def status(self):
        groups = [
            GroupFactory(),
            GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
            GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
        ]
        return groups

    def test_active_manager(self, status):
        assert len(Group.objects.active()) == 2

    def test_inactive_manager(self, status):
        assert len(Group.objects.inactive()) == 1

Response:
<INSERT> # -*- coding: utf-8 -*-
import datetime
import pytest

from components.people.constants <INSERT_END> <REPLACE_OLD> pytest

from <REPLACE_NEW> STATUS
from <REPLACE_END> <INSERT> GroupFactory, <INSERT_END> <REPLACE_OLD> Idol
from components.people.constants import STATUS

pytestmark <REPLACE_NEW> Group, Idol

pytestmark <REPLACE_END> <REPLACE_OLD> idols(self):
 <REPLACE_NEW> status(self):
 <REPLACE_END> <REPLACE_OLD> idols):
 <REPLACE_NEW> status):
 <REPLACE_END> <REPLACE_OLD> idols):
 <REPLACE_NEW> status):
 <REPLACE_END> <REPLACE_OLD> 2
 <REPLACE_NEW> 2

class TestGroups:
    @pytest.fixture
    def status(self):
        groups = [
            GroupFactory(),
            GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
            GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
        ]
        return groups

    def test_active_manager(self, status):
        assert len(Group.objects.active()) == 2

    def test_inactive_manager(self, status):
        assert len(Group.objects.inactive()) == 1
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import datetime
import pytest

from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol

pytestmark = pytest.mark.django_db

class TestIdols:
    @pytest.fixture
    def status(self):
        idols = []
        [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
        [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
        return idols

    def test_active_manager(self, status):
        assert len(Idol.objects.active()) == 3

    def test_inactive_manager(self, status):
        assert len(Idol.objects.inactive()) == 2

class TestGroups:
    @pytest.fixture
    def status(self):
        groups = [
            GroupFactory(),
            GroupFactory(ended=datetime.date.today() + datetime.timedelta(days=30)),
            GroupFactory(ended=datetime.date.today() - datetime.timedelta(days=30))
        ]
        return groups

    def test_active_manager(self, status):
        assert len(Group.objects.active()) == 2

    def test_inactive_manager(self, status):
        assert len(Group.objects.inactive()) == 1

Prompt:
Test group managers. Rename idols() => status().

import pytest

from components.people.factories import IdolFactory
from components.people.models import Idol
from components.people.constants import STATUS

pytestmark = pytest.mark.django_db

class TestIdols:
    @pytest.fixture
    def idols(self):
        idols = []
        [idols.append(IdolFactory(status=STATUS.active)) for i in xrange(3)]
        [idols.append(IdolFactory(status=STATUS.former)) for i in xrange(2)]
        return idols

    def test_active_manager(self, idols):
        assert len(Idol.objects.active()) == 3

    def test_inactive_manager(self, idols):
        assert len(Idol.objects.inactive()) == 2


# coding: utf-8

import logging
import os
import shutil
import sys
import tempfile
import unittest

import six

import fiona

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

class UnicodePathTest(unittest.TestCase):

    def setUp(self):
        tempdir = tempfile.mkdtemp()
        self.dir = os.path.join(tempdir, 'français')
        shutil.copytree('docs/data/', self.dir)

    def tearDown(self):
        shutil.rmtree(os.path.dirname(self.dir))

    def test_unicode_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
        with fiona.open(path) as c:
            assert len(c) == 48

    def test_unicode_path_layer(self):
        path = self.dir
        layer = 'test_uk'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
            layer = layer.decode('utf-8')
        with fiona.open(path, layer=layer) as c:
            assert len(c) == 48

    def test_utf8_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            with fiona.open(path) as c:
                assert len(c) == 48

Clean up parent temporary directory

Response:
<REPLACE_OLD> shutil.rmtree(self.dir)

 <REPLACE_NEW> shutil.rmtree(os.path.dirname(self.dir))

 <REPLACE_END> <|endoftext|> # coding: utf-8

import logging
import os
import shutil
import sys
import tempfile
import unittest

import six

import fiona

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

class UnicodePathTest(unittest.TestCase):

    def setUp(self):
        tempdir = tempfile.mkdtemp()
        self.dir = os.path.join(tempdir, 'français')
        shutil.copytree('docs/data/', self.dir)

    def tearDown(self):
        shutil.rmtree(os.path.dirname(self.dir))

    def test_unicode_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
        with fiona.open(path) as c:
            assert len(c) == 48

    def test_unicode_path_layer(self):
        path = self.dir
        layer = 'test_uk'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
            layer = layer.decode('utf-8')
        with fiona.open(path, layer=layer) as c:
            assert len(c) == 48

    def test_utf8_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            with fiona.open(path) as c:
                assert len(c) == 48

Prompt:
TST: Clean up parent temporary directory

# coding: utf-8

import logging
import os
import shutil
import sys
import tempfile
import unittest

import six

import fiona

logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)

class UnicodePathTest(unittest.TestCase):

    def setUp(self):
        tempdir = tempfile.mkdtemp()
        self.dir = os.path.join(tempdir, 'français')
        shutil.copytree('docs/data/', self.dir)

    def tearDown(self):
        shutil.rmtree(self.dir)

    def test_unicode_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
        with fiona.open(path) as c:
            assert len(c) == 48

    def test_unicode_path_layer(self):
        path = self.dir
        layer = 'test_uk'
        if sys.version_info < (3,):
            path = path.decode('utf-8')
            layer = layer.decode('utf-8')
        with fiona.open(path, layer=layer) as c:
            assert len(c) == 48

    def test_utf8_path(self):
        path = self.dir + '/test_uk.shp'
        if sys.version_info < (3,):
            with fiona.open(path) as c:
                assert len(c) == 48


#!/usr/bin/python
import os
import re
from setuptools import setup
from m2r import parse_from_file
import restructuredtext_lint

# Parser README.md into reStructuredText format
rst_readme = parse_from_file('README.md')

# Validate the README, checking for errors
errors = restructuredtext_lint.lint(rst_readme)

# Raise an exception for any errors found
if errors:
    print(rst_readme)
    raise ValueError('README.md contains errors: ',
                     ', '.join([e.message for e in errors]))

# Attempt to get version number from TravisCI environment variable
version = os.environ.get('TRAVIS_TAG', default='0.0.0')

# Remove leading 'v'
version = re.sub('^v', '', version)

setup(
    name='anybadge',
    description='Simple, flexible badge generator for project badges.',
    long_description=rst_readme,
    version=version,
    author='Jon Grace-Cox',
    author_email='jongracecox@gmail.com',
    py_modules=['anybadge', 'anybadge_server'],
    setup_requires=['setuptools', 'wheel'],
    tests_require=['unittest'],
    install_requires=[],
    data_files=[],
    options={
        'bdist_wheel': {'universal': True}
    },
    url='https://github.com/jongracecox/anybadge',
    entry_points={
        'console_scripts': ['anybadge=anybadge:main',
                            'anybadge-server=anybadge_server:main'],
    },
    classifiers=[
        'License :: OSI Approved :: MIT License'
    ]
)

Use classifiers to specify the license.

Response:
<REPLACE_OLD> }
)
 <REPLACE_NEW> },
    classifiers=[
        'License :: OSI Approved :: MIT License'
    ]
)
 <REPLACE_END> <|endoftext|> #!/usr/bin/python
import os
import re
from setuptools import setup
from m2r import parse_from_file
import restructuredtext_lint

# Parser README.md into reStructuredText format
rst_readme = parse_from_file('README.md')

# Validate the README, checking for errors
errors = restructuredtext_lint.lint(rst_readme)

# Raise an exception for any errors found
if errors:
    print(rst_readme)
    raise ValueError('README.md contains errors: ',
                     ', '.join([e.message for e in errors]))

# Attempt to get version number from TravisCI environment variable
version = os.environ.get('TRAVIS_TAG', default='0.0.0')

# Remove leading 'v'
version = re.sub('^v', '', version)

setup(
    name='anybadge',
    description='Simple, flexible badge generator for project badges.',
    long_description=rst_readme,
    version=version,
    author='Jon Grace-Cox',
    author_email='jongracecox@gmail.com',
    py_modules=['anybadge', 'anybadge_server'],
    setup_requires=['setuptools', 'wheel'],
    tests_require=['unittest'],
    install_requires=[],
    data_files=[],
    options={
        'bdist_wheel': {'universal': True}
    },
    url='https://github.com/jongracecox/anybadge',
    entry_points={
        'console_scripts': ['anybadge=anybadge:main',
                            'anybadge-server=anybadge_server:main'],
    },
    classifiers=[
        'License :: OSI Approved :: MIT License'
    ]
)

Prompt:
Use classifiers to specify the license.

Classifiers are a standard way of specifying a license, and make it easy
for automated tools to properly detect the license of the package.

The "license" field should only be used if the license has no
corresponding Trove classifier.

#!/usr/bin/python
import os
import re
from setuptools import setup
from m2r import parse_from_file
import restructuredtext_lint

# Parser README.md into reStructuredText format
rst_readme = parse_from_file('README.md')

# Validate the README, checking for errors
errors = restructuredtext_lint.lint(rst_readme)

# Raise an exception for any errors found
if errors:
    print(rst_readme)
    raise ValueError('README.md contains errors: ',
                     ', '.join([e.message for e in errors]))

# Attempt to get version number from TravisCI environment variable
version = os.environ.get('TRAVIS_TAG', default='0.0.0')

# Remove leading 'v'
version = re.sub('^v', '', version)

setup(
    name='anybadge',
    description='Simple, flexible badge generator for project badges.',
    long_description=rst_readme,
    version=version,
    author='Jon Grace-Cox',
    author_email='jongracecox@gmail.com',
    py_modules=['anybadge', 'anybadge_server'],
    setup_requires=['setuptools', 'wheel'],
    tests_require=['unittest'],
    install_requires=[],
    data_files=[],
    options={
        'bdist_wheel': {'universal': True}
    },
    url='https://github.com/jongracecox/anybadge',
    entry_points={
        'console_scripts': ['anybadge=anybadge:main',
                            'anybadge-server=anybadge_server:main'],
    }
)