Indent return in identify class.

Indent return in identify class.

Response:
<REPLACE_OLD> BioID:
    defs <REPLACE_NEW> BioID:
	defs <REPLACE_END> <REPLACE_OLD> None

    def <REPLACE_NEW> None

	def <REPLACE_END> <REPLACE_OLD> defpath):
        with <REPLACE_NEW> defpath):
		with <REPLACE_END> <REPLACE_OLD> deffile:
            conts <REPLACE_NEW> deffile:
			conts <REPLACE_END> <REPLACE_OLD> deffile.read()
        self.defs <REPLACE_NEW> deffile.read()
		self.defs <REPLACE_END> <REPLACE_OLD> json.loads(conts)["formats"]

    @classmethod
    def <REPLACE_NEW> json.loads(conts)["formats"]

	@classmethod
	def <REPLACE_END> <REPLACE_OLD> files):
        recog <REPLACE_NEW> files):
		recog <REPLACE_END> <REPLACE_OLD> {}
        for <REPLACE_NEW> {}
		for <REPLACE_END> <REPLACE_OLD> files:
            with <REPLACE_NEW> files:
			with <REPLACE_END> <REPLACE_OLD> infile:
                buff <REPLACE_NEW> infile:
				buff <REPLACE_END> <REPLACE_OLD> infile.read()
                mem_map <REPLACE_NEW> infile.read()
				mem_map <REPLACE_END> <REPLACE_OLD> mmap.PROT_READ)

            if <REPLACE_NEW> mmap.PROT_READ)

			if <REPLACE_END> <REPLACE_OLD> 0:
                recog[file] <REPLACE_NEW> 0:
				recog[file] <REPLACE_END> <REPLACE_OLD> :)
                continue

            for <REPLACE_NEW> :)
				continue

			for <REPLACE_END> <REPLACE_OLD> cls.defs:
                matched <REPLACE_NEW> cls.defs:
				matched <REPLACE_END> <REPLACE_OLD> True
                if <REPLACE_NEW> True
				if <REPLACE_END> <REPLACE_OLD> fdef:
                    for <REPLACE_NEW> fdef:
					for <REPLACE_END> <REPLACE_OLD> re.IGNORECASE):
                            matched <REPLACE_NEW> re.IGNORECASE):
							matched <REPLACE_END> <REPLACE_OLD> False
                            break
                if <REPLACE_NEW> False
							break
			if <REPLACE_END> <REPLACE_OLD> fdef:
                    for <REPLACE_NEW> fdef:
				for <REPLACE_END> <REPLACE_OLD> fdef["bytes"]:
                        if <REPLACE_NEW> fdef["bytes"]:
					if <REPLACE_END> <REPLACE_OLD> -1:
                            matched <REPLACE_NEW> -1:
						matched <REPLACE_END> <REPLACE_OLD> False
                            break
                if matched:
                    recog[file] <REPLACE_NEW> False
						break
			if matched:
				recog[file] <REPLACE_END> <REPLACE_OLD> fdef["name"]
                    break

            mem_map.close()
            if <REPLACE_NEW> fdef["name"]
				break

		mem_map.close()
		if <REPLACE_END> <REPLACE_OLD> recog:
                recog[file] <REPLACE_NEW> recog:
			recog[file] <REPLACE_END> <REPLACE_OLD> "unrecognized"

        return <REPLACE_NEW> "unrecognized"

		return <REPLACE_END> <|endoftext|> #!/usr/bin/env python
#
# A class for auto identifying bioinformatics file formats.
# By Lee & Matt

import re
import json
import mmap

class BioID:
	defs = None

	def __init__(self, defpath):
		with open(defpath, "r") as deffile:
			conts = deffile.read()
		self.defs = json.loads(conts)["formats"]

	@classmethod
	def identify(cls, files):
		recog = {}
		for file in files:
			with open(file, "r") as infile:
				buff = infile.read()
				mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ)

			if len(buff) == 0:
				recog[file] = "empty"  # Empty files have no format :)
				continue

			for fdef in cls.defs:
				matched = True
				if "regexen" in fdef:
					for regex in fdef["regexen"]:
						if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE):
							matched = False
							break
			if "bytes" in fdef:
				for bytes in fdef["bytes"]:
					if mem_map.find(bytes.decode("string_escape")) == -1:
						matched = False
						break
			if matched:
				recog[file] = fdef["name"]
				break

		mem_map.close()
		if file not in recog:
			recog[file] = "unrecognized"

		return recog

Prompt:
Indent return in identify class.

#!/usr/bin/env python
#
# A class for auto identifying bioinformatics file formats.
# By Lee & Matt

import re
import json
import mmap

class BioID:
    defs = None

    def __init__(self, defpath):
        with open(defpath, "r") as deffile:
            conts = deffile.read()
        self.defs = json.loads(conts)["formats"]

    @classmethod
    def identify(cls, files):
        recog = {}
        for file in files:
            with open(file, "r") as infile:
                buff = infile.read()
                mem_map = mmap.mmap(infile.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ)

            if len(buff) == 0:
                recog[file] = "empty"  # Empty files have no format :)
                continue

            for fdef in cls.defs:
                matched = True
                if "regexen" in fdef:
                    for regex in fdef["regexen"]:
						if not re.findall(regex.replace("\\n", "\n"), buff, re.IGNORECASE):
                            matched = False
                            break
                if "bytes" in fdef:
                    for bytes in fdef["bytes"]:
                        if mem_map.find(bytes.decode("string_escape")) == -1:
                            matched = False
                            break
                if matched:
                    recog[file] = fdef["name"]
                    break

            mem_map.close()
            if file not in recog:
                recog[file] = "unrecognized"

        return recog


from __future__ import print_function

import numpy as np
np.random.seed(1337)

import keras.backend as K
from keras.models import Sequential
from keras.layers.core import Dense
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import LSTM
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD

# wrapper of ctc_cost
def ctc_cost(y_true, y_pred):
    '''
    CTC cost:
    a theano wrapper for warp-ctc
    Arguments:
        y_true : label
        y_pred : acts
    '''
    from theano_ctc import ctc_cost as warp_ctc_cost

    # convert (batch size, timestep, target) to (timestep, batch size, target)
    acts = K.permute_dimensions(y_pred, (1, 0, 2))
    labels = K.cast(K.squeeze(y_true, axis=2), 'int32')
    return warp_ctc_cost(acts, labels)

batch_size = 16
frame_len = 80
nb_feat = 120
nb_class = 36
nb_output = nb_class + 1  # add output for blank
inner_dim = 512
nb_cell = 1024

print("Building model...")
model = Sequential()
model.add(LSTM(inner_dim, input_shape = (frame_len, nb_feat), return_sequences = True))
model.add(BatchNormalization())
model.add(TimeDistributed(Dense(nb_output)))

model.summary()

# Compiling
opt = SGD(lr = 1e-5, momentum = 0.9, nesterov = True)
model.compile(optimizer = opt, loss = ctc_cost, sample_weight_mode = None)

# Generate dummy data
data = np.random.uniform(low = -5, high = 5, size = (batch_size, frame_len, nb_feat))
# Dummy labels in range [1,nb_class]. 0 = <blank>
label = 1 + np.random.randint(nb_class, size = (batch_size, frame_len, 1))

# Training
model.fit(data, label, nb_epoch = 5, batch_size = batch_size)

Add simple test for Keras

Add simple test for Keras

Response:
<REPLACE_OLD>  <REPLACE_NEW> from __future__ import print_function

import numpy as np
np.random.seed(1337)

import keras.backend as K
from keras.models import Sequential
from keras.layers.core import Dense
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import LSTM
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD

# wrapper of ctc_cost
def ctc_cost(y_true, y_pred):
    '''
    CTC cost:
    a theano wrapper for warp-ctc
    Arguments:
        y_true : label
        y_pred : acts
    '''
    from theano_ctc import ctc_cost as warp_ctc_cost

    # convert (batch size, timestep, target) to (timestep, batch size, target)
    acts = K.permute_dimensions(y_pred, (1, 0, 2))
    labels = K.cast(K.squeeze(y_true, axis=2), 'int32')
    return warp_ctc_cost(acts, labels)

batch_size = 16
frame_len = 80
nb_feat = 120
nb_class = 36
nb_output = nb_class + 1  # add output for blank
inner_dim = 512
nb_cell = 1024

print("Building model...")
model = Sequential()
model.add(LSTM(inner_dim, input_shape = (frame_len, nb_feat), return_sequences = True))
model.add(BatchNormalization())
model.add(TimeDistributed(Dense(nb_output)))

model.summary()

# Compiling
opt = SGD(lr = 1e-5, momentum = 0.9, nesterov = True)
model.compile(optimizer = opt, loss = ctc_cost, sample_weight_mode = None)

# Generate dummy data
data = np.random.uniform(low = -5, high = 5, size = (batch_size, frame_len, nb_feat))
# Dummy labels in range [1,nb_class]. 0 = <blank>
label = 1 + np.random.randint(nb_class, size = (batch_size, frame_len, 1))

# Training
model.fit(data, label, nb_epoch = 5, batch_size = batch_size)
 <REPLACE_END> <|endoftext|> from __future__ import print_function

import numpy as np
np.random.seed(1337)

import keras.backend as K
from keras.models import Sequential
from keras.layers.core import Dense
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import LSTM
from keras.layers.normalization import BatchNormalization
from keras.optimizers import SGD

# wrapper of ctc_cost
def ctc_cost(y_true, y_pred):
    '''
    CTC cost:
    a theano wrapper for warp-ctc
    Arguments:
        y_true : label
        y_pred : acts
    '''
    from theano_ctc import ctc_cost as warp_ctc_cost

    # convert (batch size, timestep, target) to (timestep, batch size, target)
    acts = K.permute_dimensions(y_pred, (1, 0, 2))
    labels = K.cast(K.squeeze(y_true, axis=2), 'int32')
    return warp_ctc_cost(acts, labels)

batch_size = 16
frame_len = 80
nb_feat = 120
nb_class = 36
nb_output = nb_class + 1  # add output for blank
inner_dim = 512
nb_cell = 1024

print("Building model...")
model = Sequential()
model.add(LSTM(inner_dim, input_shape = (frame_len, nb_feat), return_sequences = True))
model.add(BatchNormalization())
model.add(TimeDistributed(Dense(nb_output)))

model.summary()

# Compiling
opt = SGD(lr = 1e-5, momentum = 0.9, nesterov = True)
model.compile(optimizer = opt, loss = ctc_cost, sample_weight_mode = None)

# Generate dummy data
data = np.random.uniform(low = -5, high = 5, size = (batch_size, frame_len, nb_feat))
# Dummy labels in range [1,nb_class]. 0 = <blank>
label = 1 + np.random.randint(nb_class, size = (batch_size, frame_len, 1))

# Training
model.fit(data, label, nb_epoch = 5, batch_size = batch_size)

Prompt: Add simple test for Keras


# Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)

import os
import sys
import json
import yaml

def yaml2json(data):
  """
  Convert YAML to JSON (output: JSON)
  """
  try:
    d = yaml.load(data, Loader=yaml.BaseLoader)
  except Exception as e:
    d = {'error': '{}'.format(e)}

  return json.dumps(d)

def json2yaml(data):
  """
  Convert JSON to YAML (output: YAML)
  """
  try:
    d = json.loads(data)
  except Exception as e:
    d = {'error': '{}'.format(e)}

  return yaml.dump(d, default_flow_style=False)

def handle(data, **parms):
  if parms.get('reverse') == 'true':
    print(json2yaml(data))
  else:
    print(yaml2json(data))

Response:
<REPLACE_OLD> handle(data, **parms):
  def yaml2json(ydata):
   <REPLACE_NEW> yaml2json(data):
 <REPLACE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <REPLACE_OLD> yaml.load(ydata, <REPLACE_NEW> yaml.load(data, <REPLACE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <REPLACE_OLD> json.dumps(d)

  def json2yaml(jdata):
   <REPLACE_NEW> json.dumps(d)

def json2yaml(data):
 <REPLACE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <REPLACE_OLD> json.loads(jdata)
   <REPLACE_NEW> json.loads(data)
 <REPLACE_END> <DELETE>   <DELETE_END> <DELETE>   <DELETE_END> <REPLACE_OLD> default_flow_style=False)

 <REPLACE_NEW> default_flow_style=False)

def handle(data, **parms):
 <REPLACE_END> <|endoftext|> # Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)

import os
import sys
import json
import yaml

def yaml2json(data):
  """
  Convert YAML to JSON (output: JSON)
  """
  try:
    d = yaml.load(data, Loader=yaml.BaseLoader)
  except Exception as e:
    d = {'error': '{}'.format(e)}

  return json.dumps(d)

def json2yaml(data):
  """
  Convert JSON to YAML (output: YAML)
  """
  try:
    d = json.loads(data)
  except Exception as e:
    d = {'error': '{}'.format(e)}

  return yaml.dump(d, default_flow_style=False)

def handle(data, **parms):
  if parms.get('reverse') == 'true':
    print(json2yaml(data))
  else:
    print(yaml2json(data))

Prompt:
Make handle function to behave similar as main function

# Author: Milos Buncic
# Date: 2017/10/14
# Description: Convert YAML to JSON and vice versa (OpenFaaS function)

import os
import sys
import json
import yaml

def handle(data, **parms):
  def yaml2json(ydata):
    """
    Convert YAML to JSON (output: JSON)
    """
    try:
      d = yaml.load(ydata, Loader=yaml.BaseLoader)
    except Exception as e:
      d = {'error': '{}'.format(e)}

    return json.dumps(d)

  def json2yaml(jdata):
    """
    Convert JSON to YAML (output: YAML)
    """
    try:
      d = json.loads(jdata)
    except Exception as e:
      d = {'error': '{}'.format(e)}

    return yaml.dump(d, default_flow_style=False)

  if parms.get('reverse') == 'true':
    print(json2yaml(data))
  else:
    print(yaml2json(data))


from django.core.management.base import BaseCommand

from topics.models import Topic

class Command(BaseCommand):
    help = u'Bootstrap the topic lists in the database.'

    def handle(self, *args, **kwargs):
        self.load_topics()

    def load_topics(self):
        self.stdout.write(u'Loading hot list topics...')

        topics = [
            u'Budget & Taxes',
            u'Business & Technology',
            u'Criminal Justice',
            u'Energy',
            u'Environment',
            u'Ethics',
            u'Health & Human Services',
            u'Higher Education',
            u'Immigration & Border Security',
            u'Public Education',
            u'Social Justice',
            u'Transportation',
        ]

        for topic in topics:
            Topic.objects.get_or_create(name=topic)

Response:
<DELETE> u'Civil Liberties',
            <DELETE_END> <REPLACE_OLD> u'Energy & Environment',
 <REPLACE_NEW> u'Energy',
            u'Environment',
 <REPLACE_END> <INSERT>            u'Social Justice',
 <INSERT_END> <|endoftext|> from django.core.management.base import BaseCommand

from topics.models import Topic

class Command(BaseCommand):
    help = u'Bootstrap the topic lists in the database.'

    def handle(self, *args, **kwargs):
        self.load_topics()

    def load_topics(self):
        self.stdout.write(u'Loading hot list topics...')

        topics = [
            u'Budget & Taxes',
            u'Business & Technology',
            u'Criminal Justice',
            u'Energy',
            u'Environment',
            u'Ethics',
            u'Health & Human Services',
            u'Higher Education',
            u'Immigration & Border Security',
            u'Public Education',
            u'Social Justice',
            u'Transportation',
        ]

        for topic in topics:
            Topic.objects.get_or_create(name=topic)

Prompt:
Split Energy and Environment, change Civil Liberties to Social Justice

from django.core.management.base import BaseCommand

from topics.models import Topic

class Command(BaseCommand):
    help = u'Bootstrap the topic lists in the database.'

    def handle(self, *args, **kwargs):
        self.load_topics()

    def load_topics(self):
        self.stdout.write(u'Loading hot list topics...')

        topics = [
            u'Budget & Taxes',
            u'Business & Technology',
            u'Civil Liberties',
            u'Criminal Justice',
            u'Energy & Environment',
            u'Ethics',
            u'Health & Human Services',
            u'Higher Education',
            u'Immigration & Border Security',
            u'Public Education',
            u'Transportation',
        ]

        for topic in topics:
            Topic.objects.get_or_create(name=topic)


import datetime
import json
import sys

import ffs
import re

from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader

def main(workspace):
    DATA_DIR = ffs.Path(workspace)
    datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))

    u = Uploader("ccgois")
    for dataset in datasets:
        resources = []
        for resource in dataset['sources']:
            resource['format'] = resource['filetype']
            resource['name'] = resource['url'].split('/')[-1]

            filename = filename_for_resource(resource)
            path = DATA_DIR / filename

            download_file(resource['url'], path)
            print "Uploading to S3"
            url = u.upload(path)
            resource['url'] = url
            resources.append(resource)
        dataset['resources'] = resources
    u.close()

    json.dump(datasets, open(DATA_DIR / 'ccgois_indicators.json', 'w'))

Response:
<REPLACE_OLD> resource['url'].split('/')[-1],

 <REPLACE_NEW> resource['url'].split('/')[-1]

 <REPLACE_END> <DELETE>    print datasets[0]['resources']

 <DELETE_END> <|endoftext|> import datetime
import json
import sys

import ffs
import re

from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader

def main(workspace):
    DATA_DIR = ffs.Path(workspace)
    datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))

    u = Uploader("ccgois")
    for dataset in datasets:
        resources = []
        for resource in dataset['sources']:
            resource['format'] = resource['filetype']
            resource['name'] = resource['url'].split('/')[-1]

            filename = filename_for_resource(resource)
            path = DATA_DIR / filename

            download_file(resource['url'], path)
            print "Uploading to S3"
            url = u.upload(path)
            resource['url'] = url
            resources.append(resource)
        dataset['resources'] = resources
    u.close()

    json.dump(datasets, open(DATA_DIR / 'ccgois_indicators.json', 'w'))

Prompt:
Fix the naming of the newly created resources

import datetime
import json
import sys

import ffs
import re

from publish.lib.helpers import filename_for_resource, download_file
from publish.lib.upload import Uploader

def main(workspace):
    DATA_DIR = ffs.Path(workspace)
    datasets = json.load(open(DATA_DIR / 'ccgois_indicators.json'))

    u = Uploader("ccgois")
    for dataset in datasets:
        resources = []
        for resource in dataset['sources']:
            resource['format'] = resource['filetype']
            resource['name'] = resource['url'].split('/')[-1],

            filename = filename_for_resource(resource)
            path = DATA_DIR / filename

            download_file(resource['url'], path)
            print "Uploading to S3"
            url = u.upload(path)
            resource['url'] = url
            resources.append(resource)
        dataset['resources'] = resources
    u.close()

    print datasets[0]['resources']

    json.dump(datasets, open(DATA_DIR / 'ccgois_indicators.json', 'w'))


#!/usr/bin/python

import os
import sqlite3
import sys
import time

if len(sys.argv) < 3:
    raise ValueError('Usage: %s "Firstnam Lastname" email@example.com' % sys.argv[0])

db = sqlite3.connect('/var/lib/zon-api/data.db')
api_key = str(os.urandom(26).encode('hex'))
tier = 'free'
name = sys.argv[1]
email = sys.argv[2]
requests = 0
reset = int(time.time())
query = 'INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)'
db.execute(query, (api_key, tier, name, email, requests, reset))
db.commit()
db.close()
print api_key

Add helper script to generate API keys.

Add helper script to generate API keys.

Response:
<INSERT> #!/usr/bin/python

import os
import sqlite3
import sys
import time

if len(sys.argv) < 3:
 <INSERT_END> <INSERT>   raise ValueError('Usage: %s "Firstnam Lastname" email@example.com' % sys.argv[0])

db = sqlite3.connect('/var/lib/zon-api/data.db')
api_key = str(os.urandom(26).encode('hex'))
tier = 'free'
name = sys.argv[1]
email = sys.argv[2]
requests = 0
reset = int(time.time())
query = 'INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)'
db.execute(query, (api_key, tier, name, email, requests, reset))
db.commit()
db.close()
print api_key
 <INSERT_END> <|endoftext|> #!/usr/bin/python

import os
import sqlite3
import sys
import time

if len(sys.argv) < 3:
    raise ValueError('Usage: %s "Firstnam Lastname" email@example.com' % sys.argv[0])

db = sqlite3.connect('/var/lib/zon-api/data.db')
api_key = str(os.urandom(26).encode('hex'))
tier = 'free'
name = sys.argv[1]
email = sys.argv[2]
requests = 0
reset = int(time.time())
query = 'INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)'
db.execute(query, (api_key, tier, name, email, requests, reset))
db.commit()
db.close()
print api_key

Prompt: Add helper script to generate API keys.


# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from django.shortcuts import render_to_response
from django.template import RequestContext

def home_page(request):
    return render_to_response('home_page/index.html', RequestContext(request))

Add RequestContext to Micro site

Response:
<REPLACE_OLD> render_to_response

def <REPLACE_NEW> render_to_response
from django.template import RequestContext

def <REPLACE_END> <REPLACE_OLD> render_to_response('home_page/index.html')
 <REPLACE_NEW> render_to_response('home_page/index.html', RequestContext(request))
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from django.shortcuts import render_to_response
from django.template import RequestContext

def home_page(request):
    return render_to_response('home_page/index.html', RequestContext(request))

Prompt:
Add RequestContext to Micro site

This allows us to populate settings variables such as Google Analytics
codes. See original work done for #769.

Refs #920

# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division

from django.shortcuts import render_to_response

def home_page(request):
    return render_to_response('home_page/index.html')


#!/usr/bin/env python

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['xacro'],
    package_dir={'': 'src'}
)

setup(**d)

Remove bin copy of xacro.py

Remove bin copy of xacro.py

Response:
<REPLACE_OLD> 'src'},
    scripts=['scripts/xacro.py']
)

setup(**d)
 <REPLACE_NEW> 'src'}
)

setup(**d)
 <REPLACE_END> <|endoftext|> #!/usr/bin/env python

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['xacro'],
    package_dir={'': 'src'}
)

setup(**d)

Prompt:
Remove bin copy of xacro.py
#!/usr/bin/env python

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['xacro'],
    package_dir={'': 'src'},
    scripts=['scripts/xacro.py']
)

setup(**d)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [('auvsi_suas', '0012_missionclockevent'), ]

    operations = [
        migrations.AlterField(
            model_name='target',
            name='target_type',
            field=models.IntegerField(choices=[(1, b'standard'), (2, b'qrc'), (
                3, b'off_axis'), (4, b'emergent')]), ),
    ]

Remove the IR target type in migration.

Remove the IR target type in migration.

Response:
<INSERT> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

 <INSERT_END> <INSERT>   dependencies = [('auvsi_suas', '0012_missionclockevent'), ]

    operations = [
        migrations.AlterField(
            model_name='target',
            name='target_type',
            field=models.IntegerField(choices=[(1, b'standard'), (2, b'qrc'), (
                3, b'off_axis'), (4, b'emergent')]), ),
    ]
 <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [('auvsi_suas', '0012_missionclockevent'), ]

    operations = [
        migrations.AlterField(
            model_name='target',
            name='target_type',
            field=models.IntegerField(choices=[(1, b'standard'), (2, b'qrc'), (
                3, b'off_axis'), (4, b'emergent')]), ),
    ]

Prompt: Remove the IR target type in migration.


from string import ascii_lowercase
import django
import os
import string

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()

from breach.models import Target, Victim

endpoint = 'https://dionyziz.com/breach-test/reflect.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9

target_1 = Target(
    endpoint=endpoint,
    prefix=prefix,
    alphabet=alphabet,
    secretlength=secretlength,
    alignmentalphabet=string.ascii_uppercase
)
target_1.save()

print 'Created Target:\n\tendpoint: {}\n\tprefix: {}\n\talphabet: {}\n\tsecretlength: {}'.format(endpoint, prefix, alphabet, secretlength)

snifferendpoint = 'http://127.0.0.1:9000'
sourceip = '192.168.1.22'

victim_1 = Victim(
    target=target_1,
    snifferendpoint=snifferendpoint,
    sourceip=sourceip,
    method='serial'
)
victim_1.save()

print 'Created Victim:\n\tvictim_id: {}\n\tsnifferendpoint: {}\n\tsourceip: {}'.format(victim_1.id, snifferendpoint, sourceip)

Add population script for dionyziz

Add population script for dionyziz

Response:
<INSERT> from string import ascii_lowercase
import django
import os
import string

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()

from breach.models import Target, Victim

endpoint = 'https://dionyziz.com/breach-test/reflect.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9

target_1 = Target(
 <INSERT_END> <INSERT>   endpoint=endpoint,
    prefix=prefix,
    alphabet=alphabet,
    secretlength=secretlength,
    alignmentalphabet=string.ascii_uppercase
)
target_1.save()

print 'Created Target:\n\tendpoint: {}\n\tprefix: {}\n\talphabet: {}\n\tsecretlength: {}'.format(endpoint, prefix, alphabet, secretlength)

snifferendpoint = 'http://127.0.0.1:9000'
sourceip = '192.168.1.22'

victim_1 = Victim(
    target=target_1,
    snifferendpoint=snifferendpoint,
    sourceip=sourceip,
    method='serial'
)
victim_1.save()

print 'Created Victim:\n\tvictim_id: {}\n\tsnifferendpoint: {}\n\tsourceip: {}'.format(victim_1.id, snifferendpoint, sourceip)
 <INSERT_END> <|endoftext|> from string import ascii_lowercase
import django
import os
import string

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
django.setup()

from breach.models import Target, Victim

endpoint = 'https://dionyziz.com/breach-test/reflect.php?ref=%s'
prefix = 'imper'
alphabet = ascii_lowercase
secretlength = 9

target_1 = Target(
    endpoint=endpoint,
    prefix=prefix,
    alphabet=alphabet,
    secretlength=secretlength,
    alignmentalphabet=string.ascii_uppercase
)
target_1.save()

print 'Created Target:\n\tendpoint: {}\n\tprefix: {}\n\talphabet: {}\n\tsecretlength: {}'.format(endpoint, prefix, alphabet, secretlength)

snifferendpoint = 'http://127.0.0.1:9000'
sourceip = '192.168.1.22'

victim_1 = Victim(
    target=target_1,
    snifferendpoint=snifferendpoint,
    sourceip=sourceip,
    method='serial'
)
victim_1.save()

print 'Created Victim:\n\tvictim_id: {}\n\tsnifferendpoint: {}\n\tsourceip: {}'.format(victim_1.id, snifferendpoint, sourceip)

Prompt: Add population script for dionyziz


from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase

class AccountExtban(ModuleData):
	implements(IPlugin, IModuleData)

	name = "AccountExtban"

	def actions(self):
		return [ ("usermatchban-R", 1, self.matchBan),
		  ("usermetadataupdate", 10, self.updateBansOnAccountChange) ]

	def matchBan(self, user, matchNegated, mask):
		if not user.metadataKeyExists("account"):
			return matchNegated
		userAccount = ircLower(user.metadataValue("account"))
		lowerMask = ircLower(mask)
		if fnmatchcase(userAccount, lowerMask):
			return not matchNegated
		return matchNegated

	def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
		if key != "account":
			return
		self.ircd.runActionStandard("updateuserbancache", user)

matchExtban = AccountExtban()

Fix matching users against R: extbans

Fix matching users against R: extbans

Response:
<REPLACE_OLD> ircLower(user.metadataValue("account"))
		if <REPLACE_NEW> ircLower(user.metadataValue("account"))
		lowerMask = ircLower(mask)
		if <REPLACE_END> <REPLACE_OLD> mask):
			return <REPLACE_NEW> lowerMask):
			return <REPLACE_END> <|endoftext|> from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase

class AccountExtban(ModuleData):
	implements(IPlugin, IModuleData)

	name = "AccountExtban"

	def actions(self):
		return [ ("usermatchban-R", 1, self.matchBan),
		  ("usermetadataupdate", 10, self.updateBansOnAccountChange) ]

	def matchBan(self, user, matchNegated, mask):
		if not user.metadataKeyExists("account"):
			return matchNegated
		userAccount = ircLower(user.metadataValue("account"))
		lowerMask = ircLower(mask)
		if fnmatchcase(userAccount, lowerMask):
			return not matchNegated
		return matchNegated

	def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
		if key != "account":
			return
		self.ircd.runActionStandard("updateuserbancache", user)

matchExtban = AccountExtban()

Prompt:
Fix matching users against R: extbans

from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase

class AccountExtban(ModuleData):
	implements(IPlugin, IModuleData)

	name = "AccountExtban"

	def actions(self):
		return [ ("usermatchban-R", 1, self.matchBan),
		  ("usermetadataupdate", 10, self.updateBansOnAccountChange) ]

	def matchBan(self, user, matchNegated, mask):
		if not user.metadataKeyExists("account"):
			return matchNegated
		userAccount = ircLower(user.metadataValue("account"))
		if fnmatchcase(userAccount, mask):
			return not matchNegated
		return matchNegated

	def updateBansOnAccountChange(self, user, key, oldValue, value, visibility, setByUser, fromServer = None):
		if key != "account":
			return
		self.ircd.runActionStandard("updateuserbancache", user)

matchExtban = AccountExtban()


import json
import jsonpointer

class Schema(dict):
    """
    Lightweight encapsulation of a JSON Schema.
    """

    @classmethod
    def from_file(cls, path_or_stream):
        """
        Create a schema from a file name or stream.
        """
        if hasattr(path_or_stream, 'read'):
            return cls(json.load(path_or_stream))
        else:
            with open(path_or_stream) as fp:
                return cls(json.load(fp))

    def resolve_ref(self, ref):
        if not ref.startswith('#'):
            raise ValueError("non-fragment references are not supported (got: %s)" % ref)
        return jsonpointer.resolve_pointer(self, ref.lstrip('#'))

Response:
<REPLACE_OLD> json

class <REPLACE_NEW> json
import jsonpointer

class <REPLACE_END> <DELETE> return Reference(ref).resolve(self)

class Reference(object):
    def __init__(self, ref):
        <DELETE_END> <DELETE> self.ref = ref

    def resolve(self, schema):
        # Very overly simplisitic - doesn't handle array indexes, etc. However,
        # works with Heroku's schema, so good enough for a prototype.
        node = schema
        for bit in self.ref.split('/')[1:]:
            node = node[bit]
        <DELETE_END> <REPLACE_OLD> node
 <REPLACE_NEW> jsonpointer.resolve_pointer(self, ref.lstrip('#'))
 <REPLACE_END> <|endoftext|> import json
import jsonpointer

class Schema(dict):
    """
    Lightweight encapsulation of a JSON Schema.
    """

    @classmethod
    def from_file(cls, path_or_stream):
        """
        Create a schema from a file name or stream.
        """
        if hasattr(path_or_stream, 'read'):
            return cls(json.load(path_or_stream))
        else:
            with open(path_or_stream) as fp:
                return cls(json.load(fp))

    def resolve_ref(self, ref):
        if not ref.startswith('#'):
            raise ValueError("non-fragment references are not supported (got: %s)" % ref)
        return jsonpointer.resolve_pointer(self, ref.lstrip('#'))

Prompt:
Use jsonpointer instead of my own terrible Reference class.

import json

class Schema(dict):
    """
    Lightweight encapsulation of a JSON Schema.
    """

    @classmethod
    def from_file(cls, path_or_stream):
        """
        Create a schema from a file name or stream.
        """
        if hasattr(path_or_stream, 'read'):
            return cls(json.load(path_or_stream))
        else:
            with open(path_or_stream) as fp:
                return cls(json.load(fp))

    def resolve_ref(self, ref):
        return Reference(ref).resolve(self)

class Reference(object):
    def __init__(self, ref):
        if not ref.startswith('#'):
            raise ValueError("non-fragment references are not supported (got: %s)" % ref)
        self.ref = ref

    def resolve(self, schema):
        # Very overly simplisitic - doesn't handle array indexes, etc. However,
        # works with Heroku's schema, so good enough for a prototype.
        node = schema
        for bit in self.ref.split('/')[1:]:
            node = node[bit]
        return node


# __init__.py - collection of Brazilian numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Brazilian numbers."""
from stdnum.br import cnpj as vat  # noqa: F401

Add missing vat alias for Brazil

Add missing vat alias for Brazil

Response:
<REPLACE_OLD> numbers."""
 <REPLACE_NEW> numbers."""
from stdnum.br import cnpj as vat  # noqa: F401
 <REPLACE_END> <|endoftext|> # __init__.py - collection of Brazilian numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Brazilian numbers."""
from stdnum.br import cnpj as vat  # noqa: F401

Prompt:
Add missing vat alias for Brazil

# __init__.py - collection of Brazilian numbers
# coding: utf-8
#
# Copyright (C) 2012 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Collection of Brazilian numbers."""


from rest_framework.permissions import BasePermission

from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user

class CanViewAssociatedCourse(BasePermission):
    """ Permission class to check user can view a publisher course or also if
    user has view permission on organization.
    """

    def has_object_permission(self, request, view, obj):
        user = request.user
        return (
            check_roles_access(user) or
            check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
        )

class InternalUserPermission(BasePermission):
    """ Permission class to check user is an internal user. """

    def has_object_permission(self, request, view, obj):
        return request.user.is_staff or is_internal_user(request.user)

class PublisherUserPermission(BasePermission):
    """ Permission class to check user is a publisher user. """

    def has_object_permission(self, request, view, obj):
        return request.user.is_staff or is_publisher_user(request.user)

    def has_permission(self, request, view):
        return request.user.is_staff or is_publisher_user(request.user)

Allow staff access to Publisher APIs

Response:
<INSERT> request.user.is_staff or <INSERT_END> <INSERT> request.user.is_staff or <INSERT_END> <INSERT> request.user.is_staff or <INSERT_END> <|endoftext|> from rest_framework.permissions import BasePermission

from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user

class CanViewAssociatedCourse(BasePermission):
    """ Permission class to check user can view a publisher course or also if
    user has view permission on organization.
    """

    def has_object_permission(self, request, view, obj):
        user = request.user
        return (
            check_roles_access(user) or
            check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
        )

class InternalUserPermission(BasePermission):
    """ Permission class to check user is an internal user. """

    def has_object_permission(self, request, view, obj):
        return request.user.is_staff or is_internal_user(request.user)

class PublisherUserPermission(BasePermission):
    """ Permission class to check user is a publisher user. """

    def has_object_permission(self, request, view, obj):
        return request.user.is_staff or is_publisher_user(request.user)

    def has_permission(self, request, view):
        return request.user.is_staff or is_publisher_user(request.user)

Prompt:
Allow staff access to Publisher APIs

A few Publisher APIs were marked as only allowing publisher users.
We should also let staff in.

DISCO-1365

from rest_framework.permissions import BasePermission

from course_discovery.apps.publisher.mixins import check_course_organization_permission, check_roles_access
from course_discovery.apps.publisher.models import OrganizationExtension
from course_discovery.apps.publisher.utils import is_internal_user, is_publisher_user

class CanViewAssociatedCourse(BasePermission):
    """ Permission class to check user can view a publisher course or also if
    user has view permission on organization.
    """

    def has_object_permission(self, request, view, obj):
        user = request.user
        return (
            check_roles_access(user) or
            check_course_organization_permission(user, obj.course, OrganizationExtension.VIEW_COURSE)
        )

class InternalUserPermission(BasePermission):
    """ Permission class to check user is an internal user. """

    def has_object_permission(self, request, view, obj):
        return is_internal_user(request.user)

class PublisherUserPermission(BasePermission):
    """ Permission class to check user is a publisher user. """

    def has_object_permission(self, request, view, obj):
        return is_publisher_user(request.user)

    def has_permission(self, request, view):
        return is_publisher_user(request.user)


import abc
from decimal import Decimal

from core import Key, Keyboard

class StandardKeyboard(Keyboard):
    """ A StandardKeyboard is a keyboard with standard Cherry MX key sizes and spacings. (see: http://www.fentek-ind.com/images/CHERRY_MX_keyswitch.pdf)

    """
    def __init__(self):
        self.unit_height = 19.05
        self.unit_width = 19.05
        self.separator = '|'
        self.comment = '-'

    @property
    def keys(self):
        keys = set()
        offset_y = Decimal(0)
        for line in self.schema.splitlines():
            # don't process lines starting with the comment prefix
            if line.startswith(self.comment):
                continue
            offset_x = Decimal(0)
            for key in line.strip(self.separator).split(self.separator):
                keys.add(Key(x=offset_x, y=offset_y))
                unit = len(key) * 0.25 + 1
                offset_x = offset_x.add(Decimal(self.unit_width * unit))
            offset_y = offset_y.add(Decimal(self.unit_height))
        return keys

    @abc.abstractproperty
    def schema(self):
        pass

Implement parsing in StandardKeyboard class

Response:
<REPLACE_OLD>  <REPLACE_NEW> import abc
from decimal import Decimal

from core import Key, Keyboard

class StandardKeyboard(Keyboard):
    """ A StandardKeyboard is a keyboard with standard Cherry MX key sizes and spacings. (see: http://www.fentek-ind.com/images/CHERRY_MX_keyswitch.pdf)

    """
    def __init__(self):
        self.unit_height = 19.05
        self.unit_width = 19.05
        self.separator = '|'
        self.comment = '-'

    @property
    def keys(self):
        keys = set()
        offset_y = Decimal(0)
        for line in self.schema.splitlines():
            # don't process lines starting with the comment prefix
            if line.startswith(self.comment):
                continue
            offset_x = Decimal(0)
            for key in line.strip(self.separator).split(self.separator):
                keys.add(Key(x=offset_x, y=offset_y))
                unit = len(key) * 0.25 + 1
                offset_x = offset_x.add(Decimal(self.unit_width * unit))
            offset_y = offset_y.add(Decimal(self.unit_height))
        return keys

    @abc.abstractproperty
    def schema(self):
        pass
 <REPLACE_END> <|endoftext|> import abc
from decimal import Decimal

from core import Key, Keyboard

class StandardKeyboard(Keyboard):
    """ A StandardKeyboard is a keyboard with standard Cherry MX key sizes and spacings. (see: http://www.fentek-ind.com/images/CHERRY_MX_keyswitch.pdf)

    """
    def __init__(self):
        self.unit_height = 19.05
        self.unit_width = 19.05
        self.separator = '|'
        self.comment = '-'

    @property
    def keys(self):
        keys = set()
        offset_y = Decimal(0)
        for line in self.schema.splitlines():
            # don't process lines starting with the comment prefix
            if line.startswith(self.comment):
                continue
            offset_x = Decimal(0)
            for key in line.strip(self.separator).split(self.separator):
                keys.add(Key(x=offset_x, y=offset_y))
                unit = len(key) * 0.25 + 1
                offset_x = offset_x.add(Decimal(self.unit_width * unit))
            offset_y = offset_y.add(Decimal(self.unit_height))
        return keys

    @abc.abstractproperty
    def schema(self):
        pass

Prompt: Implement parsing in StandardKeyboard class


from __future__ import unicode_literals

import csv

from django.core.management.base import BaseCommand

from candidatebot.helpers import CandidateBot
from popolo.models import Person

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            'filename',
            help='Path to the file with the email addresses'
        )
        parser.add_argument(
            '--source',
            help='Source of the data. The source CSV column takes precedence'
        )

    def handle(self, **options):
        with open(options['filename'], 'r') as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                source = row.get('source', options.get('source'))
                if not row['democlub_id']:
                    continue
                if not source:
                    raise ValueError("A source is required")

                try:
                    bot = CandidateBot(row['democlub_id'])
                    try:
                        bot.add_email(row['email'])
                        bot.save(source)
                    except ValueError:
                        #Email exists, move on
                        pass
                except Person.DoesNotExist:
                    print("Person ID {} not found".format(
                        row['democlub_id']))
                # print(row)

Move on if email exists

Move on if email exists

Response:
<INSERT> try:
                        <INSERT_END> <INSERT>     <INSERT_END> <REPLACE_OLD> # print(person)
 <REPLACE_NEW> except ValueError:
                        #Email exists, move on
                        pass
 <REPLACE_END> <|endoftext|> from __future__ import unicode_literals

import csv

from django.core.management.base import BaseCommand

from candidatebot.helpers import CandidateBot
from popolo.models import Person

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            'filename',
            help='Path to the file with the email addresses'
        )
        parser.add_argument(
            '--source',
            help='Source of the data. The source CSV column takes precedence'
        )

    def handle(self, **options):
        with open(options['filename'], 'r') as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                source = row.get('source', options.get('source'))
                if not row['democlub_id']:
                    continue
                if not source:
                    raise ValueError("A source is required")

                try:
                    bot = CandidateBot(row['democlub_id'])
                    try:
                        bot.add_email(row['email'])
                        bot.save(source)
                    except ValueError:
                        #Email exists, move on
                        pass
                except Person.DoesNotExist:
                    print("Person ID {} not found".format(
                        row['democlub_id']))
                # print(row)

Prompt:
Move on if email exists

from __future__ import unicode_literals

import csv

from django.core.management.base import BaseCommand

from candidatebot.helpers import CandidateBot
from popolo.models import Person

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            'filename',
            help='Path to the file with the email addresses'
        )
        parser.add_argument(
            '--source',
            help='Source of the data. The source CSV column takes precedence'
        )

    def handle(self, **options):
        with open(options['filename'], 'r') as fh:
            reader = csv.DictReader(fh)
            for row in reader:
                source = row.get('source', options.get('source'))
                if not row['democlub_id']:
                    continue
                if not source:
                    raise ValueError("A source is required")

                try:
                    bot = CandidateBot(row['democlub_id'])
                    bot.add_email(row['email'])
                    bot.save(source)
                    # print(person)
                except Person.DoesNotExist:
                    print("Person ID {} not found".format(
                        row['democlub_id']))
                # print(row)


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

import unittest
import os
from mathdeck import loadproblem

class TestMathdeckLoadProblem(unittest.TestCase):

    def test_loadproblem_has_answers_attribute(self):
        file_name = 'has_answers_attribute.py'
        file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem', file_name)
        problem = loadproblem.load_file_as_module(file)
        self.assertTrue(hasattr(problem,'answers'))

    def test_loadproblem_has_no_answers_attribute(self):
        file_name = 'has_no_answers_attribute.py'
        file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem', file_name)
        self.assertRaises(Exception, loadproblem.load_file_as_module(file))

if __name__ == '__main__':
    unittest.main()

Fix parameter values for load function

Fix parameter values for load function

Response:
<REPLACE_OLD> problem_dir <REPLACE_NEW> file <REPLACE_END> <REPLACE_OLD> 'fixtures','loadproblem')
 <REPLACE_NEW> 'fixtures','loadproblem', file_name)
 <REPLACE_END> <REPLACE_OLD> loadproblem.load_file_as_module(problem_dir,file_name)
 <REPLACE_NEW> loadproblem.load_file_as_module(file)
 <REPLACE_END> <REPLACE_OLD> problem_dir <REPLACE_NEW> file <REPLACE_END> <REPLACE_OLD> 'fixtures','loadproblem')
 <REPLACE_NEW> 'fixtures','loadproblem', file_name)
 <REPLACE_END> <REPLACE_OLD> loadproblem. \
            load_file_as_module(problem_dir,file_name))

if <REPLACE_NEW> loadproblem.load_file_as_module(file))

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

import unittest
import os
from mathdeck import loadproblem

class TestMathdeckLoadProblem(unittest.TestCase):

    def test_loadproblem_has_answers_attribute(self):
        file_name = 'has_answers_attribute.py'
        file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem', file_name)
        problem = loadproblem.load_file_as_module(file)
        self.assertTrue(hasattr(problem,'answers'))

    def test_loadproblem_has_no_answers_attribute(self):
        file_name = 'has_no_answers_attribute.py'
        file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem', file_name)
        self.assertRaises(Exception, loadproblem.load_file_as_module(file))

if __name__ == '__main__':
    unittest.main()

Prompt:
Fix parameter values for load function

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

import unittest
import os
from mathdeck import loadproblem

class TestMathdeckLoadProblem(unittest.TestCase):

    def test_loadproblem_has_answers_attribute(self):
        file_name = 'has_answers_attribute.py'
        problem_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem')
        problem = loadproblem.load_file_as_module(problem_dir,file_name)
        self.assertTrue(hasattr(problem,'answers'))

    def test_loadproblem_has_no_answers_attribute(self):
        file_name = 'has_no_answers_attribute.py'
        problem_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                'fixtures','loadproblem')
        self.assertRaises(Exception, loadproblem. \
            load_file_as_module(problem_dir,file_name))

if __name__ == '__main__':
    unittest.main()


from django.conf.urls import patterns, url

urlpatterns = patterns(
    'buysafe.views',
    url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
    (r'^start/$', 'start'),
    (r'^success/(?P<payment_type>[01])/$', 'success'),
    (r'^fail/(?P<payment_type>[01])/$', 'fail'),
    (r'^check/(?P<payment_type>[01])/$', 'check')
)

Add name for entry view URL

Add name for entry view URL

Response:
<REPLACE_OLD> patterns

urlpatterns <REPLACE_NEW> patterns, url

urlpatterns <REPLACE_END> <REPLACE_OLD> (r'^entry/(?P<order_id>\d+)/$', 'entry'),
 <REPLACE_NEW> url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
 <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url

urlpatterns = patterns(
    'buysafe.views',
    url(r'^entry/(?P<order_id>\d+)/$', 'entry', name='buysafe_pay'),
    (r'^start/$', 'start'),
    (r'^success/(?P<payment_type>[01])/$', 'success'),
    (r'^fail/(?P<payment_type>[01])/$', 'fail'),
    (r'^check/(?P<payment_type>[01])/$', 'check')
)

Prompt:
Add name for entry view URL

from django.conf.urls import patterns

urlpatterns = patterns(
    'buysafe.views',
    (r'^entry/(?P<order_id>\d+)/$', 'entry'),
    (r'^start/$', 'start'),
    (r'^success/(?P<payment_type>[01])/$', 'success'),
    (r'^fail/(?P<payment_type>[01])/$', 'fail'),
    (r'^check/(?P<payment_type>[01])/$', 'check')
)


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

from . import areas

class FailedRequest(Exception):
    def __init__(self, error):
        self.error = error

    def __str__(self):
        return repr(self.error)

class Client(object):
    """
    The Podio API client. Callers should use the factory method OAuthClient to create instances.
    """

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

    def __getattr__(self, name):
        new_trans = self.transport
        area = getattr(areas, name)
        return area(new_trans)

    def __dir__(self):
        """
        Should return list of attribute names.
        Since __getattr__ looks in areas, we simply list the content of the areas module
        """
        return dir(areas)

Response:
<REPLACE_OLD> area(new_trans)
 <REPLACE_NEW> area(new_trans)

    def __dir__(self):
        """
        Should return list of attribute names.
        Since __getattr__ looks in areas, we simply list the content of the areas module
        """
        return dir(areas)
 <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-

from . import areas

class FailedRequest(Exception):
    def __init__(self, error):
        self.error = error

    def __str__(self):
        return repr(self.error)

class Client(object):
    """
    The Podio API client. Callers should use the factory method OAuthClient to create instances.
    """

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

    def __getattr__(self, name):
        new_trans = self.transport
        area = getattr(areas, name)
        return area(new_trans)

    def __dir__(self):
        """
        Should return list of attribute names.
        Since __getattr__ looks in areas, we simply list the content of the areas module
        """
        return dir(areas)

Prompt:
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.

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

from . import areas

class FailedRequest(Exception):
    def __init__(self, error):
        self.error = error

    def __str__(self):
        return repr(self.error)

class Client(object):
    """
    The Podio API client. Callers should use the factory method OAuthClient to create instances.
    """

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

    def __getattr__(self, name):
        new_trans = self.transport
        area = getattr(areas, name)
        return area(new_trans)


#!/usr/bin/env python
# coding: utf-8

import os
import re
from setuptools import setup, find_packages

def load_required_modules():
    with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f:
        return [line.strip() for line in f.readlines() if line.strip()]

setup(
    name='dictmixin',
    __version__=re.search(
        r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',  # It excludes inline comment too
        open('dictmixin/__init__.py').read()).group(1),
    description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.',
    license='MIT',
    author='tadashi-aikawa',
    author_email='syou.maman@gmail.com',
    maintainer='tadashi-aikawa',
    maintainer_email='tadashi-aikawa',
    url='https://github.com/tadashi-aikawa/dictmixin.git',
    keywords='dict json convert parse each other',
    packages=find_packages(exclude=['tests*']),
    install_requires=load_required_modules(),
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)

Response:
<REPLACE_OLD> f.read().strip().split(os.linesep) <REPLACE_NEW> f.readlines() <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# coding: utf-8

import os
import re
from setuptools import setup, find_packages

def load_required_modules():
    with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f:
        return [line.strip() for line in f.readlines() if line.strip()]

setup(
    name='dictmixin',
    __version__=re.search(
        r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',  # It excludes inline comment too
        open('dictmixin/__init__.py').read()).group(1),
    description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.',
    license='MIT',
    author='tadashi-aikawa',
    author_email='syou.maman@gmail.com',
    maintainer='tadashi-aikawa',
    maintainer_email='tadashi-aikawa',
    url='https://github.com/tadashi-aikawa/dictmixin.git',
    keywords='dict json convert parse each other',
    packages=find_packages(exclude=['tests*']),
    install_requires=load_required_modules(),
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)

Prompt:
Fix bug which load_required_modules always returns list which length is 1

#!/usr/bin/env python
# coding: utf-8

import os
import re
from setuptools import setup, find_packages

def load_required_modules():
    with open(os.path.join(os.path.dirname(__file__), "requirements.txt")) as f:
        return [line.strip() for line in f.read().strip().split(os.linesep) if line.strip()]

setup(
    name='dictmixin',
    __version__=re.search(
        r'__version__\s*=\s*[\'"]([^\'"]*)[\'"]',  # It excludes inline comment too
        open('dictmixin/__init__.py').read()).group(1),
    description='Parsing mixin which converts `data class instance`, `dict object`, and `json string` each other.',
    license='MIT',
    author='tadashi-aikawa',
    author_email='syou.maman@gmail.com',
    maintainer='tadashi-aikawa',
    maintainer_email='tadashi-aikawa',
    url='https://github.com/tadashi-aikawa/dictmixin.git',
    keywords='dict json convert parse each other',
    packages=find_packages(exclude=['tests*']),
    install_requires=load_required_modules(),
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
)


import unittest

import mock

from chainer import testing
from chainer.training import extensions
from chainer.training import trigger

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)

Add unit test to pass Trigger instance.

Add unit test to pass Trigger instance.

Response:
<REPLACE_OLD> extensions

@testing.parameterize(
 <REPLACE_NEW> extensions
from chainer.training import trigger

@testing.parameterize(
 <REPLACE_END> <REPLACE_OLD> 10)},
)
class <REPLACE_NEW> 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class <REPLACE_END> <REPLACE_OLD> 10)},
)
class <REPLACE_NEW> 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class <REPLACE_END> <|endoftext|> import unittest

import mock

from chainer import testing
from chainer.training import extensions
from chainer.training import trigger

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)

Prompt:
Add unit test to pass Trigger instance.

import unittest

import mock

from chainer import testing
from chainer.training import extensions

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)


# Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
This module defines the Eliot log events emitted by the API implementation.
"""

__all__ = [
    "JSON_REQUEST",
    "REQUEST",
    ]

from eliot import Field, ActionType

LOG_SYSTEM = u"api"

METHOD = Field(u"method", lambda method: method,
               u"The HTTP method of the request.")
REQUEST_PATH = Field(
    u"request_path", lambda path: path,
    u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
    u"json", [unicode, bytes, dict, list, None, bool, float],
    u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
    u"code", [int],
    u"The response code for the request.")

REQUEST = ActionType(
    LOG_SYSTEM + u":request",
    [REQUEST_PATH, METHOD],
    [],
    u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
    LOG_SYSTEM + u":json_request",
    [JSON],
    [RESPONSE_CODE, JSON],
    u"A request containing JSON request and response.")

Response:
<REPLACE_OLD> Field.forTypes(
 <REPLACE_NEW> Field(u"method", lambda method: method,
 <REPLACE_END> <REPLACE_OLD> u"method", [unicode, bytes], <REPLACE_NEW>            <REPLACE_END> <REPLACE_OLD> Field.forTypes(
 <REPLACE_NEW> Field(
 <REPLACE_END> <REPLACE_OLD> [unicode, bytes],
 <REPLACE_NEW> lambda path: path,
 <REPLACE_END> <|endoftext|> # Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
This module defines the Eliot log events emitted by the API implementation.
"""

__all__ = [
    "JSON_REQUEST",
    "REQUEST",
    ]

from eliot import Field, ActionType

LOG_SYSTEM = u"api"

METHOD = Field(u"method", lambda method: method,
               u"The HTTP method of the request.")
REQUEST_PATH = Field(
    u"request_path", lambda path: path,
    u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
    u"json", [unicode, bytes, dict, list, None, bool, float],
    u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
    u"code", [int],
    u"The response code for the request.")

REQUEST = ActionType(
    LOG_SYSTEM + u":request",
    [REQUEST_PATH, METHOD],
    [],
    u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
    LOG_SYSTEM + u":json_request",
    [JSON],
    [RESPONSE_CODE, JSON],
    u"A request containing JSON request and response.")

Prompt:
Address review comment: Just pass through fields we aren't changing.

# Copyright Hybrid Logic Ltd.  See LICENSE file for details.

"""
This module defines the Eliot log events emitted by the API implementation.
"""

__all__ = [
    "JSON_REQUEST",
    "REQUEST",
    ]

from eliot import Field, ActionType

LOG_SYSTEM = u"api"

METHOD = Field.forTypes(
    u"method", [unicode, bytes], u"The HTTP method of the request.")
REQUEST_PATH = Field.forTypes(
    u"request_path", [unicode, bytes],
    u"The absolute path of the resource to which the request was issued.")
JSON = Field.forTypes(
    u"json", [unicode, bytes, dict, list, None, bool, float],
    u"JSON, either request or response depending on context.")
RESPONSE_CODE = Field.forTypes(
    u"code", [int],
    u"The response code for the request.")

REQUEST = ActionType(
    LOG_SYSTEM + u":request",
    [REQUEST_PATH, METHOD],
    [],
    u"A request was received on the public HTTP interface.")
JSON_REQUEST = ActionType(
    LOG_SYSTEM + u":json_request",
    [JSON],
    [RESPONSE_CODE, JSON],
    u"A request containing JSON request and response.")


from marshmallow import Schema, fields

class PetSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()

class SampleSchema(Schema):
    runs = fields.Nested('RunSchema', many=True, exclude=('sample',))

    count = fields.Int()

class RunSchema(Schema):
    sample = fields.Nested(SampleSchema, exclude=('runs',))

class AnalysisSchema(Schema):
    sample = fields.Nested(SampleSchema)

class AnalysisWithListSchema(Schema):
    samples = fields.List(fields.Nested(SampleSchema))

class AnalysisWithDictSchema(Schema):
    samplesDict = fields.Dict(values=fields.Nested(SampleSchema))

class PatternedObjectSchema(Schema):
    count = fields.Int(dump_only=True, **{'x-count': 1})
    count2 = fields.Int(dump_only=True, x_count2=2)

class SelfReferencingSchema(Schema):
    id = fields.Int()
    single = fields.Nested('self')
    single_with_ref = fields.Nested('self', ref='#/definitions/Self')
    many = fields.Nested('self', many=True)
    many_with_ref = fields.Nested('self', many=True, ref='#/definitions/Selves')

class OrderedSchema(Schema):
    field1 = fields.Int()
    field2 = fields.Int()
    field3 = fields.Int()
    field4 = fields.Int()
    field5 = fields.Int()

    class Meta:
        ordered = True

class DefaultCallableSchema(Schema):
    numbers = fields.List(fields.Int, missing=list)

Add schema with Dict field

Add schema with Dict field

Response:
<INSERT> AnalysisWithDictSchema(Schema):
    samplesDict = fields.Dict(values=fields.Nested(SampleSchema))

class <INSERT_END> <|endoftext|> from marshmallow import Schema, fields

class PetSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()

class SampleSchema(Schema):
    runs = fields.Nested('RunSchema', many=True, exclude=('sample',))

    count = fields.Int()

class RunSchema(Schema):
    sample = fields.Nested(SampleSchema, exclude=('runs',))

class AnalysisSchema(Schema):
    sample = fields.Nested(SampleSchema)

class AnalysisWithListSchema(Schema):
    samples = fields.List(fields.Nested(SampleSchema))

class AnalysisWithDictSchema(Schema):
    samplesDict = fields.Dict(values=fields.Nested(SampleSchema))

class PatternedObjectSchema(Schema):
    count = fields.Int(dump_only=True, **{'x-count': 1})
    count2 = fields.Int(dump_only=True, x_count2=2)

class SelfReferencingSchema(Schema):
    id = fields.Int()
    single = fields.Nested('self')
    single_with_ref = fields.Nested('self', ref='#/definitions/Self')
    many = fields.Nested('self', many=True)
    many_with_ref = fields.Nested('self', many=True, ref='#/definitions/Selves')

class OrderedSchema(Schema):
    field1 = fields.Int()
    field2 = fields.Int()
    field3 = fields.Int()
    field4 = fields.Int()
    field5 = fields.Int()

    class Meta:
        ordered = True

class DefaultCallableSchema(Schema):
    numbers = fields.List(fields.Int, missing=list)

Prompt:
Add schema with Dict field
from marshmallow import Schema, fields

class PetSchema(Schema):
    id = fields.Int(dump_only=True)
    name = fields.Str()

class SampleSchema(Schema):
    runs = fields.Nested('RunSchema', many=True, exclude=('sample',))

    count = fields.Int()

class RunSchema(Schema):
    sample = fields.Nested(SampleSchema, exclude=('runs',))

class AnalysisSchema(Schema):
    sample = fields.Nested(SampleSchema)

class AnalysisWithListSchema(Schema):
    samples = fields.List(fields.Nested(SampleSchema))

class PatternedObjectSchema(Schema):
    count = fields.Int(dump_only=True, **{'x-count': 1})
    count2 = fields.Int(dump_only=True, x_count2=2)

class SelfReferencingSchema(Schema):
    id = fields.Int()
    single = fields.Nested('self')
    single_with_ref = fields.Nested('self', ref='#/definitions/Self')
    many = fields.Nested('self', many=True)
    many_with_ref = fields.Nested('self', many=True, ref='#/definitions/Selves')

class OrderedSchema(Schema):
    field1 = fields.Int()
    field2 = fields.Int()
    field3 = fields.Int()
    field4 = fields.Int()
    field5 = fields.Int()

    class Meta:
        ordered = True

class DefaultCallableSchema(Schema):
    numbers = fields.List(fields.Int, missing=list)


# Sample extension: zoom a window to maximum height

import re
import sys

class ZoomHeight:

    menudefs = [
        ('windows', [
            ('_Zoom Height', '<<zoom-height>>'),
         ])
    ]

    windows_keydefs = {
        '<<zoom-height>>': ['<Alt-F2>'],
    }
    unix_keydefs = {
        '<<zoom-height>>': ['<Control-x><Control-z>'],
    }

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

    def zoom_height_event(self, event):
        top = self.editwin.top
        zoom_height(top)

def zoom_height(top):
    geom = top.wm_geometry()
    m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
    if not m:
        top.bell()
        return
    width, height, x, y = map(int, m.groups())
    newheight = top.winfo_screenheight()
    if sys.platform == 'win32':
        newy = 0
        newheight = newheight - 72
    else:
        newy = 24
        newheight = newheight - 96
    if height >= newheight:
        newgeom = ""
    else:
        newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
    top.wm_geometry(newgeom)

Response:
<INSERT> zoom_height(top)

def zoom_height(top):
    <INSERT_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <DELETE>     <DELETE_END> <|endoftext|> # Sample extension: zoom a window to maximum height

import re
import sys

class ZoomHeight:

    menudefs = [
        ('windows', [
            ('_Zoom Height', '<<zoom-height>>'),
         ])
    ]

    windows_keydefs = {
        '<<zoom-height>>': ['<Alt-F2>'],
    }
    unix_keydefs = {
        '<<zoom-height>>': ['<Control-x><Control-z>'],
    }

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

    def zoom_height_event(self, event):
        top = self.editwin.top
        zoom_height(top)

def zoom_height(top):
    geom = top.wm_geometry()
    m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
    if not m:
        top.bell()
        return
    width, height, x, y = map(int, m.groups())
    newheight = top.winfo_screenheight()
    if sys.platform == 'win32':
        newy = 0
        newheight = newheight - 72
    else:
        newy = 24
        newheight = newheight - 96
    if height >= newheight:
        newgeom = ""
    else:
        newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
    top.wm_geometry(newgeom)

Prompt:
Move zoom height functionality to separate function.

# Sample extension: zoom a window to maximum height

import re
import sys

class ZoomHeight:

    menudefs = [
        ('windows', [
            ('_Zoom Height', '<<zoom-height>>'),
         ])
    ]

    windows_keydefs = {
        '<<zoom-height>>': ['<Alt-F2>'],
    }
    unix_keydefs = {
        '<<zoom-height>>': ['<Control-x><Control-z>'],
    }

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

    def zoom_height_event(self, event):
        top = self.editwin.top
        geom = top.wm_geometry()
        m = re.match(r"(\d+)x(\d+)\+(-?\d+)\+(-?\d+)", geom)
        if not m:
            top.bell()
            return
        width, height, x, y = map(int, m.groups())
        newheight = top.winfo_screenheight()
        if sys.platform == 'win32':
            newy = 0
            newheight = newheight - 72
        else:
            newy = 24
            newheight = newheight - 96
        if height >= newheight:
            newgeom = ""
        else:
            newgeom = "%dx%d+%d+%d" % (width, newheight, x, newy)
        top.wm_geometry(newgeom)


from unittest import TestCase

from ddt import ddt, data
from aioresponses.compat import (
    _vanilla_merge_url_params, _yarl_merge_url_params, URL
)

@ddt
class CompatTestCase(TestCase):
    use_default_loop = False

    def setUp(self):
        self.url = 'http://example.com/api?foo=bar#fragment'
        self.yarn_available = isinstance(URL, str)

    def _get_merge_functions(self):
        if self.yarn_available:
            return {
                _vanilla_merge_url_params,
                _yarl_merge_url_params
            }
        return {
            _vanilla_merge_url_params,
        }

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_no_params_returns_same_url(self, func):
        if func in self._get_merge_functions():
            self.assertEqual(func(self.url, None), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_empty_params_returns_same_url(self, func):
        if func in self._get_merge_functions():
            self.assertEqual(func(self.url, {}), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_params_returns_corrected_url(self, func):
        if func in self._get_merge_functions():
            expected_url = 'http://example.com/api?foo=bar&x=42#fragment'
            self.assertEqual(func(self.url, {'x': 42}), expected_url)

Fix tests when yarn is not available

Fix tests when yarn is not available

Response:
<REPLACE_OLD> _yarl_merge_url_params
)

@ddt
class <REPLACE_NEW> _yarl_merge_url_params, URL
)

@ddt
class <REPLACE_END> <REPLACE_OLD> 'http://example.com/api?foo=bar#fragment'

 <REPLACE_NEW> 'http://example.com/api?foo=bar#fragment'
        self.yarn_available = isinstance(URL, str)

    def _get_merge_functions(self):
        if self.yarn_available:
            return {
                _vanilla_merge_url_params,
                _yarl_merge_url_params
            }
        return {
            _vanilla_merge_url_params,
        }

 <REPLACE_END> <INSERT>        if func in self._get_merge_functions():
     <INSERT_END> <INSERT> if func in self._get_merge_functions():
            <INSERT_END> <INSERT> if func in self._get_merge_functions():
            <INSERT_END> <INSERT>     <INSERT_END> <|endoftext|> from unittest import TestCase

from ddt import ddt, data
from aioresponses.compat import (
    _vanilla_merge_url_params, _yarl_merge_url_params, URL
)

@ddt
class CompatTestCase(TestCase):
    use_default_loop = False

    def setUp(self):
        self.url = 'http://example.com/api?foo=bar#fragment'
        self.yarn_available = isinstance(URL, str)

    def _get_merge_functions(self):
        if self.yarn_available:
            return {
                _vanilla_merge_url_params,
                _yarl_merge_url_params
            }
        return {
            _vanilla_merge_url_params,
        }

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_no_params_returns_same_url(self, func):
        if func in self._get_merge_functions():
            self.assertEqual(func(self.url, None), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_empty_params_returns_same_url(self, func):
        if func in self._get_merge_functions():
            self.assertEqual(func(self.url, {}), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_params_returns_corrected_url(self, func):
        if func in self._get_merge_functions():
            expected_url = 'http://example.com/api?foo=bar&x=42#fragment'
            self.assertEqual(func(self.url, {'x': 42}), expected_url)

Prompt:
Fix tests when yarn is not available

from unittest import TestCase

from ddt import ddt, data
from aioresponses.compat import (
    _vanilla_merge_url_params, _yarl_merge_url_params
)

@ddt
class CompatTestCase(TestCase):
    use_default_loop = False

    def setUp(self):
        self.url = 'http://example.com/api?foo=bar#fragment'

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_no_params_returns_same_url(self, func):
        self.assertEqual(func(self.url, None), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_empty_params_returns_same_url(self, func):
        self.assertEqual(func(self.url, {}), self.url)

    @data(
        _vanilla_merge_url_params,
        _yarl_merge_url_params
    )
    def test_params_returns_corrected_url(self, func):
        expected_url = 'http://example.com/api?foo=bar&x=42#fragment'
        self.assertEqual(func(self.url, {'x': 42}), expected_url)


# coding: utf-8

from __future__ import unicode_literals
from io import StringIO

import pytest

word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
  -1.499184 -0.184280 -0.598371"""

@pytest.mark.xfail
def test_issue834(en_vocab):
    f = StringIO(word2vec_str)
    vector_length = en_vocab.load_vectors(f)
    assert vector_length == 3

Mark vectors test as xfail (temporary)

Mark vectors test as xfail (temporary)

Response:
<REPLACE_OLD> StringIO

word2vec_str <REPLACE_NEW> StringIO

import pytest

word2vec_str <REPLACE_END> <REPLACE_OLD> -0.598371"""

def <REPLACE_NEW> -0.598371"""

@pytest.mark.xfail
def <REPLACE_END> <|endoftext|> # coding: utf-8

from __future__ import unicode_literals
from io import StringIO

import pytest

word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
  -1.499184 -0.184280 -0.598371"""

@pytest.mark.xfail
def test_issue834(en_vocab):
    f = StringIO(word2vec_str)
    vector_length = en_vocab.load_vectors(f)
    assert vector_length == 3

Prompt:
Mark vectors test as xfail (temporary)

# coding: utf-8

from __future__ import unicode_literals
from io import StringIO

word2vec_str = """, -0.046107 -0.035951 -0.560418
de -0.648927 -0.400976 -0.527124
. 0.113685 0.439990 -0.634510
  -1.499184 -0.184280 -0.598371"""

def test_issue834(en_vocab):
    f = StringIO(word2vec_str)
    vector_length = en_vocab.load_vectors(f)
    assert vector_length == 3


import logging
from rackattack.ssh import connection

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.ERROR)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
handler = logging.FileHandler("/var/log/rackattack.physical.network.log")
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger('network').addHandler(handler)
connection.discardParamikoLogs()
connection.discardSSHDebugMessages()
logging.getLogger("pika").setLevel(logging.INFO)

Response:
<REPLACE_OLD> %(message)s')
logging.getLogger('network').setLevel(logging.DEBUG)
logging.getLogger('network').propagate <REPLACE_NEW> %(message)s')
logging.getLogger('network').setLevel(logging.ERROR)
logging.getLogger('network').propagate <REPLACE_END> <|endoftext|> import logging
from rackattack.ssh import connection

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.ERROR)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
handler = logging.FileHandler("/var/log/rackattack.physical.network.log")
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger('network').addHandler(handler)
connection.discardParamikoLogs()
connection.discardSSHDebugMessages()
logging.getLogger("pika").setLevel(logging.INFO)

Prompt:
Set the log level of the network logger to ERROR, since it's less needed now

import logging
from rackattack.ssh import connection

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logging.getLogger('network').setLevel(logging.DEBUG)
logging.getLogger('network').propagate = False
logging.getLogger().setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
handler = logging.FileHandler("/var/log/rackattack.physical.network.log")
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
logging.getLogger('network').addHandler(handler)
connection.discardParamikoLogs()
connection.discardSSHDebugMessages()
logging.getLogger("pika").setLevel(logging.INFO)


import json
import logging
import urllib.request

from discord.ext import commands
from discord.ext.commands import CommandError, Context

from cogbot import checks
from cogbot.cog_bot import CogBot

log = logging.getLogger(__name__)

class FaqConfig:
    def __init__(self, **options):
        self.database = options['database']

class Faq:
    def __init__(self, bot: CogBot, ext: str):
        self.bot = bot
        options = bot.state.get_extension_state(ext)
        self.config = FaqConfig(**options)
        self.data = {}

    def get_answer_by_key(self, key: str):
        return self.data.get(key)

    def get_all_keys(self):
        return self.data.keys()

    def reload_data(self):
        log.info('Reloading FAQs from: {}'.format(self.config.database))

        response = urllib.request.urlopen(self.config.database)
        content = response.read().decode('utf8')

        try:
            data = json.loads(content)
        except Exception as e:
            raise CommandError('Failed to reload FAQs: {}'.format(e))

        self.data = data

        log.info('Successfully reloaded {} FAQs'.format(len(data)))

    async def on_ready(self):
        self.reload_data()

    @commands.command(pass_context=True, name='faq')
    async def cmd_faq(self, ctx: Context, *, key: str = ''):
        if key:
            answer = self.get_answer_by_key(key)
            if answer:
                await self.bot.say(answer)
            else:
                await self.bot.add_reaction(ctx.message, u'🤷')

        else:
            await self.bot.say(', '.join(self.get_all_keys()))

    @checks.is_manager()
    @commands.command(pass_context=True, name='faqreload', hidden=True)
    async def cmd_faqreload(self, ctx: Context):
        try:
            self.reload_data()
            await self.bot.react_success(ctx)
        except:
            await self.bot.react_failure(ctx)

def setup(bot):
    bot.add_cog(Faq(bot, __name__))

Implement basic FAQ command with remote config

Response:
<REPLACE_OLD>  <REPLACE_NEW> import json
import logging
import urllib.request

from discord.ext import commands
from discord.ext.commands import CommandError, Context

from cogbot import checks
from cogbot.cog_bot import CogBot

log = logging.getLogger(__name__)

class FaqConfig:
    def __init__(self, **options):
        self.database = options['database']

class Faq:
    def __init__(self, bot: CogBot, ext: str):
        self.bot = bot
        options = bot.state.get_extension_state(ext)
        self.config = FaqConfig(**options)
        self.data = {}

    def get_answer_by_key(self, key: str):
        return self.data.get(key)

    def get_all_keys(self):
        return self.data.keys()

    def reload_data(self):
        log.info('Reloading FAQs from: {}'.format(self.config.database))

        response = urllib.request.urlopen(self.config.database)
        content = response.read().decode('utf8')

        try:
            data = json.loads(content)
        except Exception as e:
            raise CommandError('Failed to reload FAQs: {}'.format(e))

        self.data = data

        log.info('Successfully reloaded {} FAQs'.format(len(data)))

    async def on_ready(self):
        self.reload_data()

    @commands.command(pass_context=True, name='faq')
    async def cmd_faq(self, ctx: Context, *, key: str = ''):
        if key:
            answer = self.get_answer_by_key(key)
            if answer:
                await self.bot.say(answer)
            else:
                await self.bot.add_reaction(ctx.message, u'🤷')

        else:
            await self.bot.say(', '.join(self.get_all_keys()))

    @checks.is_manager()
    @commands.command(pass_context=True, name='faqreload', hidden=True)
    async def cmd_faqreload(self, ctx: Context):
        try:
            self.reload_data()
            await self.bot.react_success(ctx)
        except:
            await self.bot.react_failure(ctx)

def setup(bot):
    bot.add_cog(Faq(bot, __name__))
 <REPLACE_END> <|endoftext|> import json
import logging
import urllib.request

from discord.ext import commands
from discord.ext.commands import CommandError, Context

from cogbot import checks
from cogbot.cog_bot import CogBot

log = logging.getLogger(__name__)

class FaqConfig:
    def __init__(self, **options):
        self.database = options['database']

class Faq:
    def __init__(self, bot: CogBot, ext: str):
        self.bot = bot
        options = bot.state.get_extension_state(ext)
        self.config = FaqConfig(**options)
        self.data = {}

    def get_answer_by_key(self, key: str):
        return self.data.get(key)

    def get_all_keys(self):
        return self.data.keys()

    def reload_data(self):
        log.info('Reloading FAQs from: {}'.format(self.config.database))

        response = urllib.request.urlopen(self.config.database)
        content = response.read().decode('utf8')

        try:
            data = json.loads(content)
        except Exception as e:
            raise CommandError('Failed to reload FAQs: {}'.format(e))

        self.data = data

        log.info('Successfully reloaded {} FAQs'.format(len(data)))

    async def on_ready(self):
        self.reload_data()

    @commands.command(pass_context=True, name='faq')
    async def cmd_faq(self, ctx: Context, *, key: str = ''):
        if key:
            answer = self.get_answer_by_key(key)
            if answer:
                await self.bot.say(answer)
            else:
                await self.bot.add_reaction(ctx.message, u'🤷')

        else:
            await self.bot.say(', '.join(self.get_all_keys()))

    @checks.is_manager()
    @commands.command(pass_context=True, name='faqreload', hidden=True)
    async def cmd_faqreload(self, ctx: Context):
        try:
            self.reload_data()
            await self.bot.react_success(ctx)
        except:
            await self.bot.react_failure(ctx)

def setup(bot):
    bot.add_cog(Faq(bot, __name__))

Prompt: Implement basic FAQ command with remote config


from __future__ import print_function
import sys
import hashlib
import base64

def print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def to_unicode(content):
    # TODO: considering using the 'six' library for this, for now just do something simple.
    if sys.version_info >= (3,0):
        return str(content)
    elif sys.version_info < (3,0):
        return unicode(content)

def sha256hash(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return hashlib.sha256(content).hexdigest()

def base64encode(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return to_unicode(base64.b64encode(content))

def _is_unicode(content):
    if (sys.version_info >= (3,0) and isinstance(content, str)
        or sys.version_info < (3,0) and isinstance(content, unicode)):
        return True
    return False

Response:
<REPLACE_OLD> base64.b64encode(content)

def <REPLACE_NEW> to_unicode(base64.b64encode(content))

def <REPLACE_END> <|endoftext|> from __future__ import print_function
import sys
import hashlib
import base64

def print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def to_unicode(content):
    # TODO: considering using the 'six' library for this, for now just do something simple.
    if sys.version_info >= (3,0):
        return str(content)
    elif sys.version_info < (3,0):
        return unicode(content)

def sha256hash(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return hashlib.sha256(content).hexdigest()

def base64encode(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return to_unicode(base64.b64encode(content))

def _is_unicode(content):
    if (sys.version_info >= (3,0) and isinstance(content, str)
        or sys.version_info < (3,0) and isinstance(content, unicode)):
        return True
    return False

Prompt:
Return serializable string from base64encode.

from __future__ import print_function
import sys
import hashlib
import base64

def print_error(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

def to_unicode(content):
    # TODO: considering using the 'six' library for this, for now just do something simple.
    if sys.version_info >= (3,0):
        return str(content)
    elif sys.version_info < (3,0):
        return unicode(content)

def sha256hash(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return hashlib.sha256(content).hexdigest()

def base64encode(content):
    if _is_unicode(content):
        content = content.encode('utf-8')
    return base64.b64encode(content)

def _is_unicode(content):
    if (sys.version_info >= (3,0) and isinstance(content, str)
        or sys.version_info < (3,0) and isinstance(content, unicode)):
        return True
    return False


#! /usr/bin/env python3

from sys import stdin

def part_count(lemma):
    return lemma.count('#')

def compile_dict(label_lemma_pairs):
    res = {}

    for label, lemma in label_lemma_pairs:
        if label in res:
            old_lemma = res[label]

            if part_count(old_lemma) > part_count(lemma):
                res[label] = lemma
        else:
            res[label] = lemma

    return res

for line in stdin:
    line = line.strip()

    if line == '':
        print('')
    else:
        wf, feats, lemma, label, ann = line.split('\t')

        lemmas = ann
        if ann.find(' ') != -1:
            lemmas = ann[:ann.find(' ')]
            ann = ann[ann.find(' ') + 1:]
        else:
            ann = '_'

        lemma_dict = {}
        if lemmas != '_':
            lemma_dict = compile_dict(eval(lemmas))

        if label in lemma_dict:
            lemma = lemma_dict[label]
            lemma = lemma.lower()
            lemma = lemma.replace('#','')

        print('%s\t%s\t%s\t%s\t%s' % (wf, feats, lemma, label, ann))

Choose lemma with fewest parts.

Choose lemma with fewest parts.

Response:
<REPLACE_OLD> stdin

for <REPLACE_NEW> stdin

def part_count(lemma):
    return lemma.count('#')

def compile_dict(label_lemma_pairs):
    res = {}

    for label, lemma in label_lemma_pairs:
        if label in res:
            old_lemma = res[label]

            if part_count(old_lemma) > part_count(lemma):
                res[label] = lemma
        else:
            res[label] = lemma

    return res

for <REPLACE_END> <REPLACE_OLD> [ann.find(' '):]

 <REPLACE_NEW> ann[ann.find(' ') + 1:]
        else:
            ann = '_'

 <REPLACE_END> <REPLACE_OLD> dict(eval(ann))
 <REPLACE_NEW> {}
        if lemmas != '_':
            lemma_dict = compile_dict(eval(lemmas))
 <REPLACE_END> <|endoftext|> #! /usr/bin/env python3

from sys import stdin

def part_count(lemma):
    return lemma.count('#')

def compile_dict(label_lemma_pairs):
    res = {}

    for label, lemma in label_lemma_pairs:
        if label in res:
            old_lemma = res[label]

            if part_count(old_lemma) > part_count(lemma):
                res[label] = lemma
        else:
            res[label] = lemma

    return res

for line in stdin:
    line = line.strip()

    if line == '':
        print('')
    else:
        wf, feats, lemma, label, ann = line.split('\t')

        lemmas = ann
        if ann.find(' ') != -1:
            lemmas = ann[:ann.find(' ')]
            ann = ann[ann.find(' ') + 1:]
        else:
            ann = '_'

        lemma_dict = {}
        if lemmas != '_':
            lemma_dict = compile_dict(eval(lemmas))

        if label in lemma_dict:
            lemma = lemma_dict[label]
            lemma = lemma.lower()
            lemma = lemma.replace('#','')

        print('%s\t%s\t%s\t%s\t%s' % (wf, feats, lemma, label, ann))

Prompt:
Choose lemma with fewest parts.

#! /usr/bin/env python3

from sys import stdin

for line in stdin:
    line = line.strip()

    if line == '':
        print('')
    else:
        wf, feats, lemma, label, ann = line.split('\t')

        lemmas = ann
        if ann.find(' ') != -1:
            lemmas = ann[:ann.find(' ')]
            ann = [ann.find(' '):]

        lemma_dict = dict(eval(ann))

        if label in lemma_dict:
            lemma = lemma_dict[label]
            lemma = lemma.lower()
            lemma = lemma.replace('#','')

        print('%s\t%s\t%s\t%s\t%s' % (wf, feats, lemma, label, ann))