Skip to content

Instantly share code, notes, and snippets.

@breandan
Last active October 30, 2022 04:39
Show Gist options
  • Save breandan/13837785e1781f004735f55f430e830c to your computer and use it in GitHub Desktop.
Save breandan/13837785e1781f004735f55f430e830c to your computer and use it in GitHub Desktop.
SetValiant with accuracy@top-1 repairs.
Original error:
'''Test NetRpcNfs() functionally'''
from lnxproc import netrpcnfs
from.output import test_module
test_module(netrpcnfs.NetRpcNfs()
Good Repair:
'''Test NetRpcNfs() functionally'''
from lnxproc import netrpcnfs
from.output import test_module
** test_modulenetrpcnfs.NetRpcNfs()
Synthesized repair in: 4439ms
Tidyparse (valid/total): 1/1
Original error:
def get_absolute_url(self):
return('activity_item', None, {
'username': self.actor.username,
'id': self.id
Bad Repair: unexpected indent (<unknown>, line 3):
def get_absolute_url(self):
** return('activity_item', None, )
'username': self.actor.username,
'id': self.id
Synthesized repair in: 5341ms
Tidyparse (valid/total): 1/2
Original error:
def SortResults(self, field):
"""Sort the result set."""
logging.debug("Sorting %d results", len(self.results)
self.results.sort(key = lambda x: str(x.get(field, "")))
Bad Repair: invalid syntax (<unknown>, line 3):
def SortResults(self, field):
"""Sort the result set."""
** logging.debug"Sorting %d results", len(self.results)
self.results.sort(key = lambda x: str(x.get(field, "")))
Synthesized repair in: 10148ms
Tidyparse (valid/total): 1/3
Original error:
def tmp_space():
tmp_usage = "du"
tmp_arg = "-h"
path = "/tmp"
print("Spaece use in /tmp directory")
subprocess.call([tmp_usage, tmp_arg, path]
Good Repair:
def tmp_space():
tmp_usage = "du"
tmp_arg = "-h"
path = "/tmp"
print("Spaece use in /tmp directory")
** subprocess.call[tmp_usage, tmp_arg, path]
Synthesized repair in: 11933ms
Tidyparse (valid/total): 2/4
Original error:
def _get_api_key():
apikey = ThirtyBoxes._api_key_from_env()
if apikey is None:
if __name__ == "__main__":
first_opt = "1. use the -k|--api-key option,"
else:
first_opt = "1. use the apiKey argument,"
raise ThirtyBoxesError("""could not determine API key:"""
Bad Repair: invalid syntax (<unknown>, line 8):
def _get_api_key():
apikey = ThirtyBoxes._api_key_from_env()
if apikey is None:
if __name__ == "__main__":
first_opt = "1. use the -k|--api-key option,"
else:
first_opt = "1. use the apiKey argument,"
** raise ThirtyBoxesError"""could not determine API key:"""
Synthesized repair in: 2503ms
Tidyparse (valid/total): 2/5
Original error:
import sys, os
sys.path.insert(0, os.path.abspath('..')))
import unittest, grid_search, utils, ga, optimization, time, numpy, itertools, pandas, seaborn, matplotlib
Good Repair:
import sys, os
** sys.path.insert(0, os.path.abspath('..'))
import unittest, grid_search, utils, ga, optimization, time, numpy, itertools, pandas, seaborn, matplotlib
Synthesized repair in: 2873ms
Tidyparse (valid/total): 3/6
Original error:
import os
import unittest2
import tempfile
from pyoram.util.virtual_heap import SizedVirtualHeap
from pyoram.storage.block_storage import BlockStorageTypeFactory
from pyoram.encrypted_storage.encrypted_block_storage import EncryptedBlockStorage
from pyoram.encrypted_storage.encrypted_heap_storage import EncryptedHeapStorage
from pyoram.crypto.aes import AES
from six.moves import xrange
thisdir = os.path.dirname(os.path.abspath(__file__)))
Good Repair:
import os
import unittest2
import tempfile
from pyoram.util.virtual_heap import SizedVirtualHeap
from pyoram.storage.block_storage import BlockStorageTypeFactory
from pyoram.encrypted_storage.encrypted_block_storage import EncryptedBlockStorage
from pyoram.encrypted_storage.encrypted_heap_storage import EncryptedHeapStorage
from pyoram.crypto.aes import AES
from six.moves import xrange
** thisdir = os.path.dirname(os.path.abspath(__file__))
Synthesized repair in: 1749ms
Tidyparse (valid/total): 4/7
Original error:
def check_arp_header_match():
result = checks.arp_header_match_supported()
if not result:
LOG.error(_LE('Check for Open vSwitch support of ARP header matching '
'failed.ARP spoofing suppression will not work.A '
'newer version of OVS is required.')
return result
Good Repair:
def check_arp_header_match():
result = checks.arp_header_match_supported()
if not result:
** LOG.error_LE('Check for Open vSwitch support of ARP header matching '
'failed.ARP spoofing suppression will not work.A '
'newer version of OVS is required.')
return result
Synthesized repair in: 5966ms
Tidyparse (valid/total): 5/8
Original error:
import asyncio
import datetime
import jwe
import jwt
import aiohttp
from waterbutler.core import auth
from waterbutler.core import exceptions
from waterbutler.auth.osf import settings
JWE_KEY = jwe.kdf(settings.JWE_SECRET.encode(), settings.JWE_SALT.encode()
Good Repair:
import asyncio
import datetime
import jwe
import jwt
import aiohttp
from waterbutler.core import auth
from waterbutler.core import exceptions
from waterbutler.auth.osf import settings
** JWE_KEY = jwe.kdf(settings.JWE_SECRET.encode), settings.JWE_SALT.encode()
Synthesized repair in: 1574ms
Tidyparse (valid/total): 6/9
Original error:
from argparse import ArgumentParser
if __name__ == "__main__" and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))
from infrastructure import Infrastructure, enable_debug
else:
from..infrastructure import Infrastructure, enable_debug
Good Repair:
from argparse import ArgumentParser
if __name__ == "__main__" and __package__ is None:
from os import sys, path
** sys.path.append(path.dirname(path.dirnamepath.abspath(__file__)))
from infrastructure import Infrastructure, enable_debug
else:
from..infrastructure import Infrastructure, enable_debug
Synthesized repair in: 3078ms
Tidyparse (valid/total): 7/10
Original error:
def service_list(cls, deployment):
"""Get the services list."""
clients = osclients.Clients(objects.Credential(** deployment["admin"])
return clients.services()
Bad Repair: invalid syntax (<unknown>, line 4):
def service_list(cls, deployment):
"""Get the services list."""
clients = osclients.Clients(objects.Credential(** deployment["admin"])
** return clients.services)
Synthesized repair in: 21363ms
Tidyparse (valid/total): 7/11
Original error:
def placeMob(self, x, y):
self.dict_objects['mobs'].append((x, y)
print("M %s" % self.dict_objects['towers'])
Bad Repair: invalid syntax (<unknown>, line 3):
def placeMob(self, x, y):
self.dict_objects['mobs'].append((x, y)
** print"M %s" % self.dict_objects['towers'])
Synthesized repair in: 12673ms
Tidyparse (valid/total): 7/12
Original error:
def __init__(self, name, data, files = (), dirs = ():
self.__name = name
self.__data = data
self.__files = files
self.__dirs = dirs
self.__lines = None
Bad Repair: invalid syntax (<unknown>, line 1):
** def __init__(self, name, data, files = ), dirs = ():
self.__name = name
self.__data = data
self.__files = files
self.__dirs = dirs
self.__lines = None
Synthesized repair in: 7678ms
Tidyparse (valid/total): 7/13
Original error:
def randOct(x, y):
x = int(x)
y = int(y)
return str(random.randint(x, y)
Good Repair:
def randOct(x, y):
x = int(x)
y = int(y)
** return str(random.randintx, y)
Synthesized repair in: 31256ms
Tidyparse (valid/total): 8/14
Original error:
def get_solr_kwargs(self):
solr_kw = {
'facet': 'on', 'facet.field': facet_field_list, 'start': self.result_start_offset
, 'rows': self.num_display_rows
, 'hl': 'true', 'hl.fragsize': 500, 'hl.fl': highlight_field_list
if self.stats_on:
solr_kw.update({'stats': 'true', 'stats.field': ['dvtype', 'subject_ss']})
return solr_kw
Bad Repair: invalid syntax (<unknown>, line 2):
def get_solr_kwargs(self):
** solr_kw =
'facet': 'on', 'facet.field': facet_field_list, 'start': self.result_start_offset
, 'rows': self.num_display_rows
, 'hl': 'true', 'hl.fragsize': 500, 'hl.fl': highlight_field_list
if self.stats_on:
solr_kw.update({'stats': 'true', 'stats.field': ['dvtype', 'subject_ss']})
return solr_kw
Synthesized repair in: 37667ms
Tidyparse (valid/total): 8/15
Original error:
def print_page(request, id, pin):
check_inputs(id, pin)
con = Connection.objects.get(id = id)
translation.activate(brain.get_user_lang(con.telegram_id)))
message_link = HPQR_HOST + "/" + id + "." + pin
return render(request, 'print.html', {'message_link': message_link, 'HPQR_YANDEX_METRIKA': HPQR_YANDEX_METRIKA})
Bad Repair: invalid syntax (<unknown>, line 3):
** def print_page(request, id, pin:
check_inputs(id, pin)
con = Connection.objects.get(id = id)
translation.activate(brain.get_user_lang(con.telegram_id)))
message_link = HPQR_HOST + "/" + id + "." + pin
return render(request, 'print.html', {'message_link': message_link, 'HPQR_YANDEX_METRIKA': HPQR_YANDEX_METRIKA})
Synthesized repair in: 38954ms
Tidyparse (valid/total): 8/16
Original error:
import heapq
import sys
import os
cwd = os.getcwd()
if cwd not in sys.path:
sys.path.insert(0, os.getcwd()
import ipool.ipool as ipool
import data_api
Good Repair:
import heapq
import sys
import os
cwd = os.getcwd()
if cwd not in sys.path:
** sys.path.insert(0, os.getcwd)
import ipool.ipool as ipool
import data_api
Synthesized repair in: 14450ms
Tidyparse (valid/total): 9/17
Original error:
def check_supported_events_narrow_filter(narrow):
for element in narrow:
operator = element[0]
if operator not in["stream", "topic", "sender", "is"]:
raise JsonableError(_("Operator %s not supported.") %(operator, )
Good Repair:
def check_supported_events_narrow_filter(narrow):
for element in narrow:
operator = element[0]
if operator not in["stream", "topic", "sender", "is"]:
** raise JsonableError_("Operator %s not supported.") %(operator, )
Synthesized repair in: 41441ms
Tidyparse (valid/total): 10/18
Original error:
def _target_config():
global _targets
if not _targets:
_targets = ConfigParser.RawConfigParser()
_targets.readfp(StringIO.StringIO(_targets_ini)
return _targets
Good Repair:
def _target_config():
global _targets
if not _targets:
_targets = ConfigParser.RawConfigParser()
** _targets.readfpStringIO.StringIO(_targets_ini)
return _targets
Synthesized repair in: 22973ms
Tidyparse (valid/total): 11/19
Original error:
def test_1channel_update_from_vector():
im = MaskedImage.init_blank((10, 10)
update_im_from_vector(im)
Bad Repair: invalid syntax (<unknown>, line 3):
def test_1channel_update_from_vector():
im = MaskedImage.init_blank((10, 10)
** update_im_from_vectorim)
Synthesized repair in: 3427ms
Tidyparse (valid/total): 11/20
Original error:
def _npm(build, * args, ** kw):
if sys.platform.startswith("win"):
npm = "npm.cmd"
else:
npm = "npm"
if not utils.which(npm):
raise WebError("""Couldn't find {tool} on your PATH or in likely locations - is it installed?"""
Bad Repair: invalid syntax (<unknown>, line 7):
def _npm(build, * args, ** kw):
if sys.platform.startswith("win"):
npm = "npm.cmd"
else:
npm = "npm"
if not utils.which(npm):
** raise WebError"""Couldn't find {tool} on your PATH or in likely locations - is it installed?"""
Synthesized repair in: 19005ms
Tidyparse (valid/total): 11/21
Original error:
def _handler_autosample_enter(self, * args, ** kwargs):
"""Enter autosample state."""
self._init_params()
for stream_name in self._param_dict.get_keys():
self._create_scheduler(stream_name, self._param_dict.get(stream_name)))
self._driver_event(DriverAsyncEvent.STATE_CHANGE)
Bad Repair: invalid syntax (<unknown>, line 4):
def _handler_autosample_enter(self, * args, ** kwargs):
"""Enter autosample state."""
self._init_params()
** for stream_name in self._param_dict.get_keys(:
self._create_scheduler(stream_name, self._param_dict.get(stream_name)))
self._driver_event(DriverAsyncEvent.STATE_CHANGE)
Synthesized repair in: 15102ms
Tidyparse (valid/total): 11/22
Original error:
def _parameter_added_cb(self, sender, name):
for func in('get_%s' % name, 'set_%s' % name):
if hasattr(self._ins, func):
setattr(self, func, getattr(self._ins, func)))
Good Repair:
def _parameter_added_cb(self, sender, name):
for func in('get_%s' % name, 'set_%s' % name):
if hasattr(self._ins, func):
** setattr(self, func, getattr(self._ins, func))
Synthesized repair in: 33907ms
Tidyparse (valid/total): 12/23
Original error:
def _getName(self):
name = re.search(self.PATTERN_FILENAME, self.html)
if name is None:
self.fail(_("Plugin broken")
return name.group(1)
Bad Repair: invalid syntax (<unknown>, line 5):
def _getName(self):
name = re.search(self.PATTERN_FILENAME, self.html)
if name is None:
self.fail(_("Plugin broken")
** return name.group1)
Synthesized repair in: 12350ms
Tidyparse (valid/total): 12/24
Original error:
"""<DefineSource>"""
import ShareYourSystem as SYS
BaseModuleStr = "ShareYourSystem.Standards.Classors.Deriver")
DecorationModule = BaseModule
SYS.setSubModule(globals())
import inspect
import collections
from ShareYourSystem.Standards.Objects import Initiator
PropertizingGetStr = "_"
PropertizingRepresentationStr = "p:"
Good Repair:
"""<DefineSource>"""
import ShareYourSystem as SYS
** BaseModuleStr = "ShareYourSystem.Standards.Classors.Deriver"
DecorationModule = BaseModule
SYS.setSubModule(globals())
import inspect
import collections
from ShareYourSystem.Standards.Objects import Initiator
PropertizingGetStr = "_"
PropertizingRepresentationStr = "p:"
Synthesized repair in: 22364ms
Tidyparse (valid/total): 13/25
Original error:
def test_sanitize(self):
self.assertEqual(
sanitize('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12'
Bad Repair: invalid syntax (<unknown>, line 3):
def test_sanitize(self):
self.assertEqual(
** sanitize)'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12'
Synthesized repair in: 3198ms
Tidyparse (valid/total): 13/26
Original error:
def get_parser():
"""Get an ArgumentParser."""
parser = argparse.ArgumentParser(description = 'Data loader.')
parser.add_argument('data_file', type = argparse.FileType()
return parser
Bad Repair: invalid syntax (<unknown>, line 4):
def get_parser():
"""Get an ArgumentParser."""
parser = argparse.ArgumentParser(description = 'Data loader.')
** parser.add_argument'data_file', type = argparse.FileType()
return parser
Synthesized repair in: 24414ms
Tidyparse (valid/total): 13/27
Original error:
def print_tcp(tcp, margin):
fl = ''
if tcp.urg_flag:
fl += 'U'
if tcp.psh_flag:
fl += 'P'
if tcp.rst_flag:
fl += 'R'
if tcp.fin_flag:
fl += 'F'
if tcp.syn_flag:
fl += 'S'
if tcp.ack_flag:
fl += 'A'
print("TCP, %s -> %s, %d -> %d, seq=%u, ack=%u" %(
tcp.src_prefix, tcp.dst_prefix, tcp.src_port, tcp.dst_port,
tcp.seq_nbr, tcp.ack_nbr))
print(" flags=%02x (%s), window=%u, checksum=%x, urg_ptr=%u" %(
tcp.flags, fl, tcp.window, tcp.checksum, tcp.urg_ptr),
payload = tcp.payload
if not payload:
print(", no payload")
else:
pd = payload.data
print_data("\n payload ", margin, pd, 64)
Bad Repair: invalid syntax (<unknown>, line 21):
def print_tcp(tcp, margin):
fl = ''
if tcp.urg_flag:
fl += 'U'
if tcp.psh_flag:
fl += 'P'
if tcp.rst_flag:
fl += 'R'
if tcp.fin_flag:
fl += 'F'
if tcp.syn_flag:
fl += 'S'
if tcp.ack_flag:
fl += 'A'
print("TCP, %s -> %s, %d -> %d, seq=%u, ack=%u" %(
tcp.src_prefix, tcp.dst_prefix, tcp.src_port, tcp.dst_port,
tcp.seq_nbr, tcp.ack_nbr))
** print(" flags=%02x %s), window=%u, checksum=%x, urg_ptr=%u" %(
tcp.flags, fl, tcp.window, tcp.checksum, tcp.urg_ptr),
payload = tcp.payload
if not payload:
print(", no payload")
else:
pd = payload.data
print_data("\n payload ", margin, pd, 64)
Synthesized repair in: 75349ms
Tidyparse (valid/total): 13/28
Original error:
def generate_random_id__uuid():
"""generate a random UUID based string ID"""
return str(uuid.uuid4()
Good Repair:
def generate_random_id__uuid():
"""generate a random UUID based string ID"""
** return struuid.uuid4()
Synthesized repair in: 12380ms
Tidyparse (valid/total): 14/29
Original error:
def basic_data():
testcsv = """ Date, A, B, C, D"""
return pandas.read_csv(StringIO(dedent(testcsv), index_col = ['Date'])
Good Repair:
def basic_data():
testcsv = """ Date, A, B, C, D"""
** return pandas.read_csvStringIO(dedent(testcsv), index_col = ['Date'])
Synthesized repair in: 57812ms
Tidyparse (valid/total): 15/30
Original error:
import requests
parameters = {'key': '94e4f86021169ee84b3fac03a466638f', 'q': 'shredded%20chicken'}
response = requests.get{'http://food2fork.com/api/search', params = parameters)
print(response.content)
Bad Repair: invalid syntax (<unknown>, line 3):
import requests
parameters = {'key': '94e4f86021169ee84b3fac03a466638f', 'q': 'shredded%20chicken'}
** response = requests.get{'http://food2fork.com/api/search', params = parameters}
print(response.content)
Synthesized repair in: 15451ms
Tidyparse (valid/total): 15/31
Original error:
def selectByStudentnumber(db_users, studentnumber):
s = db_users.session()
ret = s.query(User).options(eagerload_all('addresses').filter(User.__table__.c.studentnumber == studentnumber).one()
s.close()
return ret
Bad Repair: invalid syntax (<unknown>, line 3):
def selectByStudentnumber(db_users, studentnumber):
s = db_users.session()
** ret = s.query(User).options(eagerload_all'addresses').filter(User.__table__.c.studentnumber == studentnumber).one()
s.close()
return ret
Synthesized repair in: 49054ms
Tidyparse (valid/total): 15/32
Original error:
def read_relative_file(filename):
"""Returns contents of the given file, which path is supposed relative"""
with open(os.path.join(os.path.dirname(__file__), filename) as f:
return f.read().strip()
Good Repair:
def read_relative_file(filename):
"""Returns contents of the given file, which path is supposed relative"""
** with openos.path.join(os.path.dirname(__file__), filename) as f:
return f.read().strip()
Synthesized repair in: 31630ms
Tidyparse (valid/total): 16/33
Original error:
def report_errors(self, errors):
for err in errors:
self.info('\t\t', str(err)))
Good Repair:
def report_errors(self, errors):
for err in errors:
** self.info('\t\t', str(err))
Synthesized repair in: 3160ms
Tidyparse (valid/total): 17/34
Original error:
def forceupdate():
response = requests.post(url + '/appversion', headers = headers, data = json.dumps({
'version': '1.1'
Bad Repair: illegal target for annotation (<unknown>, line 3):
def forceupdate():
** response = requests.post(url + '/appversion', headers = headers, data = json.dumps())
'version': '1.1'
Synthesized repair in: 17813ms
Tidyparse (valid/total): 17/35
Original error:
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')))
testinfo = "s, t 3.0, s, t 5.0, s, t 10.0, s, q"
tags = "grid_actions, AccelDeccelAmplitude, Waves3D"
import pyglet
import cocos
from cocos.director import director
Good Repair:
import sys
import os
** sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
testinfo = "s, t 3.0, s, t 5.0, s, t 10.0, s, q"
tags = "grid_actions, AccelDeccelAmplitude, Waves3D"
import pyglet
import cocos
from cocos.director import director
Synthesized repair in: 8496ms
Tidyparse (valid/total): 18/36
Original error:
def running_set(self):
"""Up to the 5 most recent active collectors"""
return self.collector_set.filter(open_date__lte = date.today().order_by('-id')[: 5]
Bad Repair: invalid syntax (<unknown>, line 3):
def running_set(self):
"""Up to the 5 most recent active collectors"""
** return self.collector_set.filteropen_date__lte = date.today().order_by('-id')[: 5]
Synthesized repair in: 20048ms
Tidyparse (valid/total): 18/37
Original error:
def get_admin_panels(self, req):
if 'VERSIONCONTROL_ADMIN' in req.perm('admin', 'versioncontrol/repository'):
yield('versioncontrol', _('Version Control'), 'repository',
_('Repositories')
Bad Repair: invalid syntax (<unknown>, line 3):
def get_admin_panels(self, req):
if 'VERSIONCONTROL_ADMIN' in req.perm('admin', 'versioncontrol/repository'):
** yield('versioncontrol', _'Version Control'), 'repository',
_('Repositories')
Synthesized repair in: 37303ms
Tidyparse (valid/total): 18/38
Original error:
def __init__(self, name, balance = Decimal('0.00'))):
self._name = name
self._balance = balance
self._recorded_balance = balance
self._initial_balance = self._balance
Good Repair:
** def __init__(self, name, balance = Decimal('0.00')):
self._name = name
self._balance = balance
self._recorded_balance = balance
self._initial_balance = self._balance
Synthesized repair in: 4095ms
Tidyparse (valid/total): 19/39
Original error:
def tz(self):
tz = [(tz, tz.replace('_', ' ')) for tz in pytz.all_timezones]
tz.insert(0, ("", "")))
return tz
Good Repair:
def tz(self):
tz = [(tz, tz.replace('_', ' ')) for tz in pytz.all_timezones]
** tz.insert(0, ("", ""))
return tz
Synthesized repair in: 49715ms
Tidyparse (valid/total): 20/40
Original error:
def test_get_path_parts(self, image):
self.photo.metadata_read = True
self.photo.timestamp = self.timestamp
self.assertEquals((2012, 8, 'foo.jpg'), self.photo.get_path_parts()
Good Repair:
def test_get_path_parts(self, image):
self.photo.metadata_read = True
self.photo.timestamp = self.timestamp
** self.assertEquals(2012, 8, 'foo.jpg'), self.photo.get_path_parts()
Synthesized repair in: 9928ms
Tidyparse (valid/total): 21/41
Original error:
'''What is the sum of the digits of the number 2^1000?'''
print(sum(map(int, str(2 ** 1000)))
from math import log
from time import sleep
Good Repair:
'''What is the sum of the digits of the number 2^1000?'''
** print(sum(map(int, str2 ** 1000)))
from math import log
from time import sleep
Synthesized repair in: 7004ms
Tidyparse (valid/total): 22/42
Original error:
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from ibm_db_alembic.ibm_db import IbmDbImpl
config = context.config
fileConfig(config.config_file_name)
from flask import current_app
config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')))
target_metadata = current_app.extensions['migrate'].db.metadata
Bad Repair: invalid syntax (<unknown>, line 8):
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
from ibm_db_alembic.ibm_db import IbmDbImpl
config = context.config
** fileConfig(config.config_file_name
from flask import current_app
config.set_main_option('sqlalchemy.url', current_app.config.get('SQLALCHEMY_DATABASE_URI')))
target_metadata = current_app.extensions['migrate'].db.metadata
Synthesized repair in: 16946ms
Tidyparse (valid/total): 22/43
Original error:
def output(n):
b = n
print('[',
while b != None:
print(b.val, )
b = b.next
print(']')
Bad Repair: invalid syntax (<unknown>, line 4):
def output(n):
b = n
print('[',
while b != None:
print(b.val, )
b = b.next
** print']')
Synthesized repair in: 17258ms
Tidyparse (valid/total): 22/44
Original error:
def playbackSliderValueChanged(self):
self.updateTimeLabel()
self.showPoseAtTime(self.getPlaybackTime()
Good Repair:
def playbackSliderValueChanged(self):
self.updateTimeLabel()
** self.showPoseAtTimeself.getPlaybackTime()
Synthesized repair in: 11752ms
Tidyparse (valid/total): 23/45
Original error:
def get_absolute_url(self):
return('blog_post', None, {
'username': self.author.username,
'year': self.publish.year,
'month': "%02d" % self.publish.month,
'slug': self.slug
Bad Repair: unexpected indent (<unknown>, line 3):
def get_absolute_url(self):
** return('blog_post', None, )
'username': self.author.username,
'year': self.publish.year,
'month': "%02d" % self.publish.month,
'slug': self.slug
Synthesized repair in: 35207ms
Tidyparse (valid/total): 23/46
Original error:
def is_dataframe(possible_dataframe):
"""Simple helper that returns True if an input is a pandas dataframe."""
return issubclass(DataFrame, type(possible_dataframe)))
Good Repair:
def is_dataframe(possible_dataframe):
"""Simple helper that returns True if an input is a pandas dataframe."""
** return issubclass(DataFrame, type(possible_dataframe))
Synthesized repair in: 8616ms
Tidyparse (valid/total): 24/47
Original error:
def chatChannelsSearch():
channels = ChatChannelManager.findChannels(session, str(request.args['chat_channel_name'])
return render_template("chat_channels.html", channels = channels)
Good Repair:
def chatChannelsSearch():
** channels = ChatChannelManager.findChannels(session, strrequest.args['chat_channel_name'])
return render_template("chat_channels.html", channels = channels)
Synthesized repair in: 21668ms
Tidyparse (valid/total): 25/48
Original error:
def generate_timestamp():
"""生成 timestamp"""
return int(time.time()
Good Repair:
def generate_timestamp():
"""生成 timestamp"""
** return inttime.time()
Synthesized repair in: 5928ms
Tidyparse (valid/total): 26/49
Original error:
def updateName(self):
self.template.name = unicode(self.lineEdit.text()
self.checkData()
Good Repair:
def updateName(self):
** self.template.name = unicodeself.lineEdit.text()
self.checkData()
Synthesized repair in: 5534ms
Tidyparse (valid/total): 27/50
Original error:
def coeff(self, pt):
"""Returns the coefficient at point pt"""
if pt < self.start or pt > self.stop:
raise IndexError("Index %s out of bounds %s" %(pt, self.interval)))
return self._eval_coeff(pt)
Good Repair:
def coeff(self, pt):
"""Returns the coefficient at point pt"""
if pt < self.start or pt > self.stop:
** raise IndexError("Index %s out of bounds %s" %(pt, self.interval))
return self._eval_coeff(pt)
Synthesized repair in: 5865ms
Tidyparse (valid/total): 28/51
Original error:
class ConvertOldTestToMeta(controldir.Converter):
"""A trivial converter, used for testing."""
def convert(self, to_convert, pb):
ui.ui_factory.note('starting upgrade from old test format to 2a')
to_convert.control_transport.put_bytes(
'branch-format',
bzrdir.BzrDirMetaFormat1().get_format_string(),
mode = to_convert._get_file_mode()
return controldir.ControlDir.open(to_convert.user_url)
Bad Repair: invalid syntax (<unknown>, line 9):
class ConvertOldTestToMeta(controldir.Converter):
"""A trivial converter, used for testing."""
def convert(self, to_convert, pb):
ui.ui_factory.note('starting upgrade from old test format to 2a')
to_convert.control_transport.put_bytes(
'branch-format',
bzrdir.BzrDirMetaFormat1().get_format_string(),
mode = to_convert._get_file_mode()
** return controldir.ControlDir.opento_convert.user_url)
Synthesized repair in: 59866ms
Tidyparse (valid/total): 28/52
Original error:
def writeheader(self):
print("\t".join(("QueryID", "UpdateID", "NuggetID", "Start",
"End", "AutoP", "Score", "Label", "Update_Text",
"Nugget_Text"))
Good Repair:
def writeheader(self):
** print("\t".join("QueryID", "UpdateID", "NuggetID", "Start",
"End", "AutoP", "Score", "Label", "Update_Text",
"Nugget_Text"))
Synthesized repair in: 8540ms
Tidyparse (valid/total): 29/53
Original error:
def test_doesnt_challenges_on_401_with_WWW_Authenticate(self):
decider = self._getFUT()
self.failIf(decider({}, '401 Ok', [('WWW-Authenticate', 'xxx')])
Good Repair:
def test_doesnt_challenges_on_401_with_WWW_Authenticate(self):
decider = self._getFUT()
** self.failIfdecider({}, '401 Ok', [('WWW-Authenticate', 'xxx')])
Synthesized repair in: 63488ms
Tidyparse (valid/total): 30/54
Original error:
s = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
x = 0
for i in range(0, len(s):
p = 1
for n in s[i: i + 5]:
p *= int(n)
if p > x:
x = p
print(x)
Bad Repair: invalid syntax (<unknown>, line 3):
s = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
x = 0
for i in range(0, len(s):
p = 1
for n in s[i: i + 5]:
** p *= intn)
if p > x:
x = p
print(x)
Synthesized repair in: 34730ms
Tidyparse (valid/total): 30/55
Original error:
def exchange_shared(a, b):
"""a: a theano shared variable"""
temp = a.get_value()
a.set_value(b.get_value()
b.set_value(temp)
Bad Repair: invalid syntax (<unknown>, line 5):
def exchange_shared(a, b):
"""a: a theano shared variable"""
temp = a.get_value()
a.set_value(b.get_value()
** b.set_valuetemp)
Synthesized repair in: 9448ms
Tidyparse (valid/total): 30/56
Original error:
def write_julian(fid, kind, data):
"""Writes a Julian-formatted date to a FIF file"""
assert len(data) == 3
data_size = 4
jd = np.sum(jcal2jd(* data)
data = np.array(jd, dtype = '>i4')
_write(fid, data, kind, data_size, FIFF.FIFFT_JULIAN, '>i4')
Good Repair:
def write_julian(fid, kind, data):
"""Writes a Julian-formatted date to a FIF file"""
assert len(data) == 3
data_size = 4
** jd = np.sum(jcal2jd* data)
data = np.array(jd, dtype = '>i4')
_write(fid, data, kind, data_size, FIFF.FIFFT_JULIAN, '>i4')
Synthesized repair in: 50166ms
Tidyparse (valid/total): 31/57
Original error:
def send_alert():
return requests.post(
"subject": "Alert",
"text": alertmessage})
Bad Repair: invalid syntax (<unknown>, line 3):
def send_alert():
return requests.post(
"subject": "Alert",
** "text": alertmessage)
Synthesized repair in: 15828ms
Tidyparse (valid/total): 31/58
Original error:
from django.core.management.base import BaseCommand
from query.base_models import ModelDelegator
import os
models = ModelDelegator(os.environ.get('DATASET')))
Good Repair:
from django.core.management.base import BaseCommand
from query.base_models import ModelDelegator
import os
** models = ModelDelegator(os.environ.get('DATASET'))
Synthesized repair in: 3069ms
Tidyparse (valid/total): 32/59
Original error:
def retranslateUi(self, HgBookmarksInOutDialog):
_translate = QtCore.QCoreApplication.translate
self.bookmarksList.setWhatsThis(_translate("HgBookmarksInOutDialog", "<b>Bookmarks List</b>\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, HgBookmarksInOutDialog):
_translate = QtCore.QCoreApplication.translate
** self.bookmarksList.setWhatsThis(_translate)"HgBookmarksInOutDialog", "<b>Bookmarks List</b>\n"
Synthesized repair in: 10453ms
Tidyparse (valid/total): 32/60
Original error:
def grad_desc(cost, theta):
alpha = 0.1
return theta -(alpha * T.grad(cost, wrt = theta)))
Good Repair:
def grad_desc(cost, theta):
alpha = 0.1
** return theta -(alpha * T.grad(cost, wrt = theta))
Synthesized repair in: 21455ms
Tidyparse (valid/total): 33/61
Original error:
"""Generate minidump symbols for use by the Crash server."""
import collections
import ctypes
import logging
import multiprocessing
import os
import tempfile
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import osutils
from chromite.lib import parallel
SymbolHeader = collections.namedtuple('SymbolHeader',
('cpu', 'id', 'name', 'os', )))
Good Repair:
"""Generate minidump symbols for use by the Crash server."""
import collections
import ctypes
import logging
import multiprocessing
import os
import tempfile
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import osutils
from chromite.lib import parallel
SymbolHeader = collections.namedtuple('SymbolHeader',
** ('cpu', 'id', 'name', 'os', ))
Synthesized repair in: 4098ms
Tidyparse (valid/total): 34/62
Original error:
import logging
import sys
import thinrpc
import thinrpc.client as client
thinrpc.logger.setLevel(logging.DEBUG)
port = int(sys.argv[1])
rn = client.RpcRemote(("localhost", port)
print(rn.hello())
Good Repair:
import logging
import sys
import thinrpc
import thinrpc.client as client
thinrpc.logger.setLevel(logging.DEBUG)
port = int(sys.argv[1])
** rn = client.RpcRemote("localhost", port)
print(rn.hello())
Synthesized repair in: 18716ms
Tidyparse (valid/total): 35/63
Original error:
def _assert_progress(self, meter, * progresses):
"""Variadic helper used to verify progress calculations."""
self.assertEqual(meter.progress, list(progresses)))
Good Repair:
def _assert_progress(self, meter, * progresses):
"""Variadic helper used to verify progress calculations."""
** self.assertEqual(meter.progress, list(progresses))
Synthesized repair in: 3736ms
Tidyparse (valid/total): 36/64
Original error:
def default_argparser():
import argparse
return argparse.ArgumentParser(parents = argparsers()
Good Repair:
def default_argparser():
import argparse
** return argparse.ArgumentParser(parents = argparsers)
Synthesized repair in: 1881ms
Tidyparse (valid/total): 37/65
Original error:
def clear_db():
'''Helper to unregister models and clear engine in unit tests'''
if not HashHandler._FACADE:
return
ConsistencyHash.metadata.drop_all(HashHandler._FACADE.get_engine()
HashHandler._FACADE = None
Good Repair:
def clear_db():
'''Helper to unregister models and clear engine in unit tests'''
if not HashHandler._FACADE:
return
** ConsistencyHash.metadata.drop_allHashHandler._FACADE.get_engine()
HashHandler._FACADE = None
Synthesized repair in: 9400ms
Tidyparse (valid/total): 38/66
Original error:
def _runs_for_milestone(self, obj):
return RunContainer(filter(
lambda r: r.milestone.id == obj.id, self.runs())
Good Repair:
def _runs_for_milestone(self, obj):
** return RunContainerfilter(
lambda r: r.milestone.id == obj.id, self.runs())
Synthesized repair in: 13640ms
Tidyparse (valid/total): 39/67
Original error:
def oauth2callback():
response.title = 'Page to receive google code'
if request.get_vars.code:
print('w'), request.get_vars.code)
return dict()
Bad Repair: invalid syntax (<unknown>, line 1):
** def oauth2callback(:
response.title = 'Page to receive google code'
if request.get_vars.code:
print('w'), request.get_vars.code)
return dict()
Synthesized repair in: 10127ms
Tidyparse (valid/total): 39/68
Original error:
class Task(BaseTask):
option_list = [make_option("--pep8-exclude",
dest = "pep8-exclude", default = pep8.DEFAULT_EXCLUDE + ",migrations",
help = "exclude files or directories which match these "
Bad Repair: invalid syntax (<unknown>, line 2):
class Task(BaseTask):
** option_list = [make_option]"--pep8-exclude",
dest = "pep8-exclude", default = pep8.DEFAULT_EXCLUDE + ",migrations",
help = "exclude files or directories which match these "
Synthesized repair in: 28267ms
Tidyparse (valid/total): 39/69
Original error:
def __init__(self, identifier, name = None, children = [], props = dict():
"""Constructor"""
self.children = children
self.properties = props
self.identifier = identifier
self.name = name if name != "" else None
self.name_is_global = True
Good Repair:
** def __init__(self, identifier, name = None, children = [], props = dict):
"""Constructor"""
self.children = children
self.properties = props
self.identifier = identifier
self.name = name if name != "" else None
self.name_is_global = True
Synthesized repair in: 6375ms
Tidyparse (valid/total): 40/70
Original error:
def _ParseOldStyleExternal(dir_token, url_token, rev_token, externals_map):
repo, path = _FindExternalPath(url_token, externals_map)
try:
return ExternalsDescription(dir_token, repo, rev_token, path, rev_token)
except ValueError as e:
raise ParseError(str(e)
Good Repair:
def _ParseOldStyleExternal(dir_token, url_token, rev_token, externals_map):
repo, path = _FindExternalPath(url_token, externals_map)
try:
return ExternalsDescription(dir_token, repo, rev_token, path, rev_token)
except ValueError as e:
** raise ParseError(stre)
Synthesized repair in: 77603ms
Tidyparse (valid/total): 41/71
Original error:
def collect_new_references_for_feed(feed):
"""Get the feed data from its URL and collect the new references into the db."""
try:
d = feedparser.parse(feed.xmlURL)
except Exception, e:
logger.error("Skipping feed at %s because of a parse problem (%s))." %(feed.source.url, e))
return[]
return add_new_references_from_feedparser_entries(feed, d.entries)
Bad Repair: invalid syntax (<unknown>, line 5):
def collect_new_references_for_feed(feed):
"""Get the feed data from its URL and collect the new references into the db."""
try:
d = feedparser.parse(feed.xmlURL)
except Exception, e:
** logger.error("Skipping feed at %s because of a parse problem (%s))." %(feed.source.url, e)
return[]
return add_new_references_from_feedparser_entries(feed, d.entries)
Synthesized repair in: 85165ms
Tidyparse (valid/total): 41/72
Original error:
def add(a, b):
print("ADDING %d + %d" %(a, b)
return a + b
Bad Repair: invalid syntax (<unknown>, line 2):
def add(a, b):
** print"ADDING %d + %d" %(a, b)
return a + b
Synthesized repair in: 14280ms
Tidyparse (valid/total): 41/73
Original error:
def cartesian_product(lists):
"""Returns cartesian product of lists as list of tuples."""
return map(tuple, cross_comb(lists)
Good Repair:
def cartesian_product(lists):
"""Returns cartesian product of lists as list of tuples."""
** return map(tuple, cross_comblists)
Synthesized repair in: 2954ms
Tidyparse (valid/total): 42/74
Original error:
def add_arguments(self, parser):
parser.add_argument('-q', '--quiet', action = 'store_true', dest = 'quiet', default = False,
help = 'If no error occurs, swallow all output.'),
parser.add_argument('--database', default = 'default',
help = ('Specifies the database to use, if using a db. '
Bad Repair: invalid syntax (<unknown>, line 5):
def add_arguments(self, parser):
parser.add_argument('-q', '--quiet', action = 'store_true', dest = 'quiet', default = False,
help = 'If no error occurs, swallow all output.'),
parser.add_argument('--database', default = 'default',
** help = )'Specifies the database to use, if using a db. '
Synthesized repair in: 39585ms
Tidyparse (valid/total): 42/75
Original error:
def retranslateUi(self, WizardPage):
WizardPage.setWindowTitle(_translate("WizardPage", "WizardPage", None))
WizardPage.setTitle(_translate("WizardPage", "Permutation Details", None))
self.exact_checkBox.setToolTip(_translate("WizardPage", "If selected, the model is fit to each possible permuation once.\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, WizardPage):
WizardPage.setWindowTitle(_translate("WizardPage", "WizardPage", None))
WizardPage.setTitle(_translate("WizardPage", "Permutation Details", None))
** self.exact_checkBox.setToolTip(_translate)"WizardPage", "If selected, the model is fit to each possible permuation once.\n"
Synthesized repair in: 64436ms
Tidyparse (valid/total): 42/76
Original error:
def delete(self, list_id):
"""Delete a list from your MailChimp account.If you delete a list, """
self.list_id = list_id
return self._mc_client._delete(url = self._build_path(list_id)
Bad Repair: invalid syntax (<unknown>, line 4):
def delete(self, list_id):
"""Delete a list from your MailChimp account.If you delete a list, """
self.list_id = list_id
** return self._mc_client._deleteurl = self._build_path(list_id)
Synthesized repair in: 2286ms
Tidyparse (valid/total): 42/77
Original error:
def error(self, msg, warn = False):
print("%s %s:%d:" %("Warning:" if warn else "Error:",
self.filename, self.linenumber), msg
Bad Repair: invalid syntax (<unknown>, line 2):
def error(self, msg, warn = False):
** print"%s %s:%d:" %("Warning:" if warn else "Error:",
self.filename, self.linenumber), msg
Synthesized repair in: 8866ms
Tidyparse (valid/total): 42/78
Original error:
def stem_word_process():
def stem_word(word):
return STEMMER.stem(word.lower()
return stem_word
Good Repair:
def stem_word_process():
def stem_word(word):
** return STEMMER.stemword.lower()
return stem_word
Synthesized repair in: 13494ms
Tidyparse (valid/total): 43/79
Original error:
def find_include_file(self, t):
keyword, quote, fname = t
result = SCons.Node.FS.find_file(fname, self.searchpath[quote])
if not result:
self.missing.append((fname, self.current_file)
return result
Good Repair:
def find_include_file(self, t):
keyword, quote, fname = t
result = SCons.Node.FS.find_file(fname, self.searchpath[quote])
if not result:
** self.missing.append(fname, self.current_file)
return result
Synthesized repair in: 101041ms
Tidyparse (valid/total): 44/80
Original error:
def assert_contain_text(src_text, desc_text):
"""assert src_text contain desc_text"""
is_contain_text = desc_text in src_text
if not is_contain_text:
raise AssertionError('% not contain %' %(src_text, desc_text)
Bad Repair: invalid syntax (<unknown>, line 5):
def assert_contain_text(src_text, desc_text):
"""assert src_text contain desc_text"""
is_contain_text = desc_text in src_text
if not is_contain_text:
** raise AssertionError'% not contain %' %(src_text, desc_text)
Synthesized repair in: 7324ms
Tidyparse (valid/total): 44/81
Original error:
def classic_ulimit(limit = 65535):
"""add ulimit for heavy load system"""
with settings(warn_only = True):
if run('cat /etc/security/limits.d/90-nproc.conf | grep %s' % "'* soft nproc'").failed:
run("echo '%s%d >> /etc/security/limits.d/90-nproc.conf'" %("'* soft nproc '", limit)
else:
run('sed -i -e "s/* soft nproc \d+/* soft nproc %d/g" /etc/security/limits.d/90-nproc.conf' % limit)
pass
Bad Repair: invalid syntax (<unknown>, line 6):
def classic_ulimit(limit = 65535):
"""add ulimit for heavy load system"""
with settings(warn_only = True):
if run('cat /etc/security/limits.d/90-nproc.conf | grep %s' % "'* soft nproc'").failed:
run("echo '%s%d >> /etc/security/limits.d/90-nproc.conf'" %("'* soft nproc '", limit)
else:
** run'sed -i -e "s/* soft nproc \d+/* soft nproc %d/g" /etc/security/limits.d/90-nproc.conf' % limit)
pass
Synthesized repair in: 19468ms
Tidyparse (valid/total): 44/82
Original error:
def write(self):
if not self.init:
return "Generator not initiated"
if self.err != "":
return self.err
deps = self.imported
provides = self.provided
err, deps, provides = self.getGoSymbols(self.tarball_path)
if err != "":
return err
self.file.write("""%global debug_package %{nil}""")
if self.provider_type == PROVIDER_GITHUB:
self.file.write("""%%global provider %s"""
Bad Repair: invalid syntax (<unknown>, line 13):
def write(self):
if not self.init:
return "Generator not initiated"
if self.err != "":
return self.err
deps = self.imported
provides = self.provided
err, deps, provides = self.getGoSymbols(self.tarball_path)
if err != "":
return err
self.file.write("""%global debug_package %{nil}""")
if self.provider_type == PROVIDER_GITHUB:
** self.file.write"""%%global provider %s"""
Synthesized repair in: 33735ms
Tidyparse (valid/total): 44/83
Original error:
def save(self):
backend.db.set(self.job_id, json.dumps(self.jobObj)
return True
Good Repair:
def save(self):
** backend.db.set(self.job_id, json.dumpsself.jobObj)
return True
Synthesized repair in: 8013ms
Tidyparse (valid/total): 45/84
Original error:
def get_form_fields_on_submission_page(subname, pagenum):
"""Get the details of all form fields as they appear on the"""
qstr = """SELECT subname, pagenb, fieldnb, fidesc, fitext, """ """level, sdesc, checkn, cd, md, fiefi1, fiefi2 """ """FROM sbmFIELD WHERE subname=%s AND pagenb=%s """ """ORDER BY fieldnb"""
qres = run_sql(qstr, (subname, pagenum)))
return qres
Good Repair:
def get_form_fields_on_submission_page(subname, pagenum):
"""Get the details of all form fields as they appear on the"""
qstr = """SELECT subname, pagenb, fieldnb, fidesc, fitext, """ """level, sdesc, checkn, cd, md, fiefi1, fiefi2 """ """FROM sbmFIELD WHERE subname=%s AND pagenb=%s """ """ORDER BY fieldnb"""
** qres = run_sql(qstr, (subname, pagenum))
return qres
Synthesized repair in: 17979ms
Tidyparse (valid/total): 46/85
Original error:
def DumpExpandedConfigToString(self):
"""Dump the SiteConfig to Json with all configs full expanded."""
return json.dumps(self, cls = self._JSONEncoder,
sort_keys = True, indent = 4, separators = (', ', ': ')))
Good Repair:
def DumpExpandedConfigToString(self):
"""Dump the SiteConfig to Json with all configs full expanded."""
return json.dumps(self, cls = self._JSONEncoder,
** sort_keys = True, indent = 4, separators = (', ', ': '))
Synthesized repair in: 3442ms
Tidyparse (valid/total): 47/86
Original error:
def maybe_put_task(self):
'''Enqueue the next task, if there are any waiting.'''
try:
self.in_queue.put(next(self.tasks)
except StopIteration:
pass
Good Repair:
def maybe_put_task(self):
'''Enqueue the next task, if there are any waiting.'''
try:
** self.in_queue.putnext(self.tasks)
except StopIteration:
pass
Synthesized repair in: 11340ms
Tidyparse (valid/total): 48/87
Original error:
def test_from_primitive(self):
class ObjectLikeThing:
_context = 'context'
for prim_val, out_val in self.from_primitive_values:
self.assertEqual(out_val, self.field.from_primitive(
ObjectLikeThing, 'attr', prim_val)
Good Repair:
def test_from_primitive(self):
class ObjectLikeThing:
_context = 'context'
for prim_val, out_val in self.from_primitive_values:
** self.assertEqualout_val, self.field.from_primitive(
ObjectLikeThing, 'attr', prim_val)
Synthesized repair in: 8205ms
Tidyparse (valid/total): 49/88
Original error:
def format_response(action, response):
"""Format response from engine into API format"""
return{'%sResponse' % action: {'%sResult' % action: response}}}
Good Repair:
def format_response(action, response):
"""Format response from engine into API format"""
** return{'%sResponse' % action: {'%sResult' % action: response}}
Synthesized repair in: 11408ms
Tidyparse (valid/total): 50/89
Original error:
def retranslateUi(self, Account):
_translate = QtCore.QCoreApplication.translate
Account.setWindowTitle(_translate("Account", "Account"))
self.legende.setHtml(_translate("Account", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, Account):
_translate = QtCore.QCoreApplication.translate
Account.setWindowTitle(_translate("Account", "Account"))
** self.legende.setHtml(_translate)"Account", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 247842ms
Tidyparse (valid/total): 50/90
Original error:
def get_author_links(authors_str):
for author in bpc_people:
authors_str = authors_str.replace(author, '<span class="pub-member-author">%s</span>' %(author)
return authors_str
Good Repair:
def get_author_links(authors_str):
for author in bpc_people:
** authors_str = authors_str.replace(author, '<span class="pub-member-author">%s</span>' %author)
return authors_str
Synthesized repair in: 13822ms
Tidyparse (valid/total): 51/91
Original error:
def helloJ(request):
nombre = "Jose"
}
return render(request, 'hello.html', nombre)
Good Repair:
def helloJ(request):
nombre = "Jose"
**
return render(request, 'hello.html', nombre)
Synthesized repair in: 3084ms
Tidyparse (valid/total): 52/92
Original error:
def _calculate_goal_horizontal_offset(self):
"""Calcule la dimension horizontale du but p/r à la résolution."""
return int(ceil(FIELD_GOAL_SEGMENT / self._resolution)
Good Repair:
def _calculate_goal_horizontal_offset(self):
"""Calcule la dimension horizontale du but p/r à la résolution."""
** return intceil(FIELD_GOAL_SEGMENT / self._resolution)
Synthesized repair in: 6510ms
Tidyparse (valid/total): 53/93
Original error:
class TestWordfastFactory(BaseTestFactory):
from translate.storage import wordfast
expected_instance = wordfast.WordfastTMFile
filename = 'dummy.txt'
file_content = ('''%20070801~103212 %User ID,S,S SMURRAY,SMS Samuel Murray-Smit,SM Samuel Murray-Smit,MW Mary White,DS Deepak Shota,MT! Machine translation (15),AL! Alignment (10),SM Samuel Murray, %TU=00000075 %AF-ZA %Wordfast TM v.5.51r/00 %EN-ZA %---80597535 Subject (5),EL,EL Electronics,AC Accounting,LE Legal,ME Mechanics,MD Medical,LT Literary,AG Agriculture,CO Commercial Client (5),LS,LS LionSoft Corp,ST SuperTron Inc,CA CompArt Ltd '''
Bad Repair: unexpected EOF while parsing (<unknown>, line 5):
class TestWordfastFactory(BaseTestFactory):
from translate.storage import wordfast
expected_instance = wordfast.WordfastTMFile
filename = 'dummy.txt'
** file_content = ('''%20070801~103212 %User ID,S,S SMURRAY,SMS Samuel Murray-Smit,SM Samuel Murray-Smit,MW Mary White,DS Deepak Shota,MT! Machine translation (15),AL! Alignment 10),SM Samuel Murray, %TU=00000075 %AF-ZA %Wordfast TM v.5.51r/00 %EN-ZA %---80597535 Subject (5),EL,EL Electronics,AC Accounting,LE Legal,ME Mechanics,MD Medical,LT Literary,AG Agriculture,CO Commercial Client (5),LS,LS LionSoft Corp,ST SuperTron Inc,CA CompArt Ltd '''
Synthesized repair in: 50216ms
Tidyparse (valid/total): 53/94
Original error:
def _connection_lost(self, link_uri, msg):
"""Callback when disconnected after a connection has been made(i.e"""
print("Connection to %s lost: %s" %(link_uri, msg)
Bad Repair: invalid syntax (<unknown>, line 3):
def _connection_lost(self, link_uri, msg):
"""Callback when disconnected after a connection has been made(i.e"""
** print("Connection to %s lost: %s" %)link_uri, msg)
Synthesized repair in: 28316ms
Tidyparse (valid/total): 53/95
Original error:
def generate_month_constraint(month):
"""generate an: class: `iris.Constraint` on the time-axis for a specified month"""
return Constraint(
time = lambda cell: cell.point == PartialDateTime(month = month)
Bad Repair: unexpected indent (<unknown>, line 4):
def generate_month_constraint(month):
"""generate an: class: `iris.Constraint` on the time-axis for a specified month"""
** return Constraint
time = lambda cell: cell.point == PartialDateTime(month = month)
Synthesized repair in: 6577ms
Tidyparse (valid/total): 53/96
Original error:
def _get_prop_value(self, tag):
"""Gets the value for a given resource property."""
return self._editor.get_element_value(self._editor.get_first_element_by_tag(tag, self._resource_elem)
Good Repair:
def _get_prop_value(self, tag):
"""Gets the value for a given resource property."""
** return self._editor.get_element_value(self._editor.get_first_element_by_tagtag, self._resource_elem)
Synthesized repair in: 7475ms
Tidyparse (valid/total): 54/97
Original error:
def _generate_split_token():
selector = base64.urlsafe_b64encode(secrets.token_bytes(SELECTOR_TOKEN_LENGTH))
verifier = base64.urlsafe_b64encode(secrets.token_bytes(SELECTOR_TOKEN_LENGTH + 6)
return selector, verifier
Good Repair:
def _generate_split_token():
selector = base64.urlsafe_b64encode(secrets.token_bytes(SELECTOR_TOKEN_LENGTH))
** verifier = base64.urlsafe_b64encode(secrets.token_bytesSELECTOR_TOKEN_LENGTH + 6)
return selector, verifier
Synthesized repair in: 70793ms
Tidyparse (valid/total): 55/98
Original error:
def run(self):
super(BigQueryLoadAvro, self).run()
try:
self._set_output_doc(self._get_input_schema()))
except Exception as e:
logger.warning('Could not propagate Avro doc to BigQuery table field descriptions: %r', e)
Bad Repair: invalid syntax (<unknown>, line 3):
def run(self):
** super(BigQueryLoadAvro, self).run(
try:
self._set_output_doc(self._get_input_schema()))
except Exception as e:
logger.warning('Could not propagate Avro doc to BigQuery table field descriptions: %r', e)
Synthesized repair in: 18292ms
Tidyparse (valid/total): 55/99
Original error:
def retranslateUi(self, dlgColumnDepend):
dlgColumnDepend.setWindowTitle(_translate("dlgColumnDepend", "Column dependencies", None))
self.qryLabel.setText(_translate("dlgColumnDepend", "The following items depend on the \'%s\' column;\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, dlgColumnDepend):
dlgColumnDepend.setWindowTitle(_translate("dlgColumnDepend", "Column dependencies", None))
** self.qryLabel.setText(_translate)"dlgColumnDepend", "The following items depend on the \'%s\' column;\n"
Synthesized repair in: 47846ms
Tidyparse (valid/total): 55/100
Original error:
def link_side(action, text, icon):
action = ('/%s' % action if action != '#' else '#')
texti = ""
if icon:
texti = '<i class="%s fa-lg"></i>' % icon
html = '<a href="%s" class="dw-spinner dw-ajax subnav2" >%s <i class="icon-chevron-right"></i>%s</a>\n' %(
action, texti, _("%s" % text)))
return html
Bad Repair: invalid syntax (<unknown>, line 3):
** def link_side(action, text, icon:
action = ('/%s' % action if action != '#' else '#')
texti = ""
if icon:
texti = '<i class="%s fa-lg"></i>' % icon
html = '<a href="%s" class="dw-spinner dw-ajax subnav2" >%s <i class="icon-chevron-right"></i>%s</a>\n' %(
action, texti, _("%s" % text)))
return html
Synthesized repair in: 10641ms
Tidyparse (valid/total): 55/101
Original error:
def add_arguments(self, parser):
parser.add_argument(
'--output-dir', '-o',
default = os.path.join(get_setting('BASE_DIR'), 'locale',
'templates', 'LC_MESSAGES'),
dest = 'outputdir',
help = (
'The directory where extracted files will be placed. '
'(Default: %%default)'
)
Bad Repair: unexpected indent (<unknown>, line 3):
def add_arguments(self, parser):
** parser.add_argument
'--output-dir', '-o',
default = os.path.join(get_setting('BASE_DIR'), 'locale',
'templates', 'LC_MESSAGES'),
dest = 'outputdir',
help = (
'The directory where extracted files will be placed. '
'(Default: %%default)'
)
Synthesized repair in: 13627ms
Tidyparse (valid/total): 55/102
Original error:
def select_source(self, source):
"""Select input source."""
self.telnet_command('SI' + self._source_list.get(source)
Bad Repair: invalid syntax (<unknown>, line 3):
def select_source(self, source):
"""Select input source."""
** self.telnet_command'SI' + self._source_list.get(source)
Synthesized repair in: 20697ms
Tidyparse (valid/total): 55/103
Original error:
def end_at(dg, nodes):
"""Returns subgraph that will guarantee that predecessors are visited"""
return set(get_dfs_postorder_subgraph(dg.reverse(), nodes).nodes()
Good Repair:
def end_at(dg, nodes):
"""Returns subgraph that will guarantee that predecessors are visited"""
** return set(get_dfs_postorder_subgraph(dg.reverse), nodes).nodes()
Synthesized repair in: 31393ms
Tidyparse (valid/total): 56/104
Original error:
def provision(self, cluster_id, nodes_ids):
url = reverse(
'ProvisionSelectedNodes',
kwargs = {'cluster_id': cluster_id}) + '?nodes={0}'.format(', '.join(nodes_ids)
func = functools.partial(self.app.put,
url,
'',
headers = self.default_headers,
expect_errors = True)
self.check_time_exec(func, 90)
Bad Repair: invalid syntax (<unknown>, line 5):
def provision(self, cluster_id, nodes_ids):
url = reverse(
'ProvisionSelectedNodes',
kwargs = {'cluster_id': cluster_id}) + '?nodes={0}'.format(', '.join(nodes_ids)
func = functools.partial(self.app.put,
url,
'',
headers = self.default_headers,
expect_errors = True)
** self.check_time_execfunc, 90)
Synthesized repair in: 293385ms
Tidyparse (valid/total): 56/105
Original error:
def wysiwyg_editor(field_id, editor_name = None, config = None):
if not editor_name:
editor_name = "%s_editor" % field_id
ctx = {
'field_id': field_id,
'editor_name': editor_name,
'config': config
}
return render_to_string(
"../templates/wysihtml5_instance.html",
ctx
Bad Repair: unexpected indent (<unknown>, line 10):
def wysiwyg_editor(field_id, editor_name = None, config = None):
if not editor_name:
editor_name = "%s_editor" % field_id
ctx = {
'field_id': field_id,
'editor_name': editor_name,
'config': config
}
** return render_to_string
"../templates/wysihtml5_instance.html",
ctx
Synthesized repair in: 30056ms
Tidyparse (valid/total): 56/106
Original error:
class InvalidArgument(Exception):
def __init__(self, arg, val):
self.arg = arg
self.val = val
def __str__(self):
return repr("Invalid argument %s: %s" %(self.arg, self.val)
Good Repair:
class InvalidArgument(Exception):
def __init__(self, arg, val):
self.arg = arg
self.val = val
def __str__(self):
** return repr("Invalid argument %s: %s" %self.arg, self.val)
Synthesized repair in: 109735ms
Tidyparse (valid/total): 57/107
Original error:
def saveIntoCouchDB(self, networkdata):
"""Store the given network data in a CouchDB."""
self.__db.save(nwd) for nwd in networkdata]
Bad Repair: invalid syntax (<unknown>, line 3):
def saveIntoCouchDB(self, networkdata):
"""Store the given network data in a CouchDB."""
** self.__db.save(nwd) for nwd in networkdata
Synthesized repair in: 4466ms
Tidyparse (valid/total): 57/108
Original error:
def parse_names(self, atoms_per, numlines):
vals = self.parsesection_mapper(
atoms_per, numlines, lambda x: x)
attr = Atomnames(np.array(vals, dtype = object)))
return attr
Bad Repair: invalid syntax (<unknown>, line 4):
** def parse_names(self, atoms_per, numlines:
vals = self.parsesection_mapper(
atoms_per, numlines, lambda x: x)
attr = Atomnames(np.array(vals, dtype = object)))
return attr
Synthesized repair in: 13986ms
Tidyparse (valid/total): 57/109
Original error:
def send_udp(udp_port, target_ip):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def sender(message):
sock.sendto(message, (target_ip, udp_port)
return sender
Good Repair:
def send_udp(udp_port, target_ip):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def sender(message):
** sock.sendto(message, target_ip, udp_port)
return sender
Synthesized repair in: 15622ms
Tidyparse (valid/total): 58/110
Original error:
class CSVMCreator(object):
default_dialect = {
"encoding": "utf-8",
"lineTerminators": ["\r\n", "\n"],
"quoteChar": "\"",
"doubleQuote": True,
"skipRows": 0,
"commentPrefix": "#",
"header": True,
"headerRowCount": 1,
"delimiter": ",",
"skipColumns": 0,
"skipBlankRows": False,
"skipInitialSpace": False,
"trim": False
Bad Repair: invalid syntax (<unknown>, line 2):
class CSVMCreator(object):
** default_dialect =
"encoding": "utf-8",
"lineTerminators": ["\r\n", "\n"],
"quoteChar": "\"",
"doubleQuote": True,
"skipRows": 0,
"commentPrefix": "#",
"header": True,
"headerRowCount": 1,
"delimiter": ",",
"skipColumns": 0,
"skipBlankRows": False,
"skipInitialSpace": False,
"trim": False
Synthesized repair in: 20507ms
Tidyparse (valid/total): 58/111
Original error:
def test_openrc_html_evil_shell_backslash_escape(self):
context = {
"user": FakeUser(),
"tenant_id": "some-cool-id",
"auth_url": "http: //tests.com",
"tenant_name": 'o\"; sudo rm -rf /'}
out = loader.render_to_string(
'project/access_and_security/api_access/openrc.sh.template',
context,
template.Context(context)
self.assertFalse('o\"' in out)
self.assertFalse('o"' in out)
self.assertTrue('\\"' in out)
Bad Repair: unexpected indent (<unknown>, line 8):
def test_openrc_html_evil_shell_backslash_escape(self):
context = {
"user": FakeUser(),
"tenant_id": "some-cool-id",
"auth_url": "http: //tests.com",
"tenant_name": 'o\"; sudo rm -rf /'}
** out = loader.render_to_string
'project/access_and_security/api_access/openrc.sh.template',
context,
template.Context(context)
self.assertFalse('o\"' in out)
self.assertFalse('o"' in out)
self.assertTrue('\\"' in out)
Synthesized repair in: 37158ms
Tidyparse (valid/total): 58/112
Original error:
def test_add_non_supported_type(self):
with self.assertRaises(TypeError):
biggus.add(range(12), np.arange(12)
Good Repair:
def test_add_non_supported_type(self):
with self.assertRaises(TypeError):
** biggus.add(range12), np.arange(12)
Synthesized repair in: 27966ms
Tidyparse (valid/total): 59/113
Original error:
def manage_blogs(*, page = '1'):
return{
'__template__': 'manage_blogs.html',
'page_index': get_page_index(page)
Bad Repair: unexpected indent (<unknown>, line 3):
def manage_blogs(*, page = '1'):
** return
'__template__': 'manage_blogs.html',
'page_index': get_page_index(page)
Synthesized repair in: 24617ms
Tidyparse (valid/total): 59/114
Original error:
def test_poll_no_messages(self):
b = self.create_backend()
self.assertState(b.poll(gen_unique_id(), states.PENDING)
Good Repair:
def test_poll_no_messages(self):
b = self.create_backend()
** self.assertStateb.poll(gen_unique_id(), states.PENDING)
Synthesized repair in: 48033ms
Tidyparse (valid/total): 60/115
Original error:
def test_Location___repr__():
tus = Location(32.2, - 111, 'US/Arizona', 700, 'Tucson')
expected = '\n'.join([
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Bad Repair: invalid syntax (<unknown>, line 1):
** def test_Location___()repr__(:
** tus = Location)32.2, - 111, 'US/Arizona', 700, 'Tucson'()
** expected = '\n'.join
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Synthesized repair in: 119131ms
Tidyparse (valid/total): 60/116
Original error:
def test_std(self):
""" sys.stdin からラッパーオブジェクトを作る """
wrapper = FileObjectWrapper(sys.stdin)
eq_(wrapper.name, '<stdin>')
ok_(hasattr(wrapper.file, 'read')
with wrapper.file as _:
pass
Good Repair:
def test_std(self):
""" sys.stdin からラッパーオブジェクトを作る """
wrapper = FileObjectWrapper(sys.stdin)
eq_(wrapper.name, '<stdin>')
** ok_hasattr(wrapper.file, 'read')
with wrapper.file as _:
pass
Synthesized repair in: 16882ms
Tidyparse (valid/total): 61/117
Original error:
def init(self):
self.set_tooltip(_("Click to expand/contract person\nRight-click for "
"options\nClick and drag in open area to rotate")
Good Repair:
def init(self):
** self.set_tooltip_("Click to expand/contract person\nRight-click for "
"options\nClick and drag in open area to rotate")
Synthesized repair in: 14311ms
Tidyparse (valid/total): 62/118
Original error:
import nose
import mock
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "..")
from modules.domain_modules import load_sound
Good Repair:
import nose
import mock
import os
import sys
** sys.path.append(os.path.joinos.path.dirname(__file__), "..")
from modules.domain_modules import load_sound
Synthesized repair in: 2742ms
Tidyparse (valid/total): 63/119
Original error:
import os
from app import settings
from babel.dates import get_timezone
basedir = os.path.abspath(os.path.dirname(__file__)))
LANGUAGES = {
'en': 'English',
}
BABEL_DEFAULT_LOCALE = 'en'
BABEL_DEFAULT_TIMEZONE = get_timezone('Europe/London')
Good Repair:
import os
from app import settings
from babel.dates import get_timezone
** basedir = os.path.abspath(os.path.dirname(__file__))
LANGUAGES = {
'en': 'English',
}
BABEL_DEFAULT_LOCALE = 'en'
BABEL_DEFAULT_TIMEZONE = get_timezone('Europe/London')
Synthesized repair in: 11483ms
Tidyparse (valid/total): 64/120
Original error:
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(RepositoryTestCase, 'test_'),
)
Good Repair:
def test_suite():
** return unittest.TestSuite(
unittest.makeSuite(RepositoryTestCase, 'test_'),
)
Synthesized repair in: 13480ms
Tidyparse (valid/total): 65/121
Original error:
def getLargestLoop(loops):
"Get largest loop from loops."
largestArea = - 999999999.0
largestLoop = None
for loop in loops:
loopArea = abs(getPolygonArea(loop)))
if loopArea > largestArea:
largestArea = loopArea
largestLoop = loop
return largestLoop
Good Repair:
def getLargestLoop(loops):
"Get largest loop from loops."
largestArea = - 999999999.0
largestLoop = None
for loop in loops:
** loopArea = abs(getPolygonArea(loop))
if loopArea > largestArea:
largestArea = loopArea
largestLoop = loop
return largestLoop
Synthesized repair in: 6308ms
Tidyparse (valid/total): 66/122
Original error:
def sort_queryset(self, queryset, desc = False):
order_by = ("-" if desc else "") + self.sort_field
queryset = queryset.order_by(order_by)
if self.sort_field.startswith("translations__"):
queryset = queryset.annotate(_dummy_ = Count(self.sort_field)
return queryset
Good Repair:
def sort_queryset(self, queryset, desc = False):
order_by = ("-" if desc else "") + self.sort_field
queryset = queryset.order_by(order_by)
if self.sort_field.startswith("translations__"):
** queryset = queryset.annotate(_dummy_ = Countself.sort_field)
return queryset
Synthesized repair in: 111250ms
Tidyparse (valid/total): 67/123
Original error:
def indentor(inblock, target):
if inblock:
for x in range(inblock):
target.write('\t'.rstrip('\n')))
Bad Repair: invalid syntax (<unknown>, line 2):
** def indentor(inblock, target:
if inblock:
for x in range(inblock):
target.write('\t'.rstrip('\n')))
Synthesized repair in: 13986ms
Tidyparse (valid/total): 67/124
Original error:
def word_key(word):
h = binascii.hexlify(word)
yield "".join(bin
Good Repair:
def word_key(word):
h = binascii.hexlify(word)
** yield "".joinbin
Synthesized repair in: 15544ms
Tidyparse (valid/total): 68/125
Original error:
def __repr__(self):
return '<%s: %s=%s>' %(self.__class__.__name__,
self.key, repr(self.value)
Bad Repair: unexpected indent (<unknown>, line 3):
def __repr__(self):
** return '<%s: %s=%s>' %self.__class__.__name__,
self.key, repr(self.value)
Synthesized repair in: 7425ms
Tidyparse (valid/total): 68/126
Original error:
class Solution:
def searchBigSortedArray(self, reader, target):
if reader == None:
return - 1
end = 0
while reader.get(end) < target and end < len(
start = 0
Bad Repair: invalid syntax (<unknown>, line 6):
class Solution:
def searchBigSortedArray(self, reader, target):
if reader == None:
return - 1
end = 0
** while reader.get(end) < target and end < len
start = 0
Synthesized repair in: 17135ms
Tidyparse (valid/total): 68/127
Original error:
class TwilioBroker:
ACCOUNT_SID = ""
AUTH_TOKEN = ""
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
def playMp3ToUser(self, phoneNumber, trackUrl):
call = self.client.calls.create(
to = phoneNumber,
from_ = "",
url = trackUrl,
method = "GET",
fallback_method = "GET",
status_callback_method = "GET",
record = "false"
Bad Repair: unexpected indent (<unknown>, line 7):
class TwilioBroker:
ACCOUNT_SID = ""
AUTH_TOKEN = ""
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
def playMp3ToUser(self, phoneNumber, trackUrl):
** call = self.client.calls.create
to = phoneNumber,
from_ = "",
url = trackUrl,
method = "GET",
fallback_method = "GET",
status_callback_method = "GET",
record = "false"
Synthesized repair in: 4006ms
Tidyparse (valid/total): 68/128
Original error:
def on_redraw_timer(self, event):
if not self.paused:
self.data.append(self.datagen.next()
self.draw_plot()
Bad Repair: invalid syntax (<unknown>, line 4):
def on_redraw_timer(self, event):
if not self.paused:
self.data.append(self.datagen.next()
** self.draw_plot)
Synthesized repair in: 31735ms
Tidyparse (valid/total): 68/129
Original error:
def get_timeout(self, service):
try:
return int(self.config.get('api', '%s_timeout' % service)
except ConfigParser.NoOptionError as e:
return 1
Good Repair:
def get_timeout(self, service):
try:
** return intself.config.get('api', '%s_timeout' % service)
except ConfigParser.NoOptionError as e:
return 1
Synthesized repair in: 4271ms
Tidyparse (valid/total): 69/130
Original error:
def sayhi(num):
result = ""
for i in range(min(num, 50):
result += "[" + str(i) + "]Hello world!\r\n"
return result
Good Repair:
def sayhi(num):
result = ""
** for i in range(minnum, 50):
result += "[" + str(i) + "]Hello world!\r\n"
return result
Synthesized repair in: 57485ms
Tidyparse (valid/total): 70/131
Original error:
def variables(self):
res = self.input_layer.variables()
for layer in self.layers:
res.extend(layer.variables()
return res
Good Repair:
def variables(self):
res = self.input_layer.variables()
for layer in self.layers:
** res.extendlayer.variables()
return res
Synthesized repair in: 21925ms
Tidyparse (valid/total): 71/132
Original error:
def logout():
logout_user()
flash(u"你已退出后台管理界面,如需进行设置请登录")
return redirect(url_for('frontend.index')
Good Repair:
def logout():
logout_user()
flash(u"你已退出后台管理界面,如需进行设置请登录")
** return redirecturl_for('frontend.index')
Synthesized repair in: 57089ms
Tidyparse (valid/total): 72/133
Original error:
def test_get_router_error(self):
self.mock_api.get_router.side_effect = w_exc.HTTPInternalServerError()
self.assertRaises(midonet_lib.MidonetApiException,
self.client.get_router, uuidutils.generate_uuid()
Good Repair:
def test_get_router_error(self):
self.mock_api.get_router.side_effect = w_exc.HTTPInternalServerError()
self.assertRaises(midonet_lib.MidonetApiException,
** self.client.get_router, uuidutils.generate_uuid)
Synthesized repair in: 20369ms
Tidyparse (valid/total): 73/134
Original error:
from settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
} BASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'repylia',
'USER': 'repylia',
'PASSWORD': 'tyranosaure',
'HOST': 'localhost',
}
}
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
Bad Repair: unexpected indent (<unknown>, line 5):
from settings import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
THUMBNAIL_DEBUG = DEBUG
** BASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'repylia',
'USER': 'repylia',
'PASSWORD': 'tyranosaure',
'HOST': 'localhost',
}
}
**
** EMAIL_HOST = 'localhost'
** EMAIL_PORT = 25
Synthesized repair in: 41892ms
Tidyparse (valid/total): 73/135
Original error:
def suite():
"""Gather all the tests from this package in a test suite."""
test_suite = unittest.TestSuite()
test_suite.addTest(unittest.makeSuite(TestFunctionalTflags, "test")
return test_suite
Good Repair:
def suite():
"""Gather all the tests from this package in a test suite."""
test_suite = unittest.TestSuite()
** test_suite.addTest(unittest.makeSuiteTestFunctionalTflags, "test")
return test_suite
Synthesized repair in: 7876ms
Tidyparse (valid/total): 74/136
Original error:
def place_file():
filename = "filename.txt"
ftp.storbinary("STOR " + filename, open(filename, "rb")
ftp.quit()
Bad Repair: invalid syntax (<unknown>, line 3):
def place_file():
filename = "filename.txt"
** ftp.storbinary"STOR " + filename, open(filename, "rb")
ftp.quit()
Synthesized repair in: 4903ms
Tidyparse (valid/total): 74/137
Original error:
def _random_cards(count):
"""Generates a set of *count* different cards chosen at random."""
cards = set()
while len(cards) < count:
cards.add(Card.random()
return cards
Good Repair:
def _random_cards(count):
"""Generates a set of *count* different cards chosen at random."""
cards = set()
while len(cards) < count:
** cards.add(Card.random)
return cards
Synthesized repair in: 39137ms
Tidyparse (valid/total): 75/138
Original error:
def add_arguments(self, parser):
parser.add_argument(
'-c', '--create',
action = 'store_true', dest = 'create', default = False,
help = 'Create locale subdirectories'
),
parser.add_argument(
'-b', '--backup',
action = 'store_true', dest = 'backup', default = False,
help = 'Create backup files of .po files'
Bad Repair: unexpected indent (<unknown>, line 8):
def add_arguments(self, parser):
parser.add_argument(
'-c', '--create',
action = 'store_true', dest = 'create', default = False,
help = 'Create locale subdirectories'
),
** parser.add_argument
'-b', '--backup',
action = 'store_true', dest = 'backup', default = False,
help = 'Create backup files of .po files'
Synthesized repair in: 25471ms
Tidyparse (valid/total): 75/139
Original error:
def check_vlan_exists(output):
"""Check whether VLAN id exists in the VLAN database."""
pattern = r"%.*not found in current VLAN database"
return not bool(re.search(pattern, output)
Good Repair:
def check_vlan_exists(output):
"""Check whether VLAN id exists in the VLAN database."""
pattern = r"%.*not found in current VLAN database"
** return not bool(re.searchpattern, output)
Synthesized repair in: 3354ms
Tidyparse (valid/total): 76/140
Original error:
def hasplugin(self, name):
"""Return True if the plugin with the given name is registered."""
return bool(self.get_plugin(name)
Good Repair:
def hasplugin(self, name):
"""Return True if the plugin with the given name is registered."""
** return bool(self.get_pluginname)
Synthesized repair in: 6921ms
Tidyparse (valid/total): 77/141
Original error:
class StudentDispatchForm(forms.Form):
student_password = forms.CharField(max_length = 20, required = False,
widget = forms.TextInput(attrs = {'class': 'span2', 'id': "student_password", 'placeholder': u"默认密码:邮箱名字", 'id': 'student_password'}
Bad Repair: invalid syntax (<unknown>, line 3):
class StudentDispatchForm(forms.Form):
student_password = forms.CharField(max_length = 20, required = False,
** widget = forms.TextInput)attrs = {'class': 'span2', 'id': "student_password", 'placeholder': u"默认密码:邮箱名字", 'id': 'student_password'}
Synthesized repair in: 26193ms
Tidyparse (valid/total): 77/142
Original error:
def retranslateUi(self, aboutDialog):
aboutDialog.setWindowTitle(QtGui.QApplication.translate("aboutDialog", "About RAFT", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("aboutDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, aboutDialog):
aboutDialog.setWindowTitle(QtGui.QApplication.translate("aboutDialog", "About RAFT", None, QtGui.QApplication.UnicodeUTF8))
** self.label_2.setText(QtGui.QApplication.translate)"aboutDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 248391ms
Tidyparse (valid/total): 77/143
Original error:
"""maps URL Configuration"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls),
]
Good Repair:
"""maps URL Configuration"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
** url(r'^admin/', includeadmin.site.urls),
]
Synthesized repair in: 21189ms
Tidyparse (valid/total): 78/144
Original error:
def OnMiddleDown(self, event):
if self.scroller.timer is None:
self.scroller.Start(event.GetPosition()
else:
self.scroller.Stop()
Good Repair:
def OnMiddleDown(self, event):
if self.scroller.timer is None:
** self.scroller.Start(event.GetPosition)
else:
self.scroller.Stop()
Synthesized repair in: 25166ms
Tidyparse (valid/total): 79/145
Original error:
def on_bookmark_clicked(self, button):
'''Open page if a bookmark is clicked.'''
self.ui.open_page(Path(button.zim_path)
Good Repair:
def on_bookmark_clicked(self, button):
'''Open page if a bookmark is clicked.'''
** self.ui.open_page(Pathbutton.zim_path)
Synthesized repair in: 9742ms
Tidyparse (valid/total): 80/146
Original error:
def post_build(self, pkt, pay):
if self.chksum == None:
pkt = pkt[: 6] + struct.pack("!H", checksum(pkt) + pkt[8: ]
return pkt
Good Repair:
def post_build(self, pkt, pay):
if self.chksum == None:
** pkt = pkt[: 6] + struct.pack("!H", checksumpkt) + pkt[8: ]
return pkt
Synthesized repair in: 105710ms
Tidyparse (valid/total): 81/147
Original error:
def local():
"""Run all local tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(Test, 'test_local')
return suite
Good Repair:
def local():
"""Run all local tests"""
suite = ServiceTestSuite()
** suite.addTest(unittest.makeSuiteTest, 'test_local')
return suite
Synthesized repair in: 6112ms
Tidyparse (valid/total): 82/148
Original error:
def main():
x, y = map(int, raw_input().split()
addWithoutOperator(x, y)
Good Repair:
def main():
** x, y = map(int, raw_input().split)
addWithoutOperator(x, y)
Synthesized repair in: 15999ms
Tidyparse (valid/total): 83/149
Original error:
def label(g, r):
"""label(graph, resource)"""
queries = ["""PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>""", """PREFIX dct: <http://purl.org/dc/terms/>""", """PREFIX bqbiol: <http://biomodels.net/biology-qualifiers/>""", """PREFIX bqbiol: <http://biomodels.net/biology-qualifiers/>""", """PREFIX dct: <http://purl.org/dc/terms/>"""
Good Repair:
def label(g, r):
"""label(graph, resource)"""
** queries = """PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>""", """PREFIX dct: <http://purl.org/dc/terms/>""", """PREFIX bqbiol: <http://biomodels.net/biology-qualifiers/>""", """PREFIX bqbiol: <http://biomodels.net/biology-qualifiers/>""", """PREFIX dct: <http://purl.org/dc/terms/>"""
Synthesized repair in: 4360ms
Tidyparse (valid/total): 84/150
Original error:
def readFunc(clockPin, dataPin):
"""The Data and Clock lines are both open collector. A resistor is connected between each line and +5V,"""
while(clockPin.value():
None
return dataPin.value()
Bad Repair: invalid syntax (<unknown>, line 3):
def readFunc(clockPin, dataPin):
"""The Data and Clock lines are both open collector. A resistor is connected between each line and +5V,"""
while(clockPin.value():
None
** return dataPin.value)
Synthesized repair in: 3991ms
Tidyparse (valid/total): 84/151
Original error:
def prompts(self):
"""An iterable of string prompts for updates that require consent."""
return itertools.chain(*(updater.prompts for updater in self)))
Good Repair:
def prompts(self):
"""An iterable of string prompts for updates that require consent."""
** return itertools.chain(*(updater.prompts for updater in self))
Synthesized repair in: 3639ms
Tidyparse (valid/total): 85/152
Original error:
def nll_gedi(p):
global kernel
kernel = gedi.kernel_optimization.new_kernel(kernel, np.exp(p)
ll = gedi.kernel_likelihood.likelihood(kernel, x, y, yerr)
return - ll if np.isfinite(ll) else 1e25
Bad Repair: invalid syntax (<unknown>, line 4):
def nll_gedi(p):
global kernel
kernel = gedi.kernel_optimization.new_kernel(kernel, np.exp(p)
** ll = gedi.kernel_likelihood.likelihoodkernel, x, y, yerr)
return - ll if np.isfinite(ll) else 1e25
Synthesized repair in: 10220ms
Tidyparse (valid/total): 85/153
Original error:
def calculate_work(prev_work, nBits):
if prev_work is None:
return None
return prev_work + target_to_work(calculate_target(nBits)
Good Repair:
def calculate_work(prev_work, nBits):
if prev_work is None:
return None
** return prev_work + target_to_work(calculate_targetnBits)
Synthesized repair in: 15924ms
Tidyparse (valid/total): 86/154
Original error:
def test_ToGS1(self):
print("***==== Test GS1 ====***"
sgtin96 = self._sgtin96.encode(self._companyPrefix, self._indicatorDigit, self._itemRef, self._filter, self._serialNumber)
print(sgtin96.toGS1())
print("***==== END Test To GS1 ====***"
print(""
Bad Repair: invalid syntax (<unknown>, line 3):
def test_ToGS1(self):
print("***==== Test GS1 ====***"
** sgtin96 = self._sgtin96.encodeself._companyPrefix, self._indicatorDigit, self._itemRef, self._filter, self._serialNumber)
print(sgtin96.toGS1())
print("***==== END Test To GS1 ====***"
** print)""
Synthesized repair in: 466310ms
Tidyparse (valid/total): 86/155
Original error:
from __future__ import print_function
import hashlib
import sys
print(hashlib.sha256(sys.argv[1]).hexdigest()
Good Repair:
from __future__ import print_function
import hashlib
import sys
** printhashlib.sha256(sys.argv[1]).hexdigest()
Synthesized repair in: 14256ms
Tidyparse (valid/total): 87/156
Original error:
def raspberry_pi():
api.env.hosts = ['{0}.local'.format(api.prompt('Raspberry Pi: ')]
api.env.user = 'pi'
Good Repair:
def raspberry_pi():
** api.env.hosts = ['{0}.local'.formatapi.prompt('Raspberry Pi: ')]
api.env.user = 'pi'
Synthesized repair in: 68787ms
Tidyparse (valid/total): 88/157
Original error:
def getIntEnable(self):
intEnable = bus.read_byte_data(self.address, INT_ENABLE)
if self.debug == True:
print("INT_ENABLE(0x2E): " + format(intEnable, '#010b')
return intEnable
Bad Repair: invalid syntax (<unknown>, line 5):
def getIntEnable(self):
intEnable = bus.read_byte_data(self.address, INT_ENABLE)
if self.debug == True:
** print("INT_ENABLE0x2E): " + format(intEnable, '#010b')
return intEnable
Synthesized repair in: 27791ms
Tidyparse (valid/total): 88/158
Original error:
import os
from django.core.urlresolvers import reverse_lazy
CODE_ROOT = os.path.dirname(os.path.dirname(__file__)))
ROOT = os.path.dirname(CODE_ROOT)
Good Repair:
import os
from django.core.urlresolvers import reverse_lazy
** CODE_ROOT = os.path.dirname(os.path.dirname(__file__))
ROOT = os.path.dirname(CODE_ROOT)
Synthesized repair in: 19754ms
Tidyparse (valid/total): 89/159
Original error:
import netaddr
from neutron.common import constants as common_const
from ryu.lib.mac import haddr_to_bin
from dragonflow._i18n import _
from dragonflow.controller.common.arp_responder import ArpResponder
from dragonflow.controller.common import constants as const
from dragonflow.controller.df_base_app import DFlowApp
from oslo_config import cfg
DF_L2_APP_OPTS = [
cfg.BoolOpt(
'l2_responder',
default = True,
help = _('Install OVS flows to respond to ARP requests.')))
]
OF_IN_PORT = 0xfff8
Good Repair:
import netaddr
from neutron.common import constants as common_const
from ryu.lib.mac import haddr_to_bin
from dragonflow._i18n import _
from dragonflow.controller.common.arp_responder import ArpResponder
from dragonflow.controller.common import constants as const
from dragonflow.controller.df_base_app import DFlowApp
from oslo_config import cfg
DF_L2_APP_OPTS = [
cfg.BoolOpt(
'l2_responder',
default = True,
** help = _('Install OVS flows to respond to ARP requests.'))
]
**
** OF_IN_PORT = 0xfff8
Synthesized repair in: 3475ms
Tidyparse (valid/total): 90/160
Original error:
def __repr__(self):
return "<%s %r>" %(self.__class__.__name__,
getattr(self, 'name', None)
Bad Repair: unexpected indent (<unknown>, line 3):
def __repr__(self):
** return "<%s %r>" %self.__class__.__name__,
getattr(self, 'name', None)
Synthesized repair in: 26999ms
Tidyparse (valid/total): 90/161
Original error:
def test_table_count_rows(self):
count = self.db.tables.Invoice.count
self.assertEqual(count), 412)
Good Repair:
def test_table_count_rows(self):
count = self.db.tables.Invoice.count
** self.assertEqual(count, 412)
Synthesized repair in: 2933ms
Tidyparse (valid/total): 91/162
Original error:
def drawCloud(tags: list, filename: str, fontname: str = 'D2Coding', size = (1920, 1080))):
pytagcloud.create_tag_image(tags, filename, fontname = fontname, size = size)
webbrowser.open(filename)
Good Repair:
** def drawCloud(tags: list, filename: str, fontname: str = 'D2Coding', size = (1920, 1080)):
pytagcloud.create_tag_image(tags, filename, fontname = fontname, size = size)
webbrowser.open(filename)
Synthesized repair in: 31600ms
Tidyparse (valid/total): 92/163
Original error:
def namesAreExplicit(nameset, objnames):
"""This function checks whether two sets of names have equal names."""
return len(nameset.intersection(objnames))) == 0
Good Repair:
def namesAreExplicit(nameset, objnames):
"""This function checks whether two sets of names have equal names."""
** return len(nameset.intersection(objnames)) == 0
Synthesized repair in: 11941ms
Tidyparse (valid/total): 93/164
Original error:
def size_unicode(arg):
"""Calculate the size of a unicode string"""
return len(arg.encode('utf-8')
Bad Repair: invalid syntax (<unknown>, line 3):
def size_unicode(arg):
"""Calculate the size of a unicode string"""
** return len(arg.encode'utf-8')
Synthesized repair in: 10185ms
Tidyparse (valid/total): 93/165
Original error:
def update_matrix_axes(self):
""" Adjust the x and y axes in the image according to the input."""
self.odmr_matrix_image.setRect(
QtCore.QRectF(
self._odmr_logic.mw_start,
0,
self._odmr_logic.mw_stop - self._odmr_logic.mw_start,
self._odmr_logic.number_of_lines
)))
Good Repair:
def update_matrix_axes(self):
""" Adjust the x and y axes in the image according to the input."""
self.odmr_matrix_image.setRect(
QtCore.QRectF(
self._odmr_logic.mw_start,
0,
self._odmr_logic.mw_stop - self._odmr_logic.mw_start,
self._odmr_logic.number_of_lines
** ))
Synthesized repair in: 5408ms
Tidyparse (valid/total): 94/166
Original error:
'''This is a plugin used to test the Plugin functionality.'''
from persistent import Persistent
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "..")))
from src.core.plugin import Plugin
from src.core.db import CustomFolder
Command = None
Good Repair:
'''This is a plugin used to test the Plugin functionality.'''
from persistent import Persistent
import sys
import os
** sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from src.core.plugin import Plugin
from src.core.db import CustomFolder
Command = None
Synthesized repair in: 8833ms
Tidyparse (valid/total): 95/167
Original error:
from ... import share
async def on_ready():
print(" Connected.\n"
+ "Ready.\n"
+ "---\n"
+ "To add this bot to a server, use this link: \n"
+ "{}\n".format(share.discord.utils.oauth_url(share.client_id)
+ "---")
Good Repair:
from ... import share
async def on_ready():
print(" Connected.\n"
+ "Ready.\n"
+ "---\n"
+ "To add this bot to a server, use this link: \n"
** + "{}\n".formatshare.discord.utils.oauth_url(share.client_id)
+ "---")
Synthesized repair in: 26148ms
Tidyparse (valid/total): 96/168
Original error:
def load(self):
views = load_lz4_compressed(self.view_path, shape = (- 1, 1, self.nb_views,
128, 256)
return views
Bad Repair: positional argument follows keyword argument (<unknown>, line 2):
def load(self):
** views = load_lz4_compressed(self.view_path, shape = - 1, 1, self.nb_views,
128, 256)
return views
Synthesized repair in: 23333ms
Tidyparse (valid/total): 96/169
Original error:
"""File for convert.py testing unbalanced parentheses."""
self.assertEqual(19, 19)
self.assertEqual(a, b
self.assertEqual(21, 21)
Bad Repair: invalid syntax (<unknown>, line 4):
"""File for convert.py testing unbalanced parentheses."""
self.assertEqual(19, 19)
self.assertEqual(a, b
** self.assertEqual21, 21)
Synthesized repair in: 3535ms
Tidyparse (valid/total): 96/170
Original error:
def rec_edit(self, z, _type, _id, name, content, service_mode = 1, ttl = 1):
fmt = "a=%s&tkn=%s&id=%s&email=%s&z=%s&type=%s&name=%s&content=%s&ttl=%s&service_mode=%s"
return self.callAPI(fmt %('rec_edit', self.TOKEN, _id, self.EMAIL, z, _type, name, content, ttl, service_mode)
Good Repair:
def rec_edit(self, z, _type, _id, name, content, service_mode = 1, ttl = 1):
fmt = "a=%s&tkn=%s&id=%s&email=%s&z=%s&type=%s&name=%s&content=%s&ttl=%s&service_mode=%s"
** return self.callAPI(fmt %'rec_edit', self.TOKEN, _id, self.EMAIL, z, _type, name, content, ttl, service_mode)
Synthesized repair in: 7486ms
Tidyparse (valid/total): 97/171
Original error:
def printList(self):
""" print the whole queue """
item = self.head
print('[',
while item:
print(item, )
item = item.next
Bad Repair: invalid syntax (<unknown>, line 5):
def printList(self):
""" print the whole queue """
item = self.head
** print(')',
while item:
print(item, )
item = item.next
Synthesized repair in: 29485ms
Tidyparse (valid/total): 97/172
Original error:
def test_plugin_help_shows_plugin(self):
os.mkdir('plugin_test')
f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
f.write(""" from bzrlib import commands"""
Bad Repair: invalid syntax (<unknown>, line 4):
def test_plugin_help_shows_plugin(self):
os.mkdir('plugin_test')
f = open(osutils.pathjoin('plugin_test', 'myplug.py'), 'w')
** f.write""" from bzrlib import commands"""
Synthesized repair in: 63321ms
Tidyparse (valid/total): 97/173
Original error:
main()
print("Ciao Mondo! :-)")
if __name__ == "__main__":
main()
Bad Repair: invalid syntax (<unknown>, line 3):
** main(
print("Ciao Mondo! :-)")
if __name__ == "__main__":
main()
Synthesized repair in: 4521ms
Tidyparse (valid/total): 97/174
Original error:
import os
import socket
import run
import datetime
import pprint
import upscale
from upscale.config import config
from upscale.db.model import Session, Namespace, Domain, Project, Template
from upscale.utils import lxc
datadir = os.path.join(os.path.dirname(os.path.realpath(upscale.__file__), 'data')
Good Repair:
import os
import socket
import run
import datetime
import pprint
import upscale
from upscale.config import config
from upscale.db.model import Session, Namespace, Domain, Project, Template
from upscale.utils import lxc
** datadir = os.path.join(os.path.dirname(os.path.realpathupscale.__file__), 'data')
Synthesized repair in: 14041ms
Tidyparse (valid/total): 98/175
Original error:
def _set_flash_msg(request, message):
set_cookie('ls_message',
SecureCookie({'m': message}, settings.SECRET_KEY).serialize()
Bad Repair: invalid syntax (<unknown>, line 3):
def _set_flash_msg(request, message):
set_cookie('ls_message',
** SecureCookie{'m': message}, settings.SECRET_KEY).serialize()
Synthesized repair in: 35233ms
Tidyparse (valid/total): 98/176
Original error:
def check_headers(request):
"A view that responds with value of the X-ARG-CHECK header"
return HttpResponse('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')
Bad Repair: invalid syntax (<unknown>, line 3):
def check_headers(request):
"A view that responds with value of the X-ARG-CHECK header"
** return HttpResponse'HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')
Synthesized repair in: 7768ms
Tidyparse (valid/total): 98/177
Original error:
def test_close_base_tag(self):
br = mechanize.Browser()
response = test_html_response("</base>")
br.set_response(response)
list(br.links()
Good Repair:
def test_close_base_tag(self):
br = mechanize.Browser()
response = test_html_response("</base>")
br.set_response(response)
** list(br.links)
Synthesized repair in: 94865ms
Tidyparse (valid/total): 99/178
Original error:
def _make_class_ldif(self, class_name, class_dn, sub_oid):
ldif = """dn: """ + class_dn + """objectClass: top""" + class_name + """adminDisplayName: """ + class_name + """cn: """ + class_name + """governsId: 1.3.6.1.4.1.7165.4.6.2.7.%d.""" % sub_oid + str(random.randint(1, 100000) + """instanceType: 4"""
return ldif
Good Repair:
def _make_class_ldif(self, class_name, class_dn, sub_oid):
** ldif = """dn: """ + class_dn + """objectClass: top""" + class_name + """adminDisplayName: """ + class_name + """cn: """ + class_name + """governsId: 1.3.6.1.4.1.7165.4.6.2.7.%d.""" % sub_oid + str(random.randint1, 100000) + """instanceType: 4"""
return ldif
Synthesized repair in: 4657ms
Tidyparse (valid/total): 100/179
Original error:
def sources(self, url, quality):
sources = []
try:
headers = {'User-Agent': random_agent(),
'X-Requested-With': 'XMLHttpRequest',
'Referer': url,
'Host': 'm4ufree.info'
Bad Repair: invalid syntax (<unknown>, line 4):
def sources(self, url, quality):
sources = []
try:
** headers = 'User-Agent': random_agent(),
'X-Requested-With': 'XMLHttpRequest',
'Referer': url,
'Host': 'm4ufree.info'
Synthesized repair in: 15682ms
Tidyparse (valid/total): 100/180
Original error:
def get_auth_url(self):
'''获取用户授权url'''
return 'https: //api.weibo.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s' %(self.appkey, urllib.quote(self.callback)
Good Repair:
def get_auth_url(self):
'''获取用户授权url'''
** return 'https: //api.weibo.com/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s' %self.appkey, urllib.quote(self.callback)
Synthesized repair in: 3145ms
Tidyparse (valid/total): 101/181
Original error:
def __init__(self, accessor, paths):
super()
self._accessor = accessor
if paths != None & & not paths.isEmpty():
for
path = None
in paths) updateRecursive(path)
Bad Repair: invalid syntax (<unknown>, line 4):
def __init__(self, accessor, paths):
super()
self._accessor = accessor
if paths != None & & not paths.isEmpty():
for
path = None
** in paths updateRecursive(path)
Synthesized repair in: 8348ms
Tidyparse (valid/total): 101/182
Original error:
def _filter_counts(filter_dict):
'''Returns an immutable ordered dict of filter: counts; when an item'''
return OrderedDict(utils.sort_dict(filter_dict)))
Good Repair:
def _filter_counts(filter_dict):
'''Returns an immutable ordered dict of filter: counts; when an item'''
** return OrderedDict(utils.sort_dict(filter_dict))
Synthesized repair in: 3633ms
Tidyparse (valid/total): 102/183
Original error:
def _on_parent_resized(self):
"""Special slot hooked up to the event filter."""
self.resize(self.parentWidget().size()
Good Repair:
def _on_parent_resized(self):
"""Special slot hooked up to the event filter."""
** self.resize(self.parentWidget().size)
Synthesized repair in: 3920ms
Tidyparse (valid/total): 103/184
Original error:
def _check_instructor_not_in_attendees(self):
if self.instructor_id and self.instructor_id in self.attendee_ids:
raise exceptions.ValidationError(
_("A session's instructor can't be an attendee")
Bad Repair: invalid syntax (<unknown>, line 4):
def _check_instructor_not_in_attendees(self):
if self.instructor_id and self.instructor_id in self.attendee_ids:
raise exceptions.ValidationError(
** _"A session's instructor can't be an attendee")
Synthesized repair in: 7792ms
Tidyparse (valid/total): 103/185
Original error:
def scrapePage(page):
pool = Pool.objects.get(name =
tables =
for table in tables:
parseTable(table, pool)
Bad Repair: invalid syntax (<unknown>, line 2):
def scrapePage(page):
** pool = Pool.objects.getname =
tables =
for table in tables:
parseTable(table, pool)
Synthesized repair in: 7873ms
Tidyparse (valid/total): 103/186
Original error:
def block_nav_menu(self, context, nodes):
if self.has_filters:
nodes.append(loader.render_to_string('xadmin/blocks/model_list.nav_menu.filters.html', context_instance = context)))
Good Repair:
def block_nav_menu(self, context, nodes):
if self.has_filters:
** nodes.append(loader.render_to_string('xadmin/blocks/model_list.nav_menu.filters.html', context_instance = context))
Synthesized repair in: 12174ms
Tidyparse (valid/total): 104/187
Original error:
def write_to_json(path, data):
with open(path, 'w') as f:
f.write(json.dumps(data, indent = 2)))
Bad Repair: invalid syntax (<unknown>, line 2):
def write_to_json(path, data):
** with open(path, 'w' as f:
f.write(json.dumps(data, indent = 2)))
Synthesized repair in: 19930ms
Tidyparse (valid/total): 104/188
Original error:
class MusicAppTestCase(BaseTestCaseWithPatchedHome):
"""Base test case that launches the music-app."""
def setUp(self):
super(MusicAppTestCase, self).setUp()
self.app = MusicApp(self.launcher()
Good Repair:
class MusicAppTestCase(BaseTestCaseWithPatchedHome):
"""Base test case that launches the music-app."""
def setUp(self):
super(MusicAppTestCase, self).setUp()
** self.app = MusicApp(self.launcher)
Synthesized repair in: 30057ms
Tidyparse (valid/total): 105/189
Original error:
def get_fake_volume_info_data(target_portal, volume_id):
return{
'driver_volume_type': 'iscsi',
'data': {
'volume_id': 1,
'target_iqn': 'iqn.2010-10.org.openstack:volume-' + volume_id,
'target_portal': target_portal,
'target_lun': 1,
'auth_method': 'CHAP',
'auth_method': 'fake',
'auth_method': 'fake',
}
Bad Repair: invalid syntax (<unknown>, line 5):
def get_fake_volume_info_data(target_portal, volume_id):
return{
'driver_volume_type': 'iscsi',
** 'data':
'volume_id': 1,
'target_iqn': 'iqn.2010-10.org.openstack:volume-' + volume_id,
'target_portal': target_portal,
'target_lun': 1,
'auth_method': 'CHAP',
'auth_method': 'fake',
'auth_method': 'fake',
}
Synthesized repair in: 8572ms
Tidyparse (valid/total): 105/190
Original error:
def call(self, params):
"""Make an API call to the wiki.*params* is a dictionary of query string"""
return json.loads(self._fetch_http(self._api_url, params)
Good Repair:
def call(self, params):
"""Make an API call to the wiki.*params* is a dictionary of query string"""
** return json.loadsself._fetch_http(self._api_url, params)
Synthesized repair in: 4048ms
Tidyparse (valid/total): 106/191
Original error:
def create_summary_metadata(display_name, description):
"""Create a `tf.SummaryMetadata` proto for image plugin data."""
content = plugin_data_pb2.ImagePluginData(version = PROTO_VERSION)
metadata = tf.SummaryMetadata(
display_name = display_name,
summary_description = description,
plugin_data = tf.SummaryMetadata.PluginData(
plugin_name = PLUGIN_NAME,
content = content.SerializeToString())
return metadata
Bad Repair: unexpected indent (<unknown>, line 5):
def create_summary_metadata(display_name, description):
"""Create a `tf.SummaryMetadata` proto for image plugin data."""
content = plugin_data_pb2.ImagePluginData(version = PROTO_VERSION)
** metadata = tf.SummaryMetadata
display_name = display_name,
summary_description = description,
plugin_data = tf.SummaryMetadata.PluginData(
plugin_name = PLUGIN_NAME,
content = content.SerializeToString())
return metadata
Synthesized repair in: 11763ms
Tidyparse (valid/total): 106/192
Original error:
def buttonbox(self):
box = Frame(self)
w = Button(box, text = 'OK', width = 10, command = self.ok, default = ACTIVE)
w.pack(side = LEFT, padx = 5, pady = 5)
w = Button(box, text = 'Cancel', width = 10
Bad Repair: cannot assign to literal (<unknown>, line 5):
def buttonbox(self):
box = Frame(self)
w = Button(box, text = 'OK', width = 10, command = self.ok, default = ACTIVE)
w.pack(side = LEFT, padx = 5, pady = 5)
** w = Buttonbox, text = 'Cancel', width = 10
Synthesized repair in: 62857ms
Tidyparse (valid/total): 106/193
Original error:
def run():
runner = unittest.TextTestRunner(verbosity = 2)
runner.run(suite()
Good Repair:
def run():
runner = unittest.TextTestRunner(verbosity = 2)
** runner.runsuite()
Synthesized repair in: 23640ms
Tidyparse (valid/total): 107/194
Original error:
def getGlobalSettings(config):
for k, v in dict(config.items('globals').iteritems():
cfg = configuration()
cfg.name = k
cfg.value = v
yield cfg
Good Repair:
def getGlobalSettings(config):
** for k, v in dict(config.items('globals').iteritems):
cfg = configuration()
cfg.name = k
cfg.value = v
yield cfg
Synthesized repair in: 9825ms
Tidyparse (valid/total): 108/195
Original error:
def retranslateUi(self, NewPatternDialog):
NewPatternDialog.setWindowTitle(_translate("NewPatternDialog", "sconcho: New Pattern Grid", None))
self.label.setText(_translate("NewPatternDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, NewPatternDialog):
NewPatternDialog.setWindowTitle(_translate("NewPatternDialog", "sconcho: New Pattern Grid", None))
** self.label.setText(_translate)"NewPatternDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 167704ms
Tidyparse (valid/total): 108/196
Original error:
def size(myStack):
count = 0
while(not isinstance(myStack, noneNode):
count = count + 1
myStack = myStack.next
Good Repair:
def size(myStack):
count = 0
** while(not isinstancemyStack, noneNode):
count = count + 1
myStack = myStack.next
Synthesized repair in: 23285ms
Tidyparse (valid/total): 109/197
Original error:
def test_20_notfound_cluster(self):
command = "show cluster --cluster cluster-does-not-exist"
self.notfoundtest(command.split(" ")
Bad Repair: invalid syntax (<unknown>, line 3):
def test_20_notfound_cluster(self):
command = "show cluster --cluster cluster-does-not-exist"
** self.notfoundtest(command.split" ")
Synthesized repair in: 7203ms
Tidyparse (valid/total): 109/198
Original error:
def server_changed(self, x):
if x:
self.change_server(str(x.text(0))), self.protocol)
Good Repair:
def server_changed(self, x):
if x:
** self.change_server(str(x.text(0))), self.protocol
Synthesized repair in: 21272ms
Tidyparse (valid/total): 110/199
Original error:
def get_command_line(self):
buf = self.view.get_buffer()
inp = buf.get_iter_at_mark(buf.get_mark("input")
cur = buf.get_end_iter()
return buf.get_text(inp, cur, False)
Bad Repair: invalid syntax (<unknown>, line 3):
def get_command_line(self):
buf = self.view.get_buffer()
** inp = buf.get_iter_at_mark(buf.get_mark"input")
cur = buf.get_end_iter()
return buf.get_text(inp, cur, False)
Synthesized repair in: 41597ms
Tidyparse (valid/total): 110/200
Original error:
def make_session(token = None, state = None, scope = None):
return OAuth2Session(
client_id = data_info.OAUTH2_CLIENT_ID,
token = token,
state = state,
scope = scope,
redirect_uri = data_info.OAUTH2_REDIRECT_URI,
auto_refresh_kwargs = {
'client_id': data_info.OAUTH2_CLIENT_ID,
'client_secret': data_info.OAUTH2_CLIENT_SECRET,
},
auto_refresh_url = data_info.TOKEN_URL,
token_updater = token_updater
Bad Repair: unexpected indent (<unknown>, line 3):
def make_session(token = None, state = None, scope = None):
** return OAuth2Session
client_id = data_info.OAUTH2_CLIENT_ID,
token = token,
state = state,
scope = scope,
redirect_uri = data_info.OAUTH2_REDIRECT_URI,
auto_refresh_kwargs = {
'client_id': data_info.OAUTH2_CLIENT_ID,
'client_secret': data_info.OAUTH2_CLIENT_SECRET,
},
auto_refresh_url = data_info.TOKEN_URL,
token_updater = token_updater
Synthesized repair in: 9263ms
Tidyparse (valid/total): 110/201
Original error:
def write_dump(f, data, prefix = "", sep = ":"):
import json
if prefix: f.write("".join(prefix, sep, json.dumps())
else: f.write(json.dumps())
Bad Repair: invalid syntax (<unknown>, line 3):
def write_dump(f, data, prefix = "", sep = ":"):
import json
** if prefix: f.write"".join(prefix, sep, json.dumps())
else: f.write(json.dumps())
Synthesized repair in: 37069ms
Tidyparse (valid/total): 110/202
Original error:
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.widget), _translate("MainWindow", "File list"))
self.textBrowser_4.setHtml(_translate("MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 5):
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.widget), _translate("MainWindow", "File list"))
** self.textBrowser_4.setHtml(_translate)"MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 801925ms
Tidyparse (valid/total): 110/203
Original error:
def readline(self):
r"""Reads the next line from the file.Leaves the '\n' at the end."""
self._preread_check()
return compat.as_str_any(self._read_buf.ReadLineAsString()
Good Repair:
def readline(self):
r"""Reads the next line from the file.Leaves the '\n' at the end."""
self._preread_check()
** return compat.as_str_anyself._read_buf.ReadLineAsString()
Synthesized repair in: 41246ms
Tidyparse (valid/total): 111/204
Original error:
def _bu(self, string):
"""bold and underline string."""
return ircutils.bold(ircutils.underline(string)))
Good Repair:
def _bu(self, string):
"""bold and underline string."""
** return ircutils.bold(ircutils.underline(string))
Synthesized repair in: 3700ms
Tidyparse (valid/total): 112/205
Original error:
def locator(self):
"""Helper property that gets a corresponding CCXLocator for this CCX."""
return CCXLocator.from_course_locator(self.course_id, unicode(self.id)
Good Repair:
def locator(self):
"""Helper property that gets a corresponding CCXLocator for this CCX."""
** return CCXLocator.from_course_locatorself.course_id, unicode(self.id)
Synthesized repair in: 19109ms
Tidyparse (valid/total): 113/206
Original error:
def bold(self, match):
"""Convert bold markup."""
line = re.sub('\*\*', '*', match.group(1)
return line
Bad Repair: invalid syntax (<unknown>, line 3):
def bold(self, match):
"""Convert bold markup."""
** line = re.sub'\*\*', '*', match.group(1)
return line
Synthesized repair in: 3198ms
Tidyparse (valid/total): 113/207
Original error:
def has_perm(cls, user, permission):
"""Convenience method for testing if a user has our custom permissions."""
return user.has_perm(cls.perm_name(permission)
Good Repair:
def has_perm(cls, user, permission):
"""Convenience method for testing if a user has our custom permissions."""
** return user.has_permcls.perm_name(permission)
Synthesized repair in: 7163ms
Tidyparse (valid/total): 114/208
Original error:
import functools
import operator
import os
import sys
import pytest
from click.testing import CliRunner
if sys.version_info >(3, ):
reduce = functools.reduce
test_files = [os.path.join(os.path.dirname(__file__), p) for p in[
'data/RGB.byte.tif', 'data/float.tif', 'data/float_nan.tif', 'data/shade.tif']
Bad Repair: invalid syntax (<unknown>, line 9):
import functools
import operator
import os
import sys
import pytest
from click.testing import CliRunner
if sys.version_info >(3, ):
reduce = functools.reduce
** test_files = os.path.join(os.path.dirname(__file__), p) for p in[
'data/RGB.byte.tif', 'data/float.tif', 'data/float_nan.tif', 'data/shade.tif']
Synthesized repair in: 28297ms
Tidyparse (valid/total): 114/209
Original error:
def rst_add_mathjax(content):
"""Adds mathjax script for reStructuredText"""
_, ext = os.path.splitext(os.path.basename(content.source_path)
if ext != '.rst':
return
if 'class="math"' in content._content:
content._content += "<script type='text/javascript'>%s</script>" % rst_add_mathjax.mathjax_script
Good Repair:
def rst_add_mathjax(content):
"""Adds mathjax script for reStructuredText"""
** _, ext = os.path.splitextos.path.basename(content.source_path)
if ext != '.rst':
return
if 'class="math"' in content._content:
content._content += "<script type='text/javascript'>%s</script>" % rst_add_mathjax.mathjax_script
Synthesized repair in: 8963ms
Tidyparse (valid/total): 115/210
Original error:
import sys
print("Simple Sequence Beats Big Players".split(' ')[
len(sys.argv[1]) / 2 % 5 if len(sys.argv) > 1 else 0
]
Bad Repair: invalid syntax (<unknown>, line 2):
import sys
** print("Simple Sequence Beats Big Players".split' ')[
len(sys.argv[1]) / 2 % 5 if len(sys.argv) > 1 else 0
]
Synthesized repair in: 47678ms
Tidyparse (valid/total): 115/211
Original error:
import os
import jinja2
import webapp2
template_dir = os.path.realpath(os.path.join(
os.path.dirname(__file__), "../templates"
)
jinja_env = jinja2.Environment(
loader = jinja2.FileSystemLoader(template_dir),
autoescape = True
)
Bad Repair: invalid syntax (<unknown>, line 7):
import os
import jinja2
import webapp2
template_dir = os.path.realpath(os.path.join(
os.path.dirname(__file__), "../templates"
)
** jinja_env = jinja2.Environment
loader = jinja2.FileSystemLoader(template_dir),
autoescape = True
)
Synthesized repair in: 8036ms
Tidyparse (valid/total): 115/212
Original error:
def main():
printHeader()
for n in range(startRange, endRange, stepRange):
averageDistance = getRandomWalk(n)
print("For{} steps, the average distance is: {}".format(n, averageDistance)
Bad Repair: invalid syntax (<unknown>, line 5):
def main():
printHeader()
for n in range(startRange, endRange, stepRange):
averageDistance = getRandomWalk(n)
** print"For{} steps, the average distance is: {}".format(n, averageDistance)
Synthesized repair in: 33091ms
Tidyparse (valid/total): 115/213
Original error:
def main(* args):
"""Starts unit testing and passes all command line arguments to py.test."""
return pytest.main(list(args)
Good Repair:
def main(* args):
"""Starts unit testing and passes all command line arguments to py.test."""
** return pytest.main(listargs)
Synthesized repair in: 8639ms
Tidyparse (valid/total): 116/214
Original error:
def setUp(self):
super(TestCeleryFixture, self).setUp()
self.celery = self.useFixture(CeleryFixture()
Good Repair:
def setUp(self):
super(TestCeleryFixture, self).setUp()
** self.celery = self.useFixture(CeleryFixture)
Synthesized repair in: 59346ms
Tidyparse (valid/total): 117/215
Original error:
def test_value(self):
fn1 = lambda: 'fn1'
fn2 = lambda: 'fn2'
expected = lambda v: 'fn1' if v else 'fn2'
for v in[True, False, 1, 0]:
o = utils.static_cond(v, fn1, fn2)
self.assertEqual(o, expected(v)
Good Repair:
def test_value(self):
fn1 = lambda: 'fn1'
fn2 = lambda: 'fn2'
expected = lambda v: 'fn1' if v else 'fn2'
for v in[True, False, 1, 0]:
o = utils.static_cond(v, fn1, fn2)
** self.assertEqualo, expected(v)
Synthesized repair in: 15140ms
Tidyparse (valid/total): 118/216
Original error:
def add_local_plugin(self, module_name, ws_name, pfx = None):
self.local_plugins.append(
Bunch(module = module_name, ws = ws_name, pfx = pfx)
Bad Repair: unexpected indent (<unknown>, line 3):
def add_local_plugin(self, module_name, ws_name, pfx = None):
** self.local_plugins.append
Bunch(module = module_name, ws = ws_name, pfx = pfx)
Synthesized repair in: 14969ms
Tidyparse (valid/total): 118/217
Original error:
def PrintHeader(self):
print("""// Copyright 2009 Google Inc. All Rights Reserved.""" %{'key_type': self._key_type,
'mapname': self._mapname,
'result_type': self._result_type}
Bad Repair: invalid syntax (<unknown>, line 2):
def PrintHeader(self):
** print"""// Copyright 2009 Google Inc. All Rights Reserved.""" %{'key_type': self._key_type,
'mapname': self._mapname,
'result_type': self._result_type}
Synthesized repair in: 3747ms
Tidyparse (valid/total): 118/218
Original error:
def get_db_prep_value(self, value, connection = None, prepared = False):
if not value: return ""
assert(isinstance(value, list) or isinstance(value, tuple))
return u','.join(s for s in value])
Good Repair:
def get_db_prep_value(self, value, connection = None, prepared = False):
if not value: return ""
assert(isinstance(value, list) or isinstance(value, tuple))
** return u','.join(s for s in value)
Synthesized repair in: 25481ms
Tidyparse (valid/total): 119/219
Original error:
def test():
"""Run the unit tests"""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity = 2).run(tests
Good Repair:
def test():
"""Run the unit tests"""
import unittest
tests = unittest.TestLoader().discover('tests')
** unittest.TextTestRunner(verbosity = 2).runtests
Synthesized repair in: 17262ms
Tidyparse (valid/total): 120/220
Original error:
def create_from_tabular_info(tabular_info):
assert isinstance(tabular_info, TabularFileInfo), 'tabular_info must be a TabularFileInfo object'
assert tabular_info.dv_file is not None, "tabular_info.file cannot be None"
delim = tabular_info.delimiter,
tabular_info = tabular_info)
Bad Repair: unexpected indent (<unknown>, line 4):
def create_from_tabular_info(tabular_info):
assert isinstance(tabular_info, TabularFileInfo), 'tabular_info must be a TabularFileInfo object'
assert tabular_info.dv_file is not None, "tabular_info.file cannot be None"
delim = tabular_info.delimiter,
** tabular_info = tabular_info
Synthesized repair in: 8797ms
Tidyparse (valid/total): 120/221
Original error:
def clone_unofficial_plugin(plugin):
os.system(GIT_CLONE_COMMAND_TEMPLATE.format(
plugin.id, plugin.local_repository_path
)
Bad Repair: invalid syntax (<unknown>, line 3):
def clone_unofficial_plugin(plugin):
** os.system(GIT_CLONE_COMMAND_TEMPLATE.format
plugin.id, plugin.local_repository_path
)
Synthesized repair in: 3633ms
Tidyparse (valid/total): 120/222
Original error:
'''Map the initial proportions diagnosed, treated, and viral suppressed.'''
import os.path
import sys
import pandas
sys.path.append(os.path.dirname(__file__)
import common
sys.path.append('..')
import model
import mapplot
Good Repair:
'''Map the initial proportions diagnosed, treated, and viral suppressed.'''
import os.path
import sys
import pandas
** sys.path.append(os.path.dirname__file__)
import common
sys.path.append('..')
import model
import mapplot
Synthesized repair in: 2946ms
Tidyparse (valid/total): 121/223
Original error:
def restore_path():
if DEBUG:
print('Removing %r from sys.path' %(sys.path[0])
del sys.path[0]
return
Good Repair:
def restore_path():
if DEBUG:
** print('Removing %r from sys.path' %sys.path[0])
del sys.path[0]
return
Synthesized repair in: 12303ms
Tidyparse (valid/total): 122/224
Original error:
def get_columns(filename):
'''Takes a file and returns a 2-D numpy array of columns 6, 7, 39, and 72.'''
result = np.loadtxt(
result = np.transpose(result)
return result
Good Repair:
def get_columns(filename):
'''Takes a file and returns a 2-D numpy array of columns 6, 7, 39, and 72.'''
** result = np.loadtxt
result = np.transpose(result)
return result
Synthesized repair in: 3868ms
Tidyparse (valid/total): 123/225
Original error:
def name(self):
"""Returns description/name string for this driver."""
return force_text(rcapi.get_driver_description(self.ptr)
Good Repair:
def name(self):
"""Returns description/name string for this driver."""
** return force_textrcapi.get_driver_description(self.ptr)
Synthesized repair in: 7477ms
Tidyparse (valid/total): 124/226
Original error:
def _R2deriv(self, R, phi = 0., t = 0.):
if t < self._tform:
smooth = 0.
elif t < self._tsteady:
deltat = t - self._tform
xi = 2. * deltat /(self._tsteady - self._tform) - 1.
smooth = (3. / 16. * xi ** 5. - 5. / 8 * xi ** 3. + 15. / 16. * xi + .5)
else:
smooth = 1.
if R <= self._rb:
return 6. * self._af * smooth * m.cos(2. *(phi - self._omegab * t
Bad Repair: invalid syntax (<unknown>, line 11):
def _R2deriv(self, R, phi = 0., t = 0.):
if t < self._tform:
smooth = 0.
elif t < self._tsteady:
deltat = t - self._tform
xi = 2. * deltat /(self._tsteady - self._tform) - 1.
smooth = (3. / 16. * xi ** 5. - 5. / 8 * xi ** 3. + 15. / 16. * xi + .5)
else:
smooth = 1.
if R <= self._rb:
** return 6. * self._af * smooth * m.cos(2. *)phi - self._omegab * t
Synthesized repair in: 14413ms
Tidyparse (valid/total): 124/227
Original error:
def matches(self, pstate):
"""Requires the dungeon type to have all the needed tags."""
return self.TAGS.issuperset(pstate.elements.get("DUNGEON_TYPE"))) and pstate.rank >= self.MIN_RANK and not self.antagonist_conflicts(pstate)
Good Repair:
def matches(self, pstate):
"""Requires the dungeon type to have all the needed tags."""
** return self.TAGS.issuperset(pstate.elements.get("DUNGEON_TYPE")) and pstate.rank >= self.MIN_RANK and not self.antagonist_conflicts(pstate)
Synthesized repair in: 6310ms
Tidyparse (valid/total): 125/228
Original error:
from __future__ import division
import numpy as np
cimport numpy as np
ctypedef np.float64_t DTYPE_t
ctypedef np.int_t INDEX_t
cdef second_deg_poly_float(np.ndarray[INDEX_t, ndim = 2] rows,
np.ndarray[INDEX_t, ndim = 2] cols,
Bad Repair: invalid syntax (<unknown>, line 3):
from __future__ import division
import numpy as np
cimport numpy as np
ctypedef np.float64_t DTYPE_t
ctypedef np.int_t INDEX_t
** cdef second_deg_poly_floatnp.ndarray[INDEX_t, ndim = 2] rows,
np.ndarray[INDEX_t, ndim = 2] cols,
Synthesized repair in: 14397ms
Tidyparse (valid/total): 125/229
Original error:
def have(name):
return('command not found' not in
sh(name, capture = True, ignore_error = True)
Bad Repair: invalid syntax (<unknown>, line 3):
def have(name):
return('command not found' not in
** shname, capture = True, ignore_error = True)
Synthesized repair in: 7144ms
Tidyparse (valid/total): 125/230
Original error:
def clip(v):
v = mav, 0)
v = min(v, 255)
return v
Bad Repair: invalid syntax (<unknown>, line 2):
** def clip(v:
v = mav, 0)
v = min(v, 255)
return v
Synthesized repair in: 4678ms
Tidyparse (valid/total): 125/231
Original error:
import os as _os
import infra.path_hacks as _path_hacks
_build_scripts_slave = _os.path.abspath(
_os.path.join(_path_hacks.full_infra_path,
_os.pardir, 'build', 'scripts', 'slave')
__path__ = [_build_scripts_slave]
Good Repair:
import os as _os
import infra.path_hacks as _path_hacks
_build_scripts_slave = _os.path.abspath(
** _os.path.join_path_hacks.full_infra_path,
_os.pardir, 'build', 'scripts', 'slave')
__path__ = [_build_scripts_slave]
Synthesized repair in: 3949ms
Tidyparse (valid/total): 126/232
Original error:
def get_best_downloader():
downloaders = (
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
)
viable_downloaders = (dl for dl in downloaders if dl.viable()
return next(viable_downloaders, None)
Bad Repair: invalid syntax (<unknown>, line 9):
def get_best_downloader():
downloaders = (
download_file_powershell,
download_file_curl,
download_file_wget,
download_file_insecure,
)
viable_downloaders = (dl for dl in downloaders if dl.viable()
** return nextviable_downloaders, None)
Synthesized repair in: 24170ms
Tidyparse (valid/total): 126/233
Original error:
def bva_header_file(name, datapoints, eeg_file, event_file):
hdr_file = open('data/' + name + '.vhdr', 'w')
hdr_file.write(
"""Brain Vision Data Exchange Header File Version 2.0""" + name + ".eeg\n"
Good Repair:
def bva_header_file(name, datapoints, eeg_file, event_file):
hdr_file = open('data/' + name + '.vhdr', 'w')
** hdr_file.write
"""Brain Vision Data Exchange Header File Version 2.0""" + name + ".eeg\n"
Synthesized repair in: 14026ms
Tidyparse (valid/total): 127/234
Original error:
def updateBG(self):
if self.config.get("backgroundPath", None):
self.centralwidget.setStyleSheet("QWidget#centralwidget {\n"
Bad Repair: unexpected EOF while parsing (<unknown>, line 3):
def updateBG(self):
if self.config.get("backgroundPath", None):
** self.centralwidget.setStyleSheet("QWidget#centralwidget )\n"
Synthesized repair in: 121617ms
Tidyparse (valid/total): 127/235
Original error:
def file_dict(file):
fin = open(file, 'r')
d = {}
for line in fin:
line = line.rstrip()
cols = line.split()
d[cols[0] = line
fin.close()
return d
Good Repair:
def file_dict(file):
fin = open(file, 'r')
d = {}
for line in fin:
line = line.rstrip()
cols = line.split()
** d[cols0] = line
fin.close()
return d
Synthesized repair in: 98011ms
Tidyparse (valid/total): 128/236
Original error:
def set_module_state(self, state):
set_module_args(dict(
nitro_user = 'user',
nitro_pass = 'pass',
nsip = '1.1.1.1',
state = state,
)))
Good Repair:
def set_module_state(self, state):
set_module_args(dict(
nitro_user = 'user',
nitro_pass = 'pass',
nsip = '1.1.1.1',
state = state,
** ))
Synthesized repair in: 5522ms
Tidyparse (valid/total): 129/237
Original error:
def selu(x, name = 'selu'):
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
return scale * tf.where(x >= 0.0, x, alpha * tf.nn.elu(x)
Good Repair:
def selu(x, name = 'selu'):
alpha = 1.6732632423543772848170429916717
scale = 1.0507009873554804934193349852946
** return scale * tf.where(x >= 0.0, x, alpha * tf.nn.elux)
Synthesized repair in: 8814ms
Tidyparse (valid/total): 130/238
Original error:
def check_dow(dow):
try:
return datetime.datetime.strptime(dow, "%a")
except ValueError:
try:
return datetime.datetime.strptime(dow, r"%A"))
except ValueError:
if dow.is_digit():
return False
else:
return True
Bad Repair: invalid syntax (<unknown>, line 4):
def check_dow(dow):
try:
return datetime.datetime.strptime(dow, "%a")
except ValueError:
try:
** return datetime.datetime.strptime(dow, r"%A")
except ValueError:
if dow.is_digit():
return False
else:
return True
Synthesized repair in: 24204ms
Tidyparse (valid/total): 130/239
Original error:
def test_template_unsafe_clean_data_exception(self, mock_clean_data):
self.assertRaises(AnsibleError,
self.templar.template,
wrap_var('blip bar')))
Good Repair:
def test_template_unsafe_clean_data_exception(self, mock_clean_data):
self.assertRaises(AnsibleError,
self.templar.template,
** wrap_var('blip bar'))
Synthesized repair in: 12069ms
Tidyparse (valid/total): 131/240
Original error:
def get_color(key):
"""color name get from COLOR_MAP dict."""
return COLOR_MAP[PRINT_COLOR_SET[key]
Good Repair:
def get_color(key):
"""color name get from COLOR_MAP dict."""
** return COLOR_MAPPRINT_COLOR_SET[key]
Synthesized repair in: 17104ms
Tidyparse (valid/total): 132/241
Original error:
def get_admin_email(parser, token):
user = users.get_current_user()
if user:
return AdminEmailNode(user.email()
else:
logging.warning("No logged in admin!")
return None
Good Repair:
def get_admin_email(parser, token):
user = users.get_current_user()
if user:
** return AdminEmailNode(user.email)
else:
logging.warning("No logged in admin!")
return None
Synthesized repair in: 10853ms
Tidyparse (valid/total): 133/242
Original error:
def retranslateUi(self, PyCoverageDialog):
_translate = QtCore.QCoreApplication.translate
PyCoverageDialog.setWindowTitle(_translate("PyCoverageDialog", "Python Code Coverage"))
PyCoverageDialog.setWhatsThis(_translate("PyCoverageDialog", "<b>Python Code Coverage</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, PyCoverageDialog):
_translate = QtCore.QCoreApplication.translate
PyCoverageDialog.setWindowTitle(_translate("PyCoverageDialog", "Python Code Coverage"))
** PyCoverageDialog.setWhatsThis(_translate)"PyCoverageDialog", "<b>Python Code Coverage</b>\n"
Synthesized repair in: 188820ms
Tidyparse (valid/total): 133/243
Original error:
def install():
autotools.rawInstall("GETTEXT_PACKAGE=libwnck-1 DESTDIR=%s" % get.installDIR()
pisitools.dodoc("AUTHORS", "ChangeLog", "COPYING")
Bad Repair: invalid syntax (<unknown>, line 3):
def install():
autotools.rawInstall("GETTEXT_PACKAGE=libwnck-1 DESTDIR=%s" % get.installDIR()
** pisitools.dodoc"AUTHORS", "ChangeLog", "COPYING")
Synthesized repair in: 11019ms
Tidyparse (valid/total): 133/244
Original error:
def has_parent(self, parent):
"""Return true if the provided object is a parent of this object."""
return self._ex.has_parent(self.get_id(), parent.get_id()
Good Repair:
def has_parent(self, parent):
"""Return true if the provided object is a parent of this object."""
** return self._ex.has_parent(self.get_id(), parent.get_id)
Synthesized repair in: 13690ms
Tidyparse (valid/total): 134/245
Original error:
def __init__(self, job, hdd):
Task.LoggingTask.__init__(self, job, _("Mount")
self.hdd = hdd
Bad Repair: invalid syntax (<unknown>, line 2):
def __init__(self, job, hdd):
** Task.LoggingTask.__init__(self, job, _"Mount")
self.hdd = hdd
Synthesized repair in: 21524ms
Tidyparse (valid/total): 134/246
Original error:
import os
import sys
dir_path = os.path.dirname(os.path.realpath(__file__)
sys.path.append(dir_path)
Good Repair:
import os
import sys
** dir_path = os.path.dirname(os.path.realpath__file__)
sys.path.append(dir_path)
Synthesized repair in: 2968ms
Tidyparse (valid/total): 135/247
Original error:
def reverse(self, name, backend):
"""Reverses backend URL by name"""
return reverse(name, args = (backend, )
Good Repair:
def reverse(self, name, backend):
"""Reverses backend URL by name"""
** return reverse(name, args = backend, )
Synthesized repair in: 3018ms
Tidyparse (valid/total): 136/248
Original error:
def __init__(self, timeout = scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
self.base_url = kodi.get_setting('%s-base_url' %(self.get_name())
Bad Repair: invalid syntax (<unknown>, line 3):
def __init__(self, timeout = scraper.DEFAULT_TIMEOUT):
self.timeout = timeout
** self.base_url = kodi.get_setting'%s-base_url' %(self.get_name())
Synthesized repair in: 13967ms
Tidyparse (valid/total): 136/249
Original error:
def _get_course_team(self, team_id):
""" Returns course_team object from team_id."""
try:
result = CourseTeam.objects.get(team_id = team_id)
except ObjectDoesNotExist:
raise CommandError(u"Argument{0}is not a course_team team_id".format(team_id)
return result
Bad Repair: invalid syntax (<unknown>, line 6):
def _get_course_team(self, team_id):
""" Returns course_team object from team_id."""
try:
result = CourseTeam.objects.get(team_id = team_id)
except ObjectDoesNotExist:
** raise CommandErroru"Argument{0}is not a course_team team_id".format(team_id)
return result
Synthesized repair in: 140670ms
Tidyparse (valid/total): 136/250
Original error:
def printList(self, sorting_order = 1):
print('[',
if sorting_order > 0:
self.printBackward(self.head)
else:
self.printFoward(self.head)
Bad Repair: invalid syntax (<unknown>, line 3):
def printList(self, sorting_order = 1):
print('[',
if sorting_order > 0:
self.printBackward(self.head)
else:
** self.printFoward]self.head)
Synthesized repair in: 42920ms
Tidyparse (valid/total): 136/251
Original error:
def failTest(self, fullPath, lineNum, message):
stderr.write("\n%s: %d: %s: %s\n" %
(fullPath, lineNum, self.currentTest, message);
Good Repair:
def failTest(self, fullPath, lineNum, message):
stderr.write("\n%s: %d: %s: %s\n" %
** fullPath, lineNum, self.currentTest, message);
Synthesized repair in: 21709ms
Tidyparse (valid/total): 137/252
Original error:
def get_slack_oauth_uri(request):
scope = "bot"
return "https: //slack.com/oauth/authorize?scope=" + scope + "&client_id=" + settings.SLACK_CLIENT_ID + "&redirect_uri=" + request.build_absolute_uri(reverse("converse: slack: oauth")
Bad Repair: invalid syntax (<unknown>, line 3):
def get_slack_oauth_uri(request):
scope = "bot"
** return "https: //slack.com/oauth/authorize?scope=" + scope + "&client_id=" + settings.SLACK_CLIENT_ID + "&redirect_uri=" + request.build_absolute_uri(reverse"converse: slack: oauth")
Synthesized repair in: 7334ms
Tidyparse (valid/total): 137/253
Original error:
def valid_fileproto(uri):
'''Returns a boolean value based on whether or not the URI passed has a valid'''
try:
return bool(re.match('^(?: salt|https?|ftp): //', uri)))
except Exception:
return False
Bad Repair: unmatched ')' (<unknown>, line 4):
def valid_fileproto(uri):
'''Returns a boolean value based on whether or not the URI passed has a valid'''
try:
** return bool(re.match('^(?: salt|https?|ftp: //', uri)))
except Exception:
return False
Synthesized repair in: 15697ms
Tidyparse (valid/total): 137/254
Original error:
class TestLLtype(LLJitMixin):
def test_sieve00(self):
self.run_string(u""";; Use the partner file "streams.rkt" to implement the Sieve of Eratosthenes."""
Bad Repair: invalid syntax (<unknown>, line 3):
class TestLLtype(LLJitMixin):
def test_sieve00(self):
** self.run_stringu""";; Use the partner file "streams.rkt" to implement the Sieve of Eratosthenes."""
Synthesized repair in: 4772ms
Tidyparse (valid/total): 137/255
Original error:
def add_func_stats(target, source):
"""Add together all the stats for two profile entries."""
cc, nc, tt, ct, callers = source
t_cc, t_nc, t_tt, t_ct, t_callers = target
return(cc + t_cc, nc + t_nc, tt + t_tt, ct + t_ct,
add_callers(t_callers, callers)
Good Repair:
def add_func_stats(target, source):
"""Add together all the stats for two profile entries."""
cc, nc, tt, ct, callers = source
t_cc, t_nc, t_tt, t_ct, t_callers = target
return(cc + t_cc, nc + t_nc, tt + t_tt, ct + t_ct,
** add_callerst_callers, callers)
Synthesized repair in: 4084ms
Tidyparse (valid/total): 138/256
Original error:
def test_get_path(self):
directory = realpath(self.repo.path)
expected = realpath(join(self._temp_dir, 'testrepo.git')
self.assertEqual(directory, expected)
Bad Repair: invalid syntax (<unknown>, line 4):
def test_get_path(self):
directory = realpath(self.repo.path)
expected = realpath(join(self._temp_dir, 'testrepo.git')
** self.assertEqualdirectory, expected)
Synthesized repair in: 29938ms
Tidyparse (valid/total): 138/257
Original error:
def _stop(self, signame: str):
print('\ngot signal{} - exiting'.format(signame)
self._loop.stop()
Bad Repair: invalid syntax (<unknown>, line 3):
def _stop(self, signame: str):
print('\ngot signal{} - exiting'.format(signame)
** self._loop.stop)
Synthesized repair in: 9736ms
Tidyparse (valid/total): 138/258
Original error:
def fileFrames(theFile, title, anchor):
"""Write to a file the frameset to hold a table of contents."""
print("""<html>""" %{
'title': title,
'anchor': anchor
}
Bad Repair: invalid syntax (<unknown>, line 3):
def fileFrames(theFile, title, anchor):
"""Write to a file the frameset to hold a table of contents."""
** print"""<html>""" %{
'title': title,
'anchor': anchor
}
Synthesized repair in: 4869ms
Tidyparse (valid/total): 138/259
Original error:
class O3_ARM_v7a_Complex_Int(FUDesc):
opList = [OpDesc(opClass = 'IntMult', opLat = 3, pipelined = True),
count = 1
Good Repair:
class O3_ARM_v7a_Complex_Int(FUDesc):
** opList = OpDesc(opClass = 'IntMult', opLat = 3, pipelined = True),
count = 1
Synthesized repair in: 4405ms
Tidyparse (valid/total): 139/260
Original error:
'''Unique version information place'''
__version__ = '0.1.0'
VERSION = tuple(int(x) for x in __version__.split('.')
Bad Repair: invalid syntax (<unknown>, line 3):
'''Unique version information place'''
__version__ = '0.1.0'
** VERSION = tuple(int(x) for x in __version__.split'.')
Synthesized repair in: 3302ms
Tidyparse (valid/total): 139/261
Original error:
def push_connection(connection):
"""Pushes the given connection on the stack"""
_connection_stack.push(patch_connection(connection)
Good Repair:
def push_connection(connection):
"""Pushes the given connection on the stack"""
** _connection_stack.pushpatch_connection(connection)
Synthesized repair in: 3619ms
Tidyparse (valid/total): 140/262
Original error:
class HorizRadioRenderer(RadioSelect.renderer):
def render(self):
return mark_safe('\n'.join(['%s\n' % w for w in self])
Bad Repair: invalid syntax (<unknown>, line 3):
class HorizRadioRenderer(RadioSelect.renderer):
def render(self):
** return mark_safe('\n'.join['%s\n' % w for w in self])
Synthesized repair in: 24276ms
Tidyparse (valid/total): 140/263
Original error:
def to_html(self, docstring_linker, ** options):
if options.get('verbatim', self._verbatim) == 0:
return plaintext_to_html(self.to_plaintext(docstring_linker)
else:
return ParsedDocstring.to_html(self, docstring_linker, ** options)
Bad Repair: invalid syntax (<unknown>, line 4):
def to_html(self, docstring_linker, ** options):
if options.get('verbatim', self._verbatim) == 0:
return plaintext_to_html(self.to_plaintext(docstring_linker)
else:
** return ParsedDocstring.to_htmlself, docstring_linker, ** options)
Synthesized repair in: 46817ms
Tidyparse (valid/total): 140/264
Original error:
def angle(val):
'''calculate the pwm for requested angle'''
return int(round(servo_min +(90.0 - val) *(servo_max - servo_min) / 180.0)
Good Repair:
def angle(val):
'''calculate the pwm for requested angle'''
** return int(round(servo_min +90.0 - val) *(servo_max - servo_min) / 180.0)
Synthesized repair in: 32947ms
Tidyparse (valid/total): 141/265
Original error:
def __init__(self):
""" Publishers and Subscribers """
self.location = rospy.Publisher('location/location',
rospy.init_node('location')
rospy.Subscriber('/cam0/tags', TagPoseArray, self.__aprilCallback)
rospy.Subscriber('/ardrone/navdata', Navdata, self.__navdataCallback)
self.location_x = 0.0
self.location_y = 0.0
self.location_z = 0.0
self.location_w = 0.0
self.velocity_x = 0.0
self.velocity_y = 0.0
self.delta_time = 0.0
self.pixel_ratio = 0.0
self.tag_tally = 0
self.stationary = 0
Bad Repair: invalid syntax (<unknown>, line 5):
def __init__(self):
""" Publishers and Subscribers """
self.location = rospy.Publisher('location/location',
rospy.init_node('location')
** rospy.Subscriber'/cam0/tags', TagPoseArray, self.__aprilCallback)
rospy.Subscriber('/ardrone/navdata', Navdata, self.__navdataCallback)
self.location_x = 0.0
self.location_y = 0.0
self.location_z = 0.0
self.location_w = 0.0
self.velocity_x = 0.0
self.velocity_y = 0.0
self.delta_time = 0.0
self.pixel_ratio = 0.0
self.tag_tally = 0
self.stationary = 0
Synthesized repair in: 10388ms
Tidyparse (valid/total): 141/266
Original error:
def error(msg, newline = True):
print('\033[31m' + msg + '\033[0m',
if newline:
print
Bad Repair: invalid syntax (<unknown>, line 3):
def error(msg, newline = True):
** print('\033[31m' + msg + '\033])0m',
if newline:
print
Synthesized repair in: 85361ms
Tidyparse (valid/total): 141/267
Original error:
def _callable_postfix(self, val, word):
if hasattr(val '__call__'):
word = word + "("
return word
Bad Repair: invalid syntax (<unknown>, line 2):
def _callable_postfix(self, val, word):
if hasattr(val '__call__'):
** word = word + ""
return word
Synthesized repair in: 24879ms
Tidyparse (valid/total): 141/268
Original error:
import testing
setup = testing.setup_mesh_source_test("Newell")
setup.source.type = "teacup"
testing.require_valid_mesh(setup.document, setup.source.get_property("output_mesh")
testing.require_similar_mesh(setup.document, setup.source.get_property("output_mesh"), "mesh.source.Newell.teacup", 1)
Bad Repair: invalid syntax (<unknown>, line 5):
import testing
setup = testing.setup_mesh_source_test("Newell")
setup.source.type = "teacup"
testing.require_valid_mesh(setup.document, setup.source.get_property("output_mesh")
** testing.require_similar_meshsetup.document, setup.source.get_property("output_mesh"), "mesh.source.Newell.teacup", 1)
Synthesized repair in: 36955ms
Tidyparse (valid/total): 141/269
Original error:
def getCalibrationData(self, index):
"""Request the 12 calibration bytes from a sensor at a specified index."""
return list(self.dev.ctrl_transfer(0x40 | 0x80, 0x6C, index % 5, index / 5, 8)
Good Repair:
def getCalibrationData(self, index):
"""Request the 12 calibration bytes from a sensor at a specified index."""
** return listself.dev.ctrl_transfer(0x40 | 0x80, 0x6C, index % 5, index / 5, 8)
Synthesized repair in: 10925ms
Tidyparse (valid/total): 142/270
Original error:
def b58encode_chk(v):
"""b58encode a string, with 32-bit checksum"""
return b58encode(v + checksum(v)
Good Repair:
def b58encode_chk(v):
"""b58encode a string, with 32-bit checksum"""
** return b58encodev + checksum(v)
Synthesized repair in: 7236ms
Tidyparse (valid/total): 143/271
Original error:
def append_file(self, relpath, f, mode = None):
"""See `bzrlib.transport.Transport`."""
return extract_result(
self._async_transport.append_file(relpath, f, mode)
Good Repair:
def append_file(self, relpath, f, mode = None):
"""See `bzrlib.transport.Transport`."""
return extract_result(
** self._async_transport.append_filerelpath, f, mode)
Synthesized repair in: 2799ms
Tidyparse (valid/total): 144/272
Original error:
class Bugger(object):
template_strings = {
'detailed': """Summary: ${Summary}"""
Bad Repair: invalid syntax (<unknown>, line 2):
class Bugger(object):
** template_strings =
'detailed': """Summary: ${Summary}"""
Synthesized repair in: 9788ms
Tidyparse (valid/total): 144/273
Original error:
def _remove_dups(self, b_list):
b_list = list(set(b_list)
return b_list
Good Repair:
def _remove_dups(self, b_list):
** b_list = listset(b_list)
return b_list
Synthesized repair in: 3154ms
Tidyparse (valid/total): 145/274
Original error:
def _asdict(self):
'Return a new dict which maps field names to their values'
return dict(zip(self._fields, self)
Good Repair:
def _asdict(self):
'Return a new dict which maps field names to their values'
** return dictzip(self._fields, self)
Synthesized repair in: 9294ms
Tidyparse (valid/total): 146/275
Original error:
def test_getFacility_With_Name_Returns_A_FacilityInfo_Object(self):
facility = config.getFacility("ISIS")
self.assertTrue(isinstance(facility, FacilityInfo)
self.assertRaises(RuntimeError, config.getFacility, "MadeUpFacility")
Good Repair:
def test_getFacility_With_Name_Returns_A_FacilityInfo_Object(self):
facility = config.getFacility("ISIS")
** self.assertTrue(isinstancefacility, FacilityInfo)
self.assertRaises(RuntimeError, config.getFacility, "MadeUpFacility")
Synthesized repair in: 49291ms
Tidyparse (valid/total): 147/276
Original error:
def get_execreqs(self, agent_uuid):
name = self.agent_name(agent_uuid)
pkg = UnpackedPackage(os.path.join(self.install_dir, agent_uuid, name)
return self._read_execreqs(pkg.distinfo)
Bad Repair: invalid syntax (<unknown>, line 4):
def get_execreqs(self, agent_uuid):
name = self.agent_name(agent_uuid)
pkg = UnpackedPackage(os.path.join(self.install_dir, agent_uuid, name)
** return self._read_execreqspkg.distinfo)
Synthesized repair in: 9099ms
Tidyparse (valid/total): 147/277
Original error:
def test_center_containing_ul(self):
"""center tag containing block-type elements"""
html = '<html xmlns="http://www.w3.org/1999/xhtml"><center>Test1<ul><li>Test2</li></ul>Test3</center></html>'
odt = xhtml2odt(html)
self.assertEquals(odt, """<text:p text:style-name="center">Test1</text:p>"""
Good Repair:
def test_center_containing_ul(self):
"""center tag containing block-type elements"""
html = '<html xmlns="http://www.w3.org/1999/xhtml"><center>Test1<ul><li>Test2</li></ul>Test3</center></html>'
odt = xhtml2odt(html)
** self.assertEqualsodt, """<text:p text:style-name="center">Test1</text:p>"""
Synthesized repair in: 21179ms
Tidyparse (valid/total): 148/278
Original error:
class scholenAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['NAAM_VOLLEDIG', 'NAAM_STRAAT_VEST', 'NR_HUIS_VEST', 'POSTCODE_VEST', 'NAAM_PLAATS_VEST', 'GEMEENTENAAM', 'PROVINCIE_VEST', 'INTERNET', 'NR_TELEFOON', 'NR_FAX', 'BRIN_NUMMER'
Bad Repair: invalid syntax (<unknown>, line 3):
class scholenAdmin(admin.ModelAdmin):
fieldsets = [
** (None, )'fields': ]'NAAM_VOLLEDIG', 'NAAM_STRAAT_VEST', 'NR_HUIS_VEST', 'POSTCODE_VEST', 'NAAM_PLAATS_VEST', 'GEMEENTENAAM', 'PROVINCIE_VEST', 'INTERNET', 'NR_TELEFOON', 'NR_FAX', 'BRIN_NUMMER'
Synthesized repair in: 227990ms
Tidyparse (valid/total): 148/279
Original error:
def create_position_at_angle_horizontally(distance, angle):
'''Rotates client position around listener horizontally.'''
rad_angle = math.radians(angle)
pos = (distance * math.cos(rad_angle), 0, distance * math.sin(rad_angle)
return pos
Good Repair:
def create_position_at_angle_horizontally(distance, angle):
'''Rotates client position around listener horizontally.'''
rad_angle = math.radians(angle)
** pos = (distance * math.cosrad_angle), 0, distance * math.sin(rad_angle)
return pos
Synthesized repair in: 11570ms
Tidyparse (valid/total): 149/280
Original error:
def print_releases(repository):
"""Report the identifiers of all known releases of the given repository to standard output."""
print('\n'.join(release.identifier for release in repository.ordered_releases)))
Bad Repair: invalid syntax (<unknown>, line 3):
** def print_releases(repository:
"""Report the identifiers of all known releases of the given repository to standard output."""
print('\n'.join(release.identifier for release in repository.ordered_releases)))
Synthesized repair in: 8946ms
Tidyparse (valid/total): 149/281
Original error:
def delete_security_group_rule(self, group_rule_id):
"""Deletes the provided Security Group rule."""
return self.delete('os-security-group-rules/%s' % str(group_rule_id)
Bad Repair: invalid syntax (<unknown>, line 3):
def delete_security_group_rule(self, group_rule_id):
"""Deletes the provided Security Group rule."""
** return self.delete'os-security-group-rules/%s' % str(group_rule_id)
Synthesized repair in: 16197ms
Tidyparse (valid/total): 149/282
Original error:
__author__ = 'philipp'
import unittest, sys, os
sys.path.append(os.path.join(os.path.abspath('..'), 'service')))
from sqs import SQS
Good Repair:
__author__ = 'philipp'
import unittest, sys, os
** sys.path.append(os.path.join(os.path.abspath('..'), 'service'))
from sqs import SQS
Synthesized repair in: 3443ms
Tidyparse (valid/total): 150/283
Original error:
def test_ToGS1(self):
print("***==== Test GS1 ====***"
epc = self._giai96.encode(self._companyPrefix, None, self._itemRef, self._filter, None)
print(epc.toGS1())
print("***==== END Test To GS1 ====***"
print(""
Bad Repair: invalid syntax (<unknown>, line 3):
def test_ToGS1(self):
print("***==== Test GS1 ====***"
** epc = self._giai96.encodeself._companyPrefix, None, self._itemRef, self._filter, None)
print(epc.toGS1())
print("***==== END Test To GS1 ====***"
** print)""
Synthesized repair in: 379336ms
Tidyparse (valid/total): 150/284
Original error:
def retranslateUi(self, CWndMainDBEdit):
CWndMainDBEdit.setWindowTitle(_translate("CWndMainDBEdit", "Edicão da Base de Dados", None))
self.lbl_lin_1.setText(_translate("CWndMainDBEdit", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, CWndMainDBEdit):
CWndMainDBEdit.setWindowTitle(_translate("CWndMainDBEdit", "Edicão da Base de Dados", None))
** self.lbl_lin_1.setText(_translate)"CWndMainDBEdit", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 283290ms
Tidyparse (valid/total): 150/285
Original error:
def normalized_dope(atmsel):
"""Returns the normalized DOPE score of the given model."""
mdl = atmsel.get_model()
return('Normalized DOPE score', mdl.assess_normalized_dope()
Good Repair:
def normalized_dope(atmsel):
"""Returns the normalized DOPE score of the given model."""
mdl = atmsel.get_model()
** return'Normalized DOPE score', mdl.assess_normalized_dope()
Synthesized repair in: 13952ms
Tidyparse (valid/total): 151/286
Original error:
def printcn(suni):
for i in uni:
print(uni.encode('utf-8')
Good Repair:
def printcn(suni):
for i in uni:
** printuni.encode('utf-8')
Synthesized repair in: 24592ms
Tidyparse (valid/total): 152/287
Original error:
import os
basedir = os.path.abspath(os.path.dirname(__file__)))
DEBUG = True
USERNAME = 'admin'
PASSWORD = 'admin'
CSRF_ENABLED = True
SECRET_KEY = 'my precious'
SQLALCHEMY_DATABASE_URI = 'sqlite: ///' + os.path.join(basedir, 'database.db')
Good Repair:
import os
** basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
USERNAME = 'admin'
PASSWORD = 'admin'
CSRF_ENABLED = True
SECRET_KEY = 'my precious'
SQLALCHEMY_DATABASE_URI = 'sqlite: ///' + os.path.join(basedir, 'database.db')
Synthesized repair in: 15990ms
Tidyparse (valid/total): 153/288
Original error:
def process_queue(session_handle, save_path, db, magnet_statuses):
dbc = db.execute("""SELECT""", {
'status_id_start_watching': magnet_statuses['start watching']
Bad Repair: illegal target for annotation (<unknown>, line 3):
def process_queue(session_handle, save_path, db, magnet_statuses):
** dbc = db.execute("""SELECT""", )
'status_id_start_watching': magnet_statuses['start watching']
Synthesized repair in: 26203ms
Tidyparse (valid/total): 153/289
Original error:
def login(username, password, version):
login_data = {
'username': username,
'password': password,
'submit': 'login',
'version': version
}
r = requests.post(BASE_URL + 'command/login/'
Good Repair:
def login(username, password, version):
login_data = {
'username': username,
'password': password,
'submit': 'login',
'version': version
}
** r = requests.postBASE_URL + 'command/login/'
Synthesized repair in: 32256ms
Tidyparse (valid/total): 154/290
Original error:
def value(self, value):
if isinstance(value, (six.string_types, six.integer_types, float, bool):
self._value = value
Good Repair:
def value(self, value):
** if isinstance(value, six.string_types, six.integer_types, float, bool):
self._value = value
Synthesized repair in: 3714ms
Tidyparse (valid/total): 155/291
Original error:
def zrem(self, * values):
"""Remove the values from the SortedSet"""
return self.db.zrem(self.key, * _parse_values(values)
Good Repair:
def zrem(self, * values):
"""Remove the values from the SortedSet"""
** return self.db.zremself.key, * _parse_values(values)
Synthesized repair in: 13500ms
Tidyparse (valid/total): 156/292
Original error:
def get_transaction(self, transaction_id):
'''returns a specific transaction resource'''
return self.get("transactions/%s" % int(transaction_id)
Good Repair:
def get_transaction(self, transaction_id):
'''returns a specific transaction resource'''
** return self.get("transactions/%s" % inttransaction_id)
Synthesized repair in: 4239ms
Tidyparse (valid/total): 157/293
Original error:
def testRaisesOnNonJNIMethod(self):
test_data = """class MyInnerClass {"""
self.assertRaises(SyntaxError,
,
jni_generator.JNIFromJavaSource,
test_data, 'foo/bar', TestOptions())
Bad Repair: invalid syntax (<unknown>, line 4):
def testRaisesOnNonJNIMethod(self):
** test_data = """class MyInnerClass """
self.assertRaises(SyntaxError,
,
jni_generator.JNIFromJavaSource,
test_data, 'foo/bar', TestOptions())
Synthesized repair in: 27152ms
Tidyparse (valid/total): 157/294
Original error:
class DrillUpButton(CommonObject):
ALLOWED_OPTIONS = {
"position": (Position, dict),
"relativeTo": basestring,
"theme": NotImplemented
Bad Repair: invalid syntax (<unknown>, line 2):
class DrillUpButton(CommonObject):
** ALLOWED_OPTIONS =
"position": (Position, dict),
"relativeTo": basestring,
"theme": NotImplemented
Synthesized repair in: 15771ms
Tidyparse (valid/total): 157/295
Original error:
def _get_object(self, headers = None, expect_statuses = (2, ))):
return self.int_client.get_object(self.account,
self.container_name,
self.object_name,
headers,
acceptable_statuses = expect_statuses)
Good Repair:
** def _get_object(self, headers = None, expect_statuses = (2, )):
return self.int_client.get_object(self.account,
self.container_name,
self.object_name,
headers,
acceptable_statuses = expect_statuses)
Synthesized repair in: 10125ms
Tidyparse (valid/total): 158/296
Original error:
def retranslateUi(self, scriptEditor):
scriptEditor.setWindowTitle(QtGui.QApplication.translate("scriptEditor", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.executeAll_btn.setToolTip(QtGui.QApplication.translate("scriptEditor", "Execute all code in current tab\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, scriptEditor):
scriptEditor.setWindowTitle(QtGui.QApplication.translate("scriptEditor", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
** self.executeAll_btn.setToolTip(QtGui.QApplication.translate)"scriptEditor", "Execute all code in current tab\n"
Synthesized repair in: 80414ms
Tidyparse (valid/total): 158/297
Original error:
def build(self):
env = ConfigureEnvironment(self.deps_cpp_info, self.settings)
configure = "cd %s/libcutl-1.10.0 && %s./configure --prefix=%s/install" %(self.conanfile_directory, env.command_line, self.conanfile_directory)
self.output.warn(configure)
self.run(configure)
self.run("cd %s/libcutl-1.10.0 && %s make install" %(self.conanfile_directory, env.command_line)
Good Repair:
def build(self):
env = ConfigureEnvironment(self.deps_cpp_info, self.settings)
configure = "cd %s/libcutl-1.10.0 && %s./configure --prefix=%s/install" %(self.conanfile_directory, env.command_line, self.conanfile_directory)
self.output.warn(configure)
self.run(configure)
** self.run("cd %s/libcutl-1.10.0 && %s make install" %self.conanfile_directory, env.command_line)
Synthesized repair in: 386695ms
Tidyparse (valid/total): 159/298
Original error:
def get_template(self, template_name, dirs):
"""Sets up an environment and Gets jinja template."""
jinja_environment = jinja2.Environment(
loader = jinja2.FileSystemLoader(dirs +[os.path.dirname(__file__)])
return jinja_environment.get_template(template_name)
Bad Repair: unexpected indent (<unknown>, line 4):
def get_template(self, template_name, dirs):
"""Sets up an environment and Gets jinja template."""
** jinja_environment = jinja2.Environment
loader = jinja2.FileSystemLoader(dirs +[os.path.dirname(__file__)])
return jinja_environment.get_template(template_name)
Synthesized repair in: 87224ms
Tidyparse (valid/total): 159/299
Original error:
def abspath(self, p):
"""Turn P into an absolute path.Relative paths are taken relative"""
return os.path.abspath(os.path.join(self.base, p)
Good Repair:
def abspath(self, p):
"""Turn P into an absolute path.Relative paths are taken relative"""
** return os.path.abspathos.path.join(self.base, p)
Synthesized repair in: 8480ms
Tidyparse (valid/total): 160/300
Original error:
def FormatItem(key, value):
sqlstr = ""
if isinstance(value, Number):
sqlstr = " `%s`=%s " %(key, value)
else:
sqlstr = " `%s`='%s' " %(key, value.replace("'", "\\'")
return sqlstr
Bad Repair: invalid syntax (<unknown>, line 6):
def FormatItem(key, value):
sqlstr = ""
if isinstance(value, Number):
sqlstr = " `%s`=%s " %(key, value)
else:
** sqlstr = " `%s`='%s' " %(key, value.replace"'", "\\'")
return sqlstr
Synthesized repair in: 113242ms
Tidyparse (valid/total): 160/301
Original error:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls))),
]
Good Repair:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
** url(r'^admin/', include(admin.site.urls)),
]
Synthesized repair in: 13028ms
Tidyparse (valid/total): 161/302
Original error:
def generate_scenarios(cls):
cls.scenarios = (
testscenarios.multiply_scenarios(cls._call_vs_cast,
cls._cap_scenarios)))
Good Repair:
def generate_scenarios(cls):
cls.scenarios = (
testscenarios.multiply_scenarios(cls._call_vs_cast,
** cls._cap_scenarios))
Synthesized repair in: 3390ms
Tidyparse (valid/total): 162/303
Original error:
def __addr_list(msg, header):
return[addr for name, addr in
email.Utils.getaddresses(msg.get_all(header, [])]
Good Repair:
def __addr_list(msg, header):
return[addr for name, addr in
** email.Utils.getaddressesmsg.get_all(header, [])]
Synthesized repair in: 18176ms
Tidyparse (valid/total): 163/304
Original error:
def flatten_one_liner(lst):
"""A one-liner nested lists flattener."""
return list(itertools.chain.from_iterable(lst)
Good Repair:
def flatten_one_liner(lst):
"""A one-liner nested lists flattener."""
** return list(itertools.chain.from_iterablelst)
Synthesized repair in: 14319ms
Tidyparse (valid/total): 164/305
Original error:
def from_json(cls, json_string):
"""Create a Circuit from a JSON-serialized string."""
return cls.from_jsonifiable(json.loads(json_string)
Good Repair:
def from_json(cls, json_string):
"""Create a Circuit from a JSON-serialized string."""
** return cls.from_jsonifiablejson.loads(json_string)
Synthesized repair in: 6950ms
Tidyparse (valid/total): 165/306
Original error:
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
suite.addTest(makeSuite(LinuxParsersTestCase)
return suite
Good Repair:
def test_suite():
from unittest import TestSuite, makeSuite
suite = TestSuite()
** suite.addTest(makeSuiteLinuxParsersTestCase)
return suite
Synthesized repair in: 15757ms
Tidyparse (valid/total): 166/307
Original error:
def __init__(self, player_party, other_party):
self._state = - 1
self._pp = player_party
self._pp_turns = [Turn(self, i for i in self._pp.chars]
self._ep = other_party
self._ep_turns = [Turn(self, i for i in self._ep.chars]
Bad Repair: invalid syntax (<unknown>, line 5):
def __init__(self, player_party, other_party):
self._state = - 1
self._pp = player_party
** self._pp_turns = [Turn
** self, i for i in self._pp.chars]
** self._ep = other_party
** self._ep_turns = [Turnself, i for i in self._ep.chars]
Synthesized repair in: 306073ms
Tidyparse (valid/total): 166/308
Original error:
def uid(player):
"""returns the player's UUID"""
return str(player.getUniqueId()))
Good Repair:
def uid(player):
"""returns the player's UUID"""
** return str(player.getUniqueId())
Synthesized repair in: 4153ms
Tidyparse (valid/total): 167/309
Original error:
def _weibull_model(t, A = 1., B = 1.):
"""Weibull model to compute the concentration."""
t = t / 60.
s_t = A * t * np.exp(np.power(- t, B)
return s_t
Good Repair:
def _weibull_model(t, A = 1., B = 1.):
"""Weibull model to compute the concentration."""
t = t / 60.
** s_t = A * t * np.exp(np.power- t, B)
return s_t
Synthesized repair in: 8268ms
Tidyparse (valid/total): 168/310
Original error:
def print_board(board):
for row in board:
print(" ".join(row)
Bad Repair: invalid syntax (<unknown>, line 3):
def print_board(board):
for row in board:
** print" ".join(row)
Synthesized repair in: 3039ms
Tidyparse (valid/total): 168/311
Original error:
def _get_supported_dtypes(self):
types = set(mdp.utils.get_dtypes('All'))
for node in self._flow:
types = types.intersection(node.get_supported_dtypes()
return list(types)
Good Repair:
def _get_supported_dtypes(self):
types = set(mdp.utils.get_dtypes('All'))
for node in self._flow:
** types = types.intersectionnode.get_supported_dtypes()
return list(types)
Synthesized repair in: 37890ms
Tidyparse (valid/total): 169/312
Original error:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings")
from scrapy.cmdline import execute
execute("scrapy crawl article_spider2 -a id=1 -a do_action=yes".split()))
Good Repair:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings")
from scrapy.cmdline import execute
** execute("scrapy crawl article_spider2 -a id=1 -a do_action=yes".split())
Synthesized repair in: 10048ms
Tidyparse (valid/total): 170/313
Original error:
import os
import unittest
import shutil
from doppel import mkdir, makedirs
this_dir = os.path.abspath(os.path.dirname(__file__)
test_stage_dir = os.path.join(this_dir, '..', 'stage')
Good Repair:
import os
import unittest
import shutil
from doppel import mkdir, makedirs
** this_dir = os.path.abspathos.path.dirname(__file__)
test_stage_dir = os.path.join(this_dir, '..', 'stage')
Synthesized repair in: 7480ms
Tidyparse (valid/total): 171/314
Original error:
def _parse_file(self, data_file):
""" Each module adding a file support must extends this method.It processes the file if it can, returns super otherwise, resulting in a chain of responsability."""
raise UserError(_('Could not make sense of the given file.\nDid you install the module to support this type of file ?')
Bad Repair: invalid syntax (<unknown>, line 3):
def _parse_file(self, data_file):
""" Each module adding a file support must extends this method.It processes the file if it can, returns super otherwise, resulting in a chain of responsability."""
** raise UserError(_'Could not make sense of the given file.\nDid you install the module to support this type of file ?')
Synthesized repair in: 7103ms
Tidyparse (valid/total): 171/315
Original error:
def test_config_check_success(self):
'''Test that a 0-config passes'''
proc = test_base.TimeoutRunner([
self.binary,
"--config_check",
"--database_path=%s" %(self.dbpath),
"--config_path=%s/test.config" % test_base.SCRIPT_DIR
Bad Repair: unexpected indent (<unknown>, line 4):
def test_config_check_success(self):
'''Test that a 0-config passes'''
** proc = test_base.TimeoutRunner()
self.binary,
"--config_check",
"--database_path=%s" %(self.dbpath),
"--config_path=%s/test.config" % test_base.SCRIPT_DIR
Synthesized repair in: 11027ms
Tidyparse (valid/total): 171/316
Original error:
def list_containers(self):
"""Return a list of containers."""
return list(self.iterate_containers()))
Good Repair:
def list_containers(self):
"""Return a list of containers."""
** return list(self.iterate_containers())
Synthesized repair in: 3289ms
Tidyparse (valid/total): 172/317
Original error:
def test_secure():
from vishnu.backend import Redis
from vishnu.session import Config
default = Config(secret = SECRET, backend = Redis())
assert default.secure == True
custom_true = Config(secret = SECRET, secure = True, backend = Redis()
assert custom_true.secure == True
custom_false = Config(secret = SECRET, secure = False, backend = Redis())
assert custom_false.secure == False
Bad Repair: invalid syntax (<unknown>, line 7):
def test_secure():
from vishnu.backend import Redis
from vishnu.session import Config
default = Config(secret = SECRET, backend = Redis())
assert default.secure == True
custom_true = Config(secret = SECRET, secure = True, backend = Redis()
assert custom_true.secure == True
** custom_false = Configsecret = SECRET, secure = False, backend = Redis())
assert custom_false.secure == False
Synthesized repair in: 17013ms
Tidyparse (valid/total): 172/318
Original error:
import urllib
print(urllib.urlencode({"sel_ciklus": "POVIJEST ÈETVRTKOM"})))
Good Repair:
import urllib
** print(urllib.urlencode({"sel_ciklus": "POVIJEST ÈETVRTKOM"}))
Synthesized repair in: 10882ms
Tidyparse (valid/total): 173/319
Original error:
def odom_callback(self, msg):
self.x0 = msg.pose.pose.position.x
self.y0 = msg.pose.pose.position.y
_, _, self.yaw0 = euler_from_quaternion((msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w)))
self.odom_received = True
Good Repair:
def odom_callback(self, msg):
self.x0 = msg.pose.pose.position.x
self.y0 = msg.pose.pose.position.y
** _, _, self.yaw0 = euler_from_quaternion((msg.pose.pose.orientation.x, msg.pose.pose.orientation.y, msg.pose.pose.orientation.z, msg.pose.pose.orientation.w))
self.odom_received = True
Synthesized repair in: 8575ms
Tidyparse (valid/total): 174/320
Original error:
def main():
try:
loop(server(('127.0.0.1', 25000))
except KeyboardInterrupt:
pass
Good Repair:
def main():
try:
** loop(server('127.0.0.1', 25000))
except KeyboardInterrupt:
pass
Synthesized repair in: 3187ms
Tidyparse (valid/total): 175/321
Original error:
def get_thread_id():
"""Returs id for current thread."""
return(os.getpid(), _thread.get_ident()
Good Repair:
def get_thread_id():
"""Returs id for current thread."""
** return(os.getpid(), _thread.get_ident)
Synthesized repair in: 5550ms
Tidyparse (valid/total): 176/322
Original error:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension = ZopeTransactionExtension())
Base = declarative_base()
Bad Repair: invalid syntax (<unknown>, line 5):
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension = ZopeTransactionExtension())
** Base = declarative_base)
Synthesized repair in: 3693ms
Tidyparse (valid/total): 176/323
Original error:
def echo_map(m):
print(MAP_FILE_TEMPLATE %{
'cmd': ' '.join(sys.argv),
'json': json.dumps(m, indent = 2, sort_keys = True),
}
Good Repair:
def echo_map(m):
** printMAP_FILE_TEMPLATE %{
'cmd': ' '.join(sys.argv),
'json': json.dumps(m, indent = 2, sort_keys = True),
}
Synthesized repair in: 76010ms
Tidyparse (valid/total): 177/324
Original error:
def retranslateUi(self, SvnTagDialog):
_translate = QtCore.QCoreApplication.translate
SvnTagDialog.setWindowTitle(_translate("SvnTagDialog", "Subversion Tag"))
self.tagCombo.setToolTip(_translate("SvnTagDialog", "Enter the name of the tag"))
self.tagCombo.setWhatsThis(_translate("SvnTagDialog", "<b>Tag Name</b>\n"
Bad Repair: invalid syntax (<unknown>, line 5):
def retranslateUi(self, SvnTagDialog):
_translate = QtCore.QCoreApplication.translate
SvnTagDialog.setWindowTitle(_translate("SvnTagDialog", "Subversion Tag"))
self.tagCombo.setToolTip(_translate("SvnTagDialog", "Enter the name of the tag"))
** self.tagCombo.setWhatsThis(_translate)"SvnTagDialog", "<b>Tag Name</b>\n"
Synthesized repair in: 954736ms
Tidyparse (valid/total): 177/325
Original error:
def test_empty_file(tmpdir):
"""Test invocation with an empty file."""
gjtk.cli.main(argv = [str(tmpdir.join('empty')])
Good Repair:
def test_empty_file(tmpdir):
"""Test invocation with an empty file."""
** gjtk.cli.main(argv = [strtmpdir.join('empty')])
Synthesized repair in: 56665ms
Tidyparse (valid/total): 178/326
Original error:
class TestApplication(unittest.TestCase):
def test_application(self):
contact = PlusContact(first_name = 'kate', last_name = 'smith', email
Bad Repair: cannot assign to literal (<unknown>, line 3):
class TestApplication(unittest.TestCase):
def test_application(self):
** contact = PlusContactfirst_name = 'kate', last_name = 'smith', email
Synthesized repair in: 28996ms
Tidyparse (valid/total): 178/327
Original error:
def print_title(width):
free_space = width -(len(TITLE) + 2)
to_left = free_space / 2
if free_space % 2 == 0:
to_right = to_left
else:
to_right = to_left - 1
print("%s %s %s" %("#" * to_left, TITLE, "#" * to_right)
Bad Repair: invalid syntax (<unknown>, line 8):
def print_title(width):
free_space = width -(len(TITLE) + 2)
to_left = free_space / 2
if free_space % 2 == 0:
to_right = to_left
else:
to_right = to_left - 1
** print"%s %s %s" %("#" * to_left, TITLE, "#" * to_right)
Synthesized repair in: 12511ms
Tidyparse (valid/total): 178/328
Original error:
def get_csrf_token(self, res):
input = res.html.find('input', dict(name = 'csrf_token')))
self.assert_(input)
return input['value']
Good Repair:
def get_csrf_token(self, res):
** input = res.html.find('input', dict(name = 'csrf_token'))
self.assert_(input)
return input['value']
Synthesized repair in: 41683ms
Tidyparse (valid/total): 179/329
Original error:
def main():
import googlecloudsdk.gcloud_main
sys.exit(googlecloudsdk.gcloud_main.main()))
Good Repair:
def main():
import googlecloudsdk.gcloud_main
** sys.exit(googlecloudsdk.gcloud_main.main())
Synthesized repair in: 14141ms
Tidyparse (valid/total): 180/330
Original error:
def check(self, value):
'''Check whether provided value is a list'''
return isinstance(value, (list, tuple)
Good Repair:
def check(self, value):
'''Check whether provided value is a list'''
** return isinstance(value, list, tuple)
Synthesized repair in: 3384ms
Tidyparse (valid/total): 181/331
Original error:
def partitionDisks(self, data):
"""Performs automatic disks partitioning basing on"""
return self.session.request('rollback/partition', 'POST',
self.getXML(data, 'partitionRequest')
Bad Repair: invalid syntax (<unknown>, line 3):
def partitionDisks(self, data):
"""Performs automatic disks partitioning basing on"""
** return self.session.request'rollback/partition', 'POST',
self.getXML(data, 'partitionRequest')
Synthesized repair in: 4942ms
Tidyparse (valid/total): 181/332
Original error:
def write_tsv(output_stream, * tup, ** kwargs):
"""Write argument list in `tup` out as a tab-separeated row to the stream."""
encoding = kwargs.get('encoding') or 'utf-8'
value = '\t'.join([s for s in tup]) + '\n'
output_stream.write(value.encode(encoding)))
Bad Repair: invalid syntax (<unknown>, line 5):
def write_tsv(output_stream, * tup, ** kwargs):
"""Write argument list in `tup` out as a tab-separeated row to the stream."""
encoding = kwargs.get('encoding') or 'utf-8'
** value = '\t'.join([s for s in tup] + '\n'
output_stream.write(value.encode(encoding)))
Synthesized repair in: 32922ms
Tidyparse (valid/total): 181/333
Original error:
def motorRampUp(self):
for i in range(o, 600, 10):
wiringpi.pwmWrite(18, i
Good Repair:
def motorRampUp(self):
for i in range(o, 600, 10):
** wiringpi.pwmWrite18, i
Synthesized repair in: 4527ms
Tidyparse (valid/total): 182/334
Original error:
"""/***************************************************************************"""
import os
from PyQt4 import QtGui, uic
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'interactive_map_tracking_dialog_base.ui')
Bad Repair: invalid syntax (<unknown>, line 5):
"""/***************************************************************************"""
import os
from PyQt4 import QtGui, uic
** FORM_CLASS, _ = uic.loadUiType(os.path.join
os.path.dirname(__file__), 'interactive_map_tracking_dialog_base.ui')
Synthesized repair in: 3367ms
Tidyparse (valid/total): 182/335
Original error:
def test():
runner = unittest.TextTestRunner()
runner.run(suite()
Good Repair:
def test():
runner = unittest.TextTestRunner()
** runner.run(suite)
Synthesized repair in: 48566ms
Tidyparse (valid/total): 183/336
Original error:
def git_pull():
"""Does a git stash then a git pull on the project"""
run('cd %s; git stash; git pull' %(env.code_root)))
Bad Repair: invalid syntax (<unknown>, line 1):
** def git_pull(:
"""Does a git stash then a git pull on the project"""
run('cd %s; git stash; git pull' %(env.code_root)))
Synthesized repair in: 8176ms
Tidyparse (valid/total): 183/337
Original error:
"""Nakasha"""
from flask import Flask, render_template, g, request, jsonify
import sqlite3
app = Flask(__name__)
app.config.update(dict(
DATABASE = '/tmp/nakasha.db',
DEBUG = True
)
Good Repair:
"""Nakasha"""
from flask import Flask, render_template, g, request, jsonify
import sqlite3
app = Flask(__name__)
** app.config.updatedict(
DATABASE = '/tmp/nakasha.db',
DEBUG = True
)
Synthesized repair in: 13919ms
Tidyparse (valid/total): 184/338
Original error:
def deploy():
'''部署文件'''
local(shutdown)
install()
local('rm -rf %s* ' % web_root_dir)
local('mv %s/* %s' %(target_classes_dir, web_root_dir)
Good Repair:
def deploy():
'''部署文件'''
local(shutdown)
install()
local('rm -rf %s* ' % web_root_dir)
** local('mv %s/* %s' %target_classes_dir, web_root_dir)
Synthesized repair in: 50941ms
Tidyparse (valid/total): 185/339
Original error:
class DrawableCullCallback(osg.Drawable.CullCallback):
virtual bool cull(osg.NodeVisitor *, osg.Drawable * drawable, osg.State *
print("Drawable cull callback ", drawable)
return False
Bad Repair: invalid syntax (<unknown>, line 2):
class DrawableCullCallback(osg.Drawable.CullCallback):
** virtual bool cullosg.NodeVisitor *, osg.Drawable * drawable, osg.State *
print("Drawable cull callback ", drawable)
return False
Synthesized repair in: 15610ms
Tidyparse (valid/total): 185/340
Original error:
def echo_colour(colour, string, * args):
"""click.echo colour with support for placeholders, e.g.%s"""
if args:
string = string % args
click.echo(click.style(string, fg = colour)
Good Repair:
def echo_colour(colour, string, * args):
"""click.echo colour with support for placeholders, e.g.%s"""
if args:
string = string % args
** click.echo(click.stylestring, fg = colour)
Synthesized repair in: 3842ms
Tidyparse (valid/total): 186/341
Original error:
def logaddexp(a, b):
diff = b - a
return tt.switch(diff > 0,
b + tt.log1p(tt.exp(- diff),
a + tt.log1p(tt.exp(diff)))
Good Repair:
def logaddexp(a, b):
diff = b - a
return tt.switch(diff > 0,
b + tt.log1p(tt.exp(- diff),
** a + tt.log1ptt.exp(diff)))
Synthesized repair in: 11612ms
Tidyparse (valid/total): 187/342
Original error:
def is_subtree(t1, t2):
if t1 == None:
return False
if t1 == t2:
return True
else:
while t1.root != t2.root:
t1_lc = t1.root.leftChild
t1_lc.parent == None
t1_rc = t1root.rightChild
t1_rc.parent == None
is_subtree(t1_lc, t2)
is_subtree(t1_rc, t2
Good Repair:
def is_subtree(t1, t2):
if t1 == None:
return False
if t1 == t2:
return True
else:
while t1.root != t2.root:
t1_lc = t1.root.leftChild
t1_lc.parent == None
t1_rc = t1root.rightChild
t1_rc.parent == None
is_subtree(t1_lc, t2)
** is_subtreet1_rc, t2
Synthesized repair in: 8062ms
Tidyparse (valid/total): 188/343
Original error:
def test_no_timeout():
parser = main.build_parser()
args = parser.parse_args('version'.split()
assert args.timeout == 60
Bad Repair: invalid syntax (<unknown>, line 3):
def test_no_timeout():
parser = main.build_parser()
** args = parser.parse_args'version'.split()
assert args.timeout == 60
Synthesized repair in: 29503ms
Tidyparse (valid/total): 188/344
Original error:
def _get_user_data_json(self):
try:
return yaml.load(self._fetch(CS_USERDATA_BASE_URL)
except:
return None
Good Repair:
def _get_user_data_json(self):
try:
** return yaml.loadself._fetch(CS_USERDATA_BASE_URL)
except:
return None
Synthesized repair in: 3658ms
Tidyparse (valid/total): 189/345
Original error:
import webapp2
from google.appengine.api import users
import os
import jinja2
jinja_env = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)
)
Good Repair:
import webapp2
from google.appengine.api import users
import os
import jinja2
jinja_env = jinja2.Environment(
** loader = jinja2.FileSystemLoaderos.path.dirname(__file__)
)
Synthesized repair in: 2533ms
Tidyparse (valid/total): 190/346
Original error:
def createJsonFullData(idList):
return{
"jsonrpc": "2.0",
"method": "bank/getBankObjectsData",
"params": {
"id_list": idList
"id": "9"
}
Bad Repair: invalid syntax (<unknown>, line 3):
def createJsonFullData(idList):
** return
"jsonrpc": "2.0",
"method": "bank/getBankObjectsData",
"params": {
"id_list": idList
"id": "9"
}
Synthesized repair in: 9013ms
Tidyparse (valid/total): 190/347
Original error:
def handle_suite_teardown_failures(self):
"""Internal usage only."""
self.visit(SuiteTeardownFailureHandler()))
Good Repair:
def handle_suite_teardown_failures(self):
"""Internal usage only."""
** self.visit(SuiteTeardownFailureHandler())
Synthesized repair in: 16668ms
Tidyparse (valid/total): 191/348
Original error:
def valor_total(self):
q = Decimal(str(self.quantidade)
return q * self.valor_unitario
Good Repair:
def valor_total(self):
** q = Decimal(strself.quantidade)
return q * self.valor_unitario
Synthesized repair in: 4174ms
Tidyparse (valid/total): 192/349
Original error:
def get_cameras():
"""Get all 'allocated' cameras."""
return _cameras_internal(** request.args.to_dict(flat = True)))
Good Repair:
def get_cameras():
"""Get all 'allocated' cameras."""
** return _cameras_internal(** request.args.to_dict(flat = True))
Synthesized repair in: 4285ms
Tidyparse (valid/total): 193/350
Original error:
def putAnnouncement(self, request):
"""Put Announcement into memcache"""
return StringMessage(data = self._cacheAnnouncement()))
Good Repair:
def putAnnouncement(self, request):
"""Put Announcement into memcache"""
** return StringMessage(data = self._cacheAnnouncement())
Synthesized repair in: 4264ms
Tidyparse (valid/total): 194/351
Original error:
from CvPythonExtensions import *
import sys
import os
import string
gc = CyGlobalContext()
pythonDir = os.path.join(gc.getAltrootDir(), '..', 'Python', 'v7')
execfile(os.path.join(pythonDir, 'PbWizard.py')
Good Repair:
from CvPythonExtensions import *
import sys
import os
import string
gc = CyGlobalContext()
pythonDir = os.path.join(gc.getAltrootDir(), '..', 'Python', 'v7')
** execfileos.path.join(pythonDir, 'PbWizard.py')
Synthesized repair in: 105429ms
Tidyparse (valid/total): 195/352
Original error:
def upload_build():
t = TEST_TYPES[os.environ["TEST_TYPE"]
if t.create_build:
t.upload_build()
Bad Repair: invalid syntax (<unknown>, line 2):
def upload_build():
** t = TEST_TYPES[os.environ"TEST_TYPE"]
if t.create_build:
t.upload_build()
Synthesized repair in: 12653ms
Tidyparse (valid/total): 195/353
Original error:
def test_get_deployment(self, mock):
fake_deployment = {
"id": "10",
"name": "activiti-examples.bar",
"deploymentTime": "2010-10-13T14:54:26.750+02:00",
"category": "examples",
"url": self.activiti.deployment_url(10),
"tenantId": None
Bad Repair: invalid syntax (<unknown>, line 2):
def test_get_deployment(self, mock):
** fake_deployment =
"id": "10",
"name": "activiti-examples.bar",
"deploymentTime": "2010-10-13T14:54:26.750+02:00",
"category": "examples",
"url": self.activiti.deployment_url(10),
"tenantId": None
Synthesized repair in: 20592ms
Tidyparse (valid/total): 195/354
Original error:
def start(self):
self._receiver_thread = threading.Thread(target = self._receiver, args = ()
self._receiver_thread.daemon = True
self._receiver_thread.start()
Bad Repair: invalid syntax (<unknown>, line 3):
def start(self):
self._receiver_thread = threading.Thread(target = self._receiver, args = ()
self._receiver_thread.daemon = True
** self._receiver_thread.start)
Synthesized repair in: 5209ms
Tidyparse (valid/total): 195/355
Original error:
def long_variable_from_numpy(numpy_matrix, cuda = False):
"""Convert integer numpy matrix to a Pytorch tensor for indexing operations"""
out = Variable(LongTensor(numpy_matrix.astype(np.int64))
if cuda:
out = out.cuda()
return out
Good Repair:
def long_variable_from_numpy(numpy_matrix, cuda = False):
"""Convert integer numpy matrix to a Pytorch tensor for indexing operations"""
** out = VariableLongTensor(numpy_matrix.astype(np.int64))
if cuda:
out = out.cuda()
return out
Synthesized repair in: 19143ms
Tidyparse (valid/total): 196/356
Original error:
def _AddSlaveBoard(_option, _opt_str, value, parser):
"""Callback that adds a slave board to the list of slave targets."""
parser.values.slave_targets.append(BuildTarget(value)
Good Repair:
def _AddSlaveBoard(_option, _opt_str, value, parser):
"""Callback that adds a slave board to the list of slave targets."""
** parser.values.slave_targets.appendBuildTarget(value)
Synthesized repair in: 9689ms
Tidyparse (valid/total): 197/357
Original error:
def test():
phash = helpers.Phash(plot()
assert phash.phash == 'fd7e03fc03bc0381', phash.get_details()
return
Good Repair:
def test():
** phash = helpers.Phashplot()
assert phash.phash == 'fd7e03fc03bc0381', phash.get_details()
return
Synthesized repair in: 8124ms
Tidyparse (valid/total): 198/358
Original error:
def upgrade():
op.add_column('bid',
sa.Column('weight', sa.FLOAT())
Bad Repair: invalid syntax (<unknown>, line 2):
def upgrade():
** op.add_column'bid',
sa.Column('weight', sa.FLOAT())
Synthesized repair in: 2831ms
Tidyparse (valid/total): 198/359
Original error:
def server_info(self):
return{
"version": "2.0.6",
"sysInfo": "Mock",
"versionArray": [
2,
0,
6,
0
],
"bits": 64,
"debug": False,
"maxBsonObjectSize": 16777216,
"ok": 1
Bad Repair: unexpected indent (<unknown>, line 3):
def server_info(self):
** return
"version": "2.0.6",
"sysInfo": "Mock",
"versionArray": [
2,
0,
6,
0
],
"bits": 64,
"debug": False,
"maxBsonObjectSize": 16777216,
"ok": 1
Synthesized repair in: 9199ms
Tidyparse (valid/total): 198/360
Original error:
from cattle.type_manager import register_type, LIFECYCLE, REQUEST_HANDLER
from.volmgr import Volmgr
from.handler import SnapshotHandler
register_type(LIFECYCLE, Volmgr()
register_type(REQUEST_HANDLER, SnapshotHandler())
Good Repair:
from cattle.type_manager import register_type, LIFECYCLE, REQUEST_HANDLER
from.volmgr import Volmgr
from.handler import SnapshotHandler
** register_typeLIFECYCLE, Volmgr()
register_type(REQUEST_HANDLER, SnapshotHandler())
Synthesized repair in: 4334ms
Tidyparse (valid/total): 199/361
Original error:
def as_sorted_tuple(val):
if not is_nonstr_iter(val):
val = (val, )
val = tuple(sorted(val)
return val
Good Repair:
def as_sorted_tuple(val):
if not is_nonstr_iter(val):
val = (val, )
** val = tuple(sortedval)
return val
Synthesized repair in: 130112ms
Tidyparse (valid/total): 200/362
Original error:
def prependChroot(self, clientPaths):
"""Returns List<String>"""
serverPaths = ArrayList < String >()
for
clientPath = None
in clientPaths) serverPaths.add(prependChroot(clientPath))
return serverPaths
Bad Repair: invalid syntax (<unknown>, line 3):
** def prependChroot(self, clientPaths:
"""Returns List<String>"""
serverPaths = ArrayList < String >()
for
clientPath = None
in clientPaths) serverPaths.add(prependChroot(clientPath))
return serverPaths
Synthesized repair in: 21258ms
Tidyparse (valid/total): 200/363
Original error:
def clean_fixed_price(self):
if self.range:
raise exceptions.ValidationError(
_("No range should be selected as the condition range will "
"be used instead.")
Bad Repair: invalid syntax (<unknown>, line 4):
def clean_fixed_price(self):
if self.range:
raise exceptions.ValidationError(
** _"No range should be selected as the condition range will "
"be used instead.")
Synthesized repair in: 15042ms
Tidyparse (valid/total): 200/364
Original error:
def parse_tokens(tokens):
"""Parses the given token sequence into a sequence of top-level TOML elements."""
from.tokenstream import TokenStream
return _parse_token_stream(TokenStream(tokens)
Good Repair:
def parse_tokens(tokens):
"""Parses the given token sequence into a sequence of top-level TOML elements."""
from.tokenstream import TokenStream
** return _parse_token_stream(TokenStreamtokens)
Synthesized repair in: 3081ms
Tidyparse (valid/total): 201/365
Original error:
def _compare_component(cls, matcher, value):
if callable(matcher):
return bool(matcher(value)))
elif matcher is None:
return True
else:
return value == matcher
Good Repair:
def _compare_component(cls, matcher, value):
if callable(matcher):
** return bool(matcher(value))
elif matcher is None:
return True
else:
return value == matcher
Synthesized repair in: 12174ms
Tidyparse (valid/total): 202/366
Original error:
def PrintOps(self, ops):
for op in ops:
print("\t", spdy4_codec_impl.FormatOp(op)
Bad Repair: invalid syntax (<unknown>, line 3):
def PrintOps(self, ops):
for op in ops:
** print"\t", spdy4_codec_impl.FormatOp(op)
Synthesized repair in: 8558ms
Tidyparse (valid/total): 202/367
Original error:
def disp_parent(parent):
psn, s = 0, ''
for fr in range(B.h):
s += fr * ' ' + ' '.join([
psn += B.w
return s
Good Repair:
def disp_parent(parent):
psn, s = 0, ''
for fr in range(B.h):
** s += fr * ' ' + ' '.join()
psn += B.w
return s
Synthesized repair in: 27801ms
Tidyparse (valid/total): 203/368
Original error:
from subzero.history_storage import SubtitleHistory
get_history = lambda: SubtitleHistory(Data, int(Prefs["history_size"])))
Good Repair:
from subzero.history_storage import SubtitleHistory
** get_history = lambda: SubtitleHistory(Data, int(Prefs["history_size"]))
Synthesized repair in: 4036ms
Tidyparse (valid/total): 204/369
Original error:
def init_driver():
driver = webdriver.PhantomJS(()
driver.wait = WebDriverWait(driver, 1)
return driver
Bad Repair: invalid syntax (<unknown>, line 3):
def init_driver():
driver = webdriver.PhantomJS(()
** driver.wait = WebDriverWaitdriver, 1)
return driver
Synthesized repair in: 8090ms
Tidyparse (valid/total): 204/370
Original error:
def test_directory_with_files_in_both(self):
print("w"), "line 1")
print("w"), "line 3")
base_utils.merge_trees(* self.paths())
self.assertFileContents("line 1\nline 3\n", "in_both")
Good Repair:
def test_directory_with_files_in_both(self):
** print("w"), "line 1"(
print("w"), "line 3")
base_utils.merge_trees(* self.paths())
self.assertFileContents("line 1\nline 3\n", "in_both")
Synthesized repair in: 266512ms
Tidyparse (valid/total): 205/371
Original error:
import unittest
import inspect
import os
from lxml import etree
from lxml.builder import E
myfile = inspect.getfile(inspect.currentframe())
mydir = os.path.dirname(inspect.getfile(inspect.currentframe())
os.environ['MACHINATION_BOOTSTRAP_DIR'] = mydir
from machination import context
Good Repair:
import unittest
import inspect
import os
from lxml import etree
from lxml.builder import E
myfile = inspect.getfile(inspect.currentframe())
** mydir = os.path.dirname(inspect.getfileinspect.currentframe())
os.environ['MACHINATION_BOOTSTRAP_DIR'] = mydir
from machination import context
Synthesized repair in: 47554ms
Tidyparse (valid/total): 206/372
Original error:
def __init__(self, tonic, mode, grand_staff, min_pitch, max_pitch, intervals, clef_left_hand, clef_right_hand, note_string, amount_of_bars, time_signature_numerator, time_signature_denominator, locales, bpm):
self.Locales = locales
self.Tonic = tonic
self.Mode = mode
self.Min_Pitch = min_pitch
self.Max_Pitch = max_pitch
self.Intervals = intervals
self.Note_String = note_string
self.Time_Signature_Numerator = time_signature_numerator
self.Time_Signature_Denominator = time_signature_denominator
self.Grand_Staff = grand_staff
self.BPM = bpm
self.mode_abbreviation = {'Minor': 'min',
'Major': 'maj',
}
self.Notes = [
"C,,", "D,,", "E,,", "F,,", "G,,", "A,,", "B,,",
"C,", "D,", "E,", "F,", "G,", "A,", "B,",
"C", "D", "E", "F", "G", "A", "B",
"c", "d", "e", "f", "g", "a", "b",
"c'", "d'", "e'", "f'", "g'", "a'", "b'"
"c''", "d''", "e''", "f''", "g''", "a''", "b''"
Bad Repair: invalid syntax (<unknown>, line 16):
def __init__(self, tonic, mode, grand_staff, min_pitch, max_pitch, intervals, clef_left_hand, clef_right_hand, note_string, amount_of_bars, time_signature_numerator, time_signature_denominator, locales, bpm):
self.Locales = locales
self.Tonic = tonic
self.Mode = mode
self.Min_Pitch = min_pitch
self.Max_Pitch = max_pitch
self.Intervals = intervals
self.Note_String = note_string
self.Time_Signature_Numerator = time_signature_numerator
self.Time_Signature_Denominator = time_signature_denominator
self.Grand_Staff = grand_staff
self.BPM = bpm
self.mode_abbreviation = {'Minor': 'min',
'Major': 'maj',
}
** self.Notes =
"C,,", "D,,", "E,,", "F,,", "G,,", "A,,", "B,,",
"C,", "D,", "E,", "F,", "G,", "A,", "B,",
"C", "D", "E", "F", "G", "A", "B",
"c", "d", "e", "f", "g", "a", "b",
"c'", "d'", "e'", "f'", "g'", "a'", "b'"
"c''", "d''", "e''", "f''", "g''", "a''", "b''"
Synthesized repair in: 28130ms
Tidyparse (valid/total): 206/373
Original error:
import os, sys
sys.path.inser(0, os.path.abspath('../cablegate')
import settings
from django.core.management import setup_environ
setup_environ(settings)
Bad Repair: invalid syntax (<unknown>, line 3):
import os, sys
sys.path.inser(0, os.path.abspath('../cablegate')
import settings
from django.core.management import setup_environ
** setup_environsettings)
Synthesized repair in: 2587ms
Tidyparse (valid/total): 206/374
Original error:
from source import *
from source.entity import entity as entity
import os
myDatabase = db("test", os.getcwd()))
myTable = entity("test_entity",
myDatabase, myDatabase.path)
Good Repair:
from source import *
from source.entity import entity as entity
import os
** myDatabase = db("test", os.getcwd())
myTable = entity("test_entity",
myDatabase, myDatabase.path)
Synthesized repair in: 17566ms
Tidyparse (valid/total): 207/375
Original error:
def get_month_abbr_len():
"""Calculate the number of characters we need to display the month"""
return max(len(month_abbr[i]) for i in range(1, 13) + 1
Bad Repair: invalid syntax (<unknown>, line 3):
def get_month_abbr_len():
"""Calculate the number of characters we need to display the month"""
** return maxlen(month_abbr[i]) for i in range(1, 13) + 1
Synthesized repair in: 37125ms
Tidyparse (valid/total): 207/376
Original error:
def extract_json_data():
open_file = json_file
file_to_open = file_path + os.sep + open_file
jsbml_parsed_data = json.load(open(file_to_open, "r")))
return jsbml_parsed_data
Good Repair:
def extract_json_data():
open_file = json_file
file_to_open = file_path + os.sep + open_file
** jsbml_parsed_data = json.load(open(file_to_open, "r"))
return jsbml_parsed_data
Synthesized repair in: 3289ms
Tidyparse (valid/total): 208/377
Original error:
def _gen_menu(menu, req):
loc = get_localizer(req)
menu.append({
'route': 'pdns.cl.domains',
'text': loc.translate(_('Domain Names'))
}
Bad Repair: invalid syntax (<unknown>, line 3):
def _gen_menu(menu, req):
loc = get_localizer(req)
** menu.append{
'route': 'pdns.cl.domains',
'text': loc.translate(_('Domain Names'))
}
Synthesized repair in: 123817ms
Tidyparse (valid/total): 208/378
Original error:
import os
import pexpect
import socket
from tempfile import mkstemp
import unittest
from mock_backend import create_and_start_backend
RSP_BINARY = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "rsp")
Good Repair:
import os
import pexpect
import socket
from tempfile import mkstemp
import unittest
from mock_backend import create_and_start_backend
** RSP_BINARY = os.path.abspath(os.path.joinos.path.dirname(__file__), "..", "rsp")
Synthesized repair in: 7857ms
Tidyparse (valid/total): 209/379
Original error:
def retranslateUi(self, ReplyAddBuddyDialog):
ReplyAddBuddyDialog.setWindowTitle(QtGui.QApplication.translate("ReplyAddBuddyDialog", "回应添加好友请求", None, QtGui.QApplication.UnicodeUTF8))
self.msg_text_edit.setHtml(QtGui.QApplication.translate("ReplyAddBuddyDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, ReplyAddBuddyDialog):
ReplyAddBuddyDialog.setWindowTitle(QtGui.QApplication.translate("ReplyAddBuddyDialog", "回应添加好友请求", None, QtGui.QApplication.UnicodeUTF8))
** self.msg_text_edit.setHtml(QtGui.QApplication.translate)"ReplyAddBuddyDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 276054ms
Tidyparse (valid/total): 209/380
Original error:
def get_css_dependencies(group):
"""Returns list of CSS dependencies belonging to `group` in settings.PIPELINE_JS."""
if settings.PIPELINE_ENABLED:
return[settings.PIPELINE_CSS[group]['output_filename']
else:
return settings.PIPELINE_CSS[group]['source_filenames']
Bad Repair: invalid syntax (<unknown>, line 5):
def get_css_dependencies(group):
"""Returns list of CSS dependencies belonging to `group` in settings.PIPELINE_JS."""
if settings.PIPELINE_ENABLED:
return[settings.PIPELINE_CSS[group]['output_filename']
else:
** return settings.PIPELINE_CSSgroup]['source_filenames']
Synthesized repair in: 10044ms
Tidyparse (valid/total): 209/381
Original error:
class PatchedForkingWorker(ForkingWorker):
'''A forking worker that doesn't register signal handlers'''
def signals(self, signals = ())):
'''Do not actually register signal handlers'''
pass
Good Repair:
class PatchedForkingWorker(ForkingWorker):
'''A forking worker that doesn't register signal handlers'''
** def signals(self, signals = ()):
'''Do not actually register signal handlers'''
pass
Synthesized repair in: 12573ms
Tidyparse (valid/total): 210/382
Original error:
def test_naturals0():
N = S.Naturals0
assert 0 in N
assert - 1 not in N
assert next(iter(N))) == 0
Good Repair:
def test_naturals0():
N = S.Naturals0
assert 0 in N
assert - 1 not in N
** assert next(iter(N)) == 0
Synthesized repair in: 4328ms
Tidyparse (valid/total): 211/383
Original error:
def binary_search_time(barbers, position, upper_bound):
low = 0
high = upper_bound
x = int(min(upper_bound, 1e11)
serve = 0
count = 0
while(count < 100):
count += 1
serve = compute_serve_at_time(barbers, x)
if(serve > position):
high = x
else:
low = x
x = (low + high) // 2
return x
Bad Repair: invalid syntax (<unknown>, line 5):
def binary_search_time(barbers, position, upper_bound):
low = 0
high = upper_bound
x = int(min(upper_bound, 1e11)
serve = 0
count = 0
** whilecount < 100):
count += 1
serve = compute_serve_at_time(barbers, x)
if(serve > position):
high = x
else:
low = x
x = (low + high) // 2
return x
Synthesized repair in: 35952ms
Tidyparse (valid/total): 211/384
Original error:
def dprint(* args):
"""Print to both stdout and stderr at the same time to allow for stdout redirection while still seeing the output in real time, rather than buffered like with tee"""
print(* args)
print(* args, file = sys.stderr
Bad Repair: cannot assign to operator (<unknown>, line 4):
def dprint(* args):
"""Print to both stdout and stderr at the same time to allow for stdout redirection while still seeing the output in real time, rather than buffered like with tee"""
print(* args)
** print* args, file = sys.stderr
Synthesized repair in: 17568ms
Tidyparse (valid/total): 211/385
Original error:
def get_available_project_types():
""" """
return([EmptyProject] +
get_available_project_types_plugins()
Good Repair:
def get_available_project_types():
""" """
return([EmptyProject] +
** get_available_project_types_plugins)
Synthesized repair in: 5847ms
Tidyparse (valid/total): 212/386
Original error:
def methodsByAttribute(clz, attribute):
"""Query metadata information for specific method attribute."""
ret = []
for m in clz.__dict__.values():
if hasattr(m, attribute):
ret.append(getattr(m, attribute)
return ret
Good Repair:
def methodsByAttribute(clz, attribute):
"""Query metadata information for specific method attribute."""
ret = []
for m in clz.__dict__.values():
if hasattr(m, attribute):
** ret.append(getattrm, attribute)
return ret
Synthesized repair in: 19381ms
Tidyparse (valid/total): 213/387
Original error:
def load_tests(loader, tests, ignore):
""" Add the Doctests from the module """
tests.addTests(doctest.DocTestSuite(Utils, optionflags = doctest.ELLIPSIS)
return tests
Good Repair:
def load_tests(loader, tests, ignore):
""" Add the Doctests from the module """
** tests.addTests(doctest.DocTestSuiteUtils, optionflags = doctest.ELLIPSIS)
return tests
Synthesized repair in: 19184ms
Tidyparse (valid/total): 214/388
Original error:
def is_number(obj):
"""Check if obj is number."""
return isinstance(obj, (int, float)
Good Repair:
def is_number(obj):
"""Check if obj is number."""
** return isinstance(obj, int, float)
Synthesized repair in: 3740ms
Tidyparse (valid/total): 215/389
Original error:
def __init__(self, dim):
self.dim = dim
self.weights = np.random.normal(0, 1, (1, dim)
Good Repair:
def __init__(self, dim):
self.dim = dim
** self.weights = np.random.normal0, 1, (1, dim)
Synthesized repair in: 4379ms
Tidyparse (valid/total): 216/390
Original error:
def synchronize_with_db(self, db, book_id, book_metadata, first_call):
'''Called during book matching when a book on the device is matched with'''
return(None, (None, False)
Good Repair:
def synchronize_with_db(self, db, book_id, book_metadata, first_call):
'''Called during book matching when a book on the device is matched with'''
** returnNone, (None, False)
Synthesized repair in: 8955ms
Tidyparse (valid/total): 217/391
Original error:
def test_normal_legal_string_washing(self):
"""textutils - testing UTF-8 washing on a perfectly normal string"""
some_str = "This is an example string"
self.assertEqual(some_str, wash_for_utf8(some_str)
Good Repair:
def test_normal_legal_string_washing(self):
"""textutils - testing UTF-8 washing on a perfectly normal string"""
some_str = "This is an example string"
** self.assertEqualsome_str, wash_for_utf8(some_str)
Synthesized repair in: 4091ms
Tidyparse (valid/total): 218/392
Original error:
def initialize(self):
self.database.execute("CREATE TABLE IF NOT EXISTS mixerData (" "forecastID INTEGER NOT NULL, " "forecastTimestamp INTEGER NOT NULL, " "timestamp NUMERIC NOT NULL, " "temperature DECIMAL DEFAULT NULL, " "rh DECIMAL DEFAULT NULL, " "wind DECIMAL DEFAULT NULL, " "solarRad DECIMAL DEFAULT NULL, " "skyCover DECIMAL DEFAULT NULL, " "rain DECIMAL DEFAULT NULL, " "et0 DECIMAL DEFAULT NULL, " "pop DECIMAL DEFAULT NULL, " "qpf DECIMAL DEFAULT NULL, " "condition INTEGER DEFAULT NULL, " "pressure DECIMAL DEFAULT NULL, " "dewPoint DECIMAL DEFAULT NULL, " "minTemp DECIMAL DEFAULT NULL, " "maxTemp DECIMAL DEFAULT NULL, " "minRH DECIMAL DEFAULT NULL, " "maxRH DECIMAL DEFAULT NULL, " "et0calc DECIMAL DEFAULT NULL, " "et0final DECIMAL DEFAULT NULL, "
self.database.commit()
Bad Repair: invalid syntax (<unknown>, line 3):
def initialize(self):
self.database.execute("CREATE TABLE IF NOT EXISTS mixerData (" "forecastID INTEGER NOT NULL, " "forecastTimestamp INTEGER NOT NULL, " "timestamp NUMERIC NOT NULL, " "temperature DECIMAL DEFAULT NULL, " "rh DECIMAL DEFAULT NULL, " "wind DECIMAL DEFAULT NULL, " "solarRad DECIMAL DEFAULT NULL, " "skyCover DECIMAL DEFAULT NULL, " "rain DECIMAL DEFAULT NULL, " "et0 DECIMAL DEFAULT NULL, " "pop DECIMAL DEFAULT NULL, " "qpf DECIMAL DEFAULT NULL, " "condition INTEGER DEFAULT NULL, " "pressure DECIMAL DEFAULT NULL, " "dewPoint DECIMAL DEFAULT NULL, " "minTemp DECIMAL DEFAULT NULL, " "maxTemp DECIMAL DEFAULT NULL, " "minRH DECIMAL DEFAULT NULL, " "maxRH DECIMAL DEFAULT NULL, " "et0calc DECIMAL DEFAULT NULL, " "et0final DECIMAL DEFAULT NULL, "
** self.database.commit))
Synthesized repair in: 39588ms
Tidyparse (valid/total): 218/393
Original error:
def run_test(self, prefix, args = []):
t = self.find_test(prefix)
if t:
return subprocess.call([t] + args, env = self.build_env()
Bad Repair: invalid syntax (<unknown>, line 4):
def run_test(self, prefix, args = []):
t = self.find_test(prefix)
if t:
** return subprocess.call[t] + args, env = self.build_env()
Synthesized repair in: 84517ms
Tidyparse (valid/total): 218/394
Original error:
def test_cert_display_assertion(self):
""" Verify assertion for invalid cert type """
self.assertRaises(ValueError, lambda: get_certificate_type_display_value('junk')
Good Repair:
def test_cert_display_assertion(self):
""" Verify assertion for invalid cert type """
** self.assertRaisesValueError, lambda: get_certificate_type_display_value('junk')
Synthesized repair in: 16537ms
Tidyparse (valid/total): 219/395
Original error:
class SetFeaturedSpeakersHandler(webapp2.RequestHandler):
def post(self):
"""Set memcache with conference feature speaker"""
ConferenceApi._cacheFeatureSpeaker(self.request.get('websafeConferenceKey'),
self.request.get('speakerUserId'),
self.request.get('speakerName'),
self.request.get('sessionName')
Bad Repair: invalid syntax (<unknown>, line 4):
class SetFeaturedSpeakersHandler(webapp2.RequestHandler):
def post(self):
"""Set memcache with conference feature speaker"""
** ConferenceApi._cacheFeatureSpeaker(self.request.get'websafeConferenceKey'),
self.request.get('speakerUserId'),
self.request.get('speakerName'),
self.request.get('sessionName')
Synthesized repair in: 65320ms
Tidyparse (valid/total): 219/396
Original error:
def finalize(self, result):
self.html.append('<div>')
self.html.append("Ran %d test%s" %
(result.testsRun, result.testsRun != 1 and "s"
Bad Repair: invalid syntax (<unknown>, line 4):
def finalize(self, result):
self.html.append('<div>')
self.html.append("Ran %d test%s" %
** )result.testsRun, result.testsRun != 1 and "s"
Synthesized repair in: 21109ms
Tidyparse (valid/total): 219/397
Original error:
class SkipListener:
def __init__(self):
self.results = []
def listener(self, path, exception):
self.results.append((path, exception)))
Good Repair:
class SkipListener:
def __init__(self):
self.results = []
def listener(self, path, exception):
** self.results.append((path, exception))
Synthesized repair in: 9342ms
Tidyparse (valid/total): 220/398
Original error:
import unittest
import sys
import os
import os
cwd = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, cwd + '/../../../build/bindings/python'))
import satsolver
Bad Repair: invalid syntax (<unknown>, line 6):
import unittest
import sys
import os
import os
** cwd = os.path.abspath(os.path.dirname(__file__)
sys.path.insert(0, cwd + '/../../../build/bindings/python'))
import satsolver
Synthesized repair in: 17157ms
Tidyparse (valid/total): 220/399
Original error:
def round_up(x, nearest_number = 1):
nearest_number = nearest_number * 1.0
return int(math.ceil(x / nearest_number) * nearest_number
Good Repair:
def round_up(x, nearest_number = 1):
nearest_number = nearest_number * 1.0
** return int(math.ceilx / nearest_number) * nearest_number
Synthesized repair in: 26038ms
Tidyparse (valid/total): 221/400
Original error:
def test_output_outlines_success_colorful():
"Language: ru -> sucess outlines colorful"
runner = Runner(join_path('ru', 'success', 'outlines.feature'), verbosity = 4)
runner.run()
assert_stdout_lines(
'\n'
Bad Repair: unexpected indent (<unknown>, line 6):
def test_output_outlines_success_colorful():
"Language: ru -> sucess outlines colorful"
runner = Runner(join_path('ru', 'success', 'outlines.feature'), verbosity = 4)
runner.run()
** assert_stdout_lines
'\n'
Synthesized repair in: 109038ms
Tidyparse (valid/total): 221/401
Original error:
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment; filename=%s" % os.path.basename(path)
if not self._allow_client_caching:
self.set_header("Cache-Control", "max-age=0, must-revalidate, private")
self.set_header("Expires", "-1")
Bad Repair: invalid syntax (<unknown>, line 4):
def set_extra_headers(self, path):
if self._as_attachment:
self.set_header("Content-Disposition", "attachment; filename=%s" % os.path.basename(path)
if not self._allow_client_caching:
** self.set_header"Cache-Control", "max-age=0, must-revalidate, private")
self.set_header("Expires", "-1")
Synthesized repair in: 24139ms
Tidyparse (valid/total): 221/402
Original error:
class Config(object):
"""Common configurations that cut across to all environnents"""
GOOGLE_LOGIN_CLIENT_ID = "<your-id-ending-with>.apps.googleusercontent.com"
GOOGLE_LOGIN_CLIENT_SECRET = "<your-secret>"
OAUTH_CREDENTIALS = {
'google': {
'id': GOOGLE_LOGIN_CLIENT_ID,
'secret': GOOGLE_LOGIN_CLIENT_SECRET
}
Bad Repair: invalid syntax (<unknown>, line 5):
class Config(object):
"""Common configurations that cut across to all environnents"""
GOOGLE_LOGIN_CLIENT_ID = "<your-id-ending-with>.apps.googleusercontent.com"
GOOGLE_LOGIN_CLIENT_SECRET = "<your-secret>"
** OAUTH_CREDENTIALS =
'google': {
'id': GOOGLE_LOGIN_CLIENT_ID,
'secret': GOOGLE_LOGIN_CLIENT_SECRET
}
Synthesized repair in: 15061ms
Tidyparse (valid/total): 221/403
Original error:
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
from tdi import html
template = html.from_string("""<node>""".lstrip()
Bad Repair: invalid syntax (<unknown>, line 5):
import warnings as _warnings
_warnings.resetwarnings()
_warnings.filterwarnings('error')
from tdi import html
** template = html.from_string"""<node>""".lstrip()
Synthesized repair in: 20247ms
Tidyparse (valid/total): 221/404
Original error:
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('thesaurus.urls'),
)
Bad Repair: invalid syntax (<unknown>, line 3):
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
** urlr'^', include('thesaurus.urls'),
)
Synthesized repair in: 1926ms
Tidyparse (valid/total): 221/405
Original error:
def test_scrape_basic_view(self):
self.scrape('simple/basic.beancount',
extra_args = argparse.Namespace(view = 'year/2013')
Bad Repair: invalid syntax (<unknown>, line 3):
def test_scrape_basic_view(self):
self.scrape('simple/basic.beancount',
** extra_args = argparse.Namespaceview = 'year/2013')
Synthesized repair in: 3438ms
Tidyparse (valid/total): 221/406
Original error:
def running(self):
"""True if the child process is running."""
return bool(self._child and self._state not in(Process.STATE_STOPPED, Process.STATE_HUNG)))
Good Repair:
def running(self):
"""True if the child process is running."""
** return bool(self._child and self._state not in(Process.STATE_STOPPED, Process.STATE_HUNG))
Synthesized repair in: 21692ms
Tidyparse (valid/total): 222/407
Original error:
def deserialize(cls, serialized):
''' Create a PublicKey from a base64 encoded bytes.'''
return PublicKey(
nacl.public.PublicKey(serialized,
encoder = nacl.encoding.Base64Encoder)
Bad Repair: unexpected indent (<unknown>, line 4):
def deserialize(cls, serialized):
''' Create a PublicKey from a base64 encoded bytes.'''
** return PublicKey
nacl.public.PublicKey(serialized,
encoder = nacl.encoding.Base64Encoder)
Synthesized repair in: 19690ms
Tidyparse (valid/total): 222/408
Original error:
def create(cls, name, description, enabled = False):
"""Creates a new capability."""
return Capability(DBCapabilities.create(
name = name, description = description, enabled = enabled)
Bad Repair: invalid syntax (<unknown>, line 4):
def create(cls, name, description, enabled = False):
"""Creates a new capability."""
** return Capability(DBCapabilities.create
name = name, description = description, enabled = enabled)
Synthesized repair in: 3068ms
Tidyparse (valid/total): 222/409
Original error:
def CopyClipboard(self):
self.ArcCode.clipboard_clear()
self.ArcCode.clipboard_append(self.ArcCode.get()
Good Repair:
def CopyClipboard(self):
self.ArcCode.clipboard_clear()
** self.ArcCode.clipboard_append(self.ArcCode.get)
Synthesized repair in: 12442ms
Tidyparse (valid/total): 223/410
Original error:
def testGetValuesFromPSTable(self):
print(self.tdb)
values = ["1431824413.343", "43.1", "1.1322905470656", "193830912", "98136216", "1458167781", "11763736", "412066", "1", "1"
Good Repair:
def testGetValuesFromPSTable(self):
print(self.tdb)
** values = "1431824413.343", "43.1", "1.1322905470656", "193830912", "98136216", "1458167781", "11763736", "412066", "1", "1"
Synthesized repair in: 17570ms
Tidyparse (valid/total): 224/411
Original error:
def endlog():
end = time()
elapsed = end - start
log("End Program", secondsToStr(elapsed)
Bad Repair: invalid syntax (<unknown>, line 4):
def endlog():
end = time()
elapsed = end - start
** log"End Program", secondsToStr(elapsed)
Synthesized repair in: 13943ms
Tidyparse (valid/total): 224/412
Original error:
def go_to(self, page: str):
if page not in self.pages:
raise InvalidPageNameException()
return globals()[self.pages[page](self.connector)
Good Repair:
def go_to(self, page: str):
if page not in self.pages:
raise InvalidPageNameException()
** return globals()[self.pagespage](self.connector)
Synthesized repair in: 63428ms
Tidyparse (valid/total): 225/413
Original error:
n = int(raw_input()
tag = '';
space = '';
for i in range(0, n):
space = ''
j = n - i - 1
while j > 0:
space += ' '
j -= 1
tag += '#'
print(space + tag)
Good Repair:
** n = intraw_input()
tag = '';
space = '';
for i in range(0, n):
space = ''
j = n - i - 1
while j > 0:
space += ' '
j -= 1
tag += '#'
print(space + tag)
Synthesized repair in: 4315ms
Tidyparse (valid/total): 226/414
Original error:
def test_location_print_all():
tus = Location(32.2, - 111, 'US/Arizona', 700, 'Tucson')
expected_str = '\n'.join([
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Bad Repair: unexpected indent (<unknown>, line 4):
def test_location_print_all():
tus = Location(32.2, - 111, 'US/Arizona', 700, 'Tucson')
** expected_str = '\n'.join()
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Synthesized repair in: 13926ms
Tidyparse (valid/total): 226/415
Original error:
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
print('set config.misc.showtestcard to', {'yes': True,
'no': False}[selection]
if selection == 'yes':
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
return
Bad Repair: invalid syntax (<unknown>, line 4):
def showTestCard(self, selection = None):
if selection is None:
selection = self.selection
** print'set config.misc.showtestcard to', {'yes': True,
'no': False}[selection]
if selection == 'yes':
config.misc.showtestcard.value = True
else:
config.misc.showtestcard.value = False
return
Synthesized repair in: 18064ms
Tidyparse (valid/total): 226/416
Original error:
def web_socket_do_extra_handshake(request):
request.connection.write('HTTP/1.1 101 Switching Protocols: \x0D\x0AConnection: Upgrade\x0D\x0AUpgrade: WebSocket\x0D\x0ASet-Cookie: ws_test=test\x0D\x0ASec-WebSocket-Origin: ' + request.ws_origin + '\x0D\x0ASec-WebSocket-Accept: ' + genkey(request.headers_in.get(common.SEC_WEBSOCKET_KEY_HEADER) + '\x0D\x0A\x0D\x0A')
request.ws_stream.send_message("test", binary = False)
return
Bad Repair: invalid syntax (<unknown>, line 2):
def web_socket_do_extra_handshake(request):
** request.connection.write'HTTP/1.1 101 Switching Protocols: \x0D\x0AConnection: Upgrade\x0D\x0AUpgrade: WebSocket\x0D\x0ASet-Cookie: ws_test=test\x0D\x0ASec-WebSocket-Origin: ' + request.ws_origin + '\x0D\x0ASec-WebSocket-Accept: ' + genkey(request.headers_in.get(common.SEC_WEBSOCKET_KEY_HEADER) + '\x0D\x0A\x0D\x0A')
request.ws_stream.send_message("test", binary = False)
return
Synthesized repair in: 19939ms
Tidyparse (valid/total): 226/417
Original error:
def base_job():
json_str = """{"description": "desc", """
job = Parse(json_str, models.JobSpec()
return job
Bad Repair: unmatched '}' (<unknown>, line 3):
def base_job():
json_str = """{"description": "desc", """
** job = Parse}json_str, models.JobSpec()
return job
Synthesized repair in: 17912ms
Tidyparse (valid/total): 226/418
Original error:
def angles(self, value):
if isinstance(value, cfgmath.Vec):
self.setKeyvalue("angles", value))
self._angles = value
return
Bad Repair: invalid syntax (<unknown>, line 2):
** def angles(self, value:
if isinstance(value, cfgmath.Vec):
self.setKeyvalue("angles", value))
self._angles = value
return
Synthesized repair in: 12081ms
Tidyparse (valid/total): 226/419
Original error:
def __init__(self, gametype, new_port, metahostpath, savesdir):
Thread.__init__(self)
self.new_port = new_port;
self.gametype = gametype;
self.metahostpath = metahostpath;
self.savesdir = savesdir;
self.started_time = strftime("%Y-%m-%d %H: %M: %S", gmtime();
self.num_start = 0;
self.num_error = 0;
Good Repair:
def __init__(self, gametype, new_port, metahostpath, savesdir):
Thread.__init__(self)
self.new_port = new_port;
self.gametype = gametype;
self.metahostpath = metahostpath;
self.savesdir = savesdir;
** self.started_time = strftime("%Y-%m-%d %H: %M: %S", gmtime);
self.num_start = 0;
self.num_error = 0;
Synthesized repair in: 6692ms
Tidyparse (valid/total): 227/420
Original error:
from.reports import sql
CUSTOM_REPORTS = (
('Custom Reports', (
sql.DistrictMonthly,
sql.HeathFacilityMonthly,
sql.DistrictWeekly,
sql.HealthFacilityWeekly,
),
)
Good Repair:
from.reports import sql
CUSTOM_REPORTS = (
** 'Custom Reports', (
sql.DistrictMonthly,
sql.HeathFacilityMonthly,
sql.DistrictWeekly,
sql.HealthFacilityWeekly,
),
)
Synthesized repair in: 13892ms
Tidyparse (valid/total): 228/421
Original error:
def printStep(self, inputs, target, output):
print('[',
for input in inputs:
print(input, )
print('] [', target, '] =', output)
Bad Repair: invalid syntax (<unknown>, line 3):
def printStep(self, inputs, target, output):
print('[',
for input in inputs:
print(input, )
** print'] [', target, '] =', output)
Synthesized repair in: 380746ms
Tidyparse (valid/total): 228/422
Original error:
def iterate(self, i):
self.setInfo('<b>Algorithm %s iteration #%i completed</b>'
%(self.alg.name, i)
Good Repair:
def iterate(self, i):
self.setInfo('<b>Algorithm %s iteration #%i completed</b>'
** %self.alg.name, i)
Synthesized repair in: 8876ms
Tidyparse (valid/total): 229/423
Original error:
def action_version(args):
"Show version/license info"
print(
"WifiStalker\n"
"Curent version: {0}\n"
"Project author: Tomasz bla Fortuna\n"
"Backend license: Gnu General Public License version 2\n"
"Frontend license: "
Bad Repair: unexpected indent (<unknown>, line 4):
def action_version(args):
"Show version/license info"
** print
"WifiStalker\n"
"Curent version: {0}\n"
"Project author: Tomasz bla Fortuna\n"
"Backend license: Gnu General Public License version 2\n"
"Frontend license: "
Synthesized repair in: 4028ms
Tidyparse (valid/total): 229/424
Original error:
def register(linter):
"""Required method to auto register this checker."""
linter.register_checker(ElseifUsedChecker(linter)
Good Repair:
def register(linter):
"""Required method to auto register this checker."""
** linter.register_checker(ElseifUsedCheckerlinter)
Synthesized repair in: 8837ms
Tidyparse (valid/total): 230/425
Original error:
def preview_clickHandler(self, x, y):
d.selections.append(PlacementClick(x, y)
if len(d.selections) == 3:
return 'createDimension: %s' % findUnusedObjectName('bendNote')
Bad Repair: invalid syntax (<unknown>, line 3):
def preview_clickHandler(self, x, y):
d.selections.append(PlacementClick(x, y)
** if lend.selections) == 3:
return 'createDimension: %s' % findUnusedObjectName('bendNote')
Synthesized repair in: 41506ms
Tidyparse (valid/total): 230/426
Original error:
def isarchive(cls, filename):
try:
return tarfile.is_tarfile(encode(filename)
except:
return False
Good Repair:
def isarchive(cls, filename):
try:
** return tarfile.is_tarfile(encodefilename)
except:
return False
Synthesized repair in: 9082ms
Tidyparse (valid/total): 231/427
Original error:
def __regex_and_pattern_from(self, prefix):
if not prefix.startswith('/'):
raise ValueError('"%s" is an invalid prefix format' % prefix)
regex = r"^%s" % prefix.lstrip('/')
pattern = patterns('', url(r'^', self)
return(regex, pattern)
Bad Repair: invalid syntax (<unknown>, line 5):
def __regex_and_pattern_from(self, prefix):
if not prefix.startswith('/'):
raise ValueError('"%s" is an invalid prefix format' % prefix)
regex = r"^%s" % prefix.lstrip('/')
** pattern = patterns'', url(r'^', self)
return(regex, pattern)
Synthesized repair in: 162556ms
Tidyparse (valid/total): 231/428
Original error:
""" Copyright Sphere Inc"""
import re
from talkweb import cparser
if __name__ == "__main__":
f = open("./gate.sk")
s = f.read()
cparser.parse(aline, - 1, len(s)
Good Repair:
""" Copyright Sphere Inc"""
import re
from talkweb import cparser
if __name__ == "__main__":
f = open("./gate.sk")
s = f.read()
** cparser.parsealine, - 1, len(s)
Synthesized repair in: 35773ms
Tidyparse (valid/total): 232/429
Original error:
def _get_object(self):
""": return: """
return Object.new_from_sha(self.repo, hex_to_bin(self.dereference_recursive(self.repo, self.path))
Good Repair:
def _get_object(self):
""": return: """
** return Object.new_from_sha(self.repo, hex_to_bin(self.dereference_recursiveself.repo, self.path))
Synthesized repair in: 12600ms
Tidyparse (valid/total): 233/430
Original error:
class _fsid(ctypes.Structure):
_fields_ = [
("val", ctypes.c_int * 2)
Bad Repair: invalid syntax (<unknown>, line 2):
class _fsid(ctypes.Structure):
** _fields_ =
("val", ctypes.c_int * 2)
Synthesized repair in: 25645ms
Tidyparse (valid/total): 233/431
Original error:
class LearnUI(Gtk.Box):
def set_kr(self, s):
self.kr.set_markup('<span size="50000">'
Bad Repair: invalid syntax (<unknown>, line 3):
class LearnUI(Gtk.Box):
def set_kr(self, s):
** self.kr.set_markup'<span size="50000">'
Synthesized repair in: 3846ms
Tidyparse (valid/total): 233/432
Original error:
def get_shortened_ipv6(address):
addr = netaddr.IPAddress(address, version = 6)
return str(addr.ipv6()
Good Repair:
def get_shortened_ipv6(address):
addr = netaddr.IPAddress(address, version = 6)
** return straddr.ipv6()
Synthesized repair in: 14213ms
Tidyparse (valid/total): 234/433
Original error:
def autogo(go, freq = None):
logger.info("Start autonomous GO " + go.ifname)
res = go.p2p_start_go(freq = freq)
logger.debug("res: " + str(res)
return res
Bad Repair: invalid syntax (<unknown>, line 4):
def autogo(go, freq = None):
logger.info("Start autonomous GO " + go.ifname)
res = go.p2p_start_go(freq = freq)
** logger.debug"res: " + str(res)
return res
Synthesized repair in: 38611ms
Tidyparse (valid/total): 234/434
Original error:
def setup(self):
import re
self.urltag_re = re.compile(r"""url(""", re.VERBOSE)
Bad Repair: unexpected indent (<unknown>, line 3):
def setup(self):
import re
** self.urltag_re = re.compile(r"""url""", re.VERBOSE)
Synthesized repair in: 3768ms
Tidyparse (valid/total): 234/435
Original error:
def _parameter_to_xml(self):
if self.parameter:
return '<parameter>%s</parameter>' %(cgi.escape(self.parameter)
return ""
Good Repair:
def _parameter_to_xml(self):
if self.parameter:
** return '<parameter>%s</parameter>' %(cgi.escapeself.parameter)
return ""
Synthesized repair in: 3764ms
Tidyparse (valid/total): 235/436
Original error:
from subprocess import call
from os import path
import hitchpostgres
import hitchselenium
import hitchpython
import hitchserve
import hitchredis
import hitchtest
import hitchsmtp
PROJECT_DIRECTORY = path.abspath(path.join(path.dirname(__file__), '..')
Good Repair:
from subprocess import call
from os import path
import hitchpostgres
import hitchselenium
import hitchpython
import hitchserve
import hitchredis
import hitchtest
import hitchsmtp
** PROJECT_DIRECTORY = path.abspath(path.joinpath.dirname(__file__), '..')
Synthesized repair in: 2793ms
Tidyparse (valid/total): 236/437
Original error:
def retranslateUi(self, SvnSwitchDialog):
_translate = QtCore.QCoreApplication.translate
SvnSwitchDialog.setWindowTitle(_translate("SvnSwitchDialog", "Subversion Switch"))
self.TextLabel1.setText(_translate("SvnSwitchDialog", "Tag Name:"))
self.tagCombo.setToolTip(_translate("SvnSwitchDialog", "Enter the name of the tag"))
self.tagCombo.setWhatsThis(_translate("SvnSwitchDialog", "<b>Tag Name</b>\n"
Bad Repair: invalid syntax (<unknown>, line 6):
def retranslateUi(self, SvnSwitchDialog):
_translate = QtCore.QCoreApplication.translate
SvnSwitchDialog.setWindowTitle(_translate("SvnSwitchDialog", "Subversion Switch"))
self.TextLabel1.setText(_translate("SvnSwitchDialog", "Tag Name:"))
self.tagCombo.setToolTip(_translate("SvnSwitchDialog", "Enter the name of the tag"))
** self.tagCombo.setWhatsThis(_translate)"SvnSwitchDialog", "<b>Tag Name</b>\n"
Synthesized repair in: 1485877ms
Tidyparse (valid/total): 236/438
Original error:
def __clear(self, _ = None):
if self.__task_queue is not None:
self.__task_queue.close(ConnectionDone('done')
Good Repair:
def __clear(self, _ = None):
if self.__task_queue is not None:
** self.__task_queue.closeConnectionDone('done')
Synthesized repair in: 7173ms
Tidyparse (valid/total): 237/439
Original error:
def retranslateUi(self, HgNewProjectOptionsDialog):
_translate = QtCore.QCoreApplication.translate
HgNewProjectOptionsDialog.setWindowTitle(_translate("HgNewProjectOptionsDialog", "New Project from Repository"))
HgNewProjectOptionsDialog.setWhatsThis(_translate("HgNewProjectOptionsDialog", "<b>New Project from Repository Dialog</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, HgNewProjectOptionsDialog):
_translate = QtCore.QCoreApplication.translate
HgNewProjectOptionsDialog.setWindowTitle(_translate("HgNewProjectOptionsDialog", "New Project from Repository"))
** HgNewProjectOptionsDialog.setWhatsThis(_translate)"HgNewProjectOptionsDialog", "<b>New Project from Repository Dialog</b>\n"
Synthesized repair in: 283213ms
Tidyparse (valid/total): 237/440
Original error:
def CompareFiles(font1, font2):
"""Compares fonts assuming font1/2 are font files."""
print(CompareSize(font1, font2)
Good Repair:
def CompareFiles(font1, font2):
"""Compares fonts assuming font1/2 are font files."""
** printCompareSize(font1, font2)
Synthesized repair in: 6964ms
Tidyparse (valid/total): 238/441
Original error:
def join(* paths):
"""Like os.path.join but doesn't treat absolute RHS specially"""
return os.path.normpath("/".join(paths)
Good Repair:
def join(* paths):
"""Like os.path.join but doesn't treat absolute RHS specially"""
** return os.path.normpath("/".joinpaths)
Synthesized repair in: 2933ms
Tidyparse (valid/total): 239/442
Original error:
def datafilelistloop(subpath, dtstrlist, datadir = DATA_DIR):
listout = []
for dtstr in dtstrlist:
listout.extend(datafilelist(subpath % dtstr, datadir = datadir)
return listout
Good Repair:
def datafilelistloop(subpath, dtstrlist, datadir = DATA_DIR):
listout = []
for dtstr in dtstrlist:
** listout.extenddatafilelist(subpath % dtstr, datadir = datadir)
return listout
Synthesized repair in: 28634ms
Tidyparse (valid/total): 240/443
Original error:
""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file"""
import hyperspy.hspy as hspy
import numpy as np
import matplotlib.pyplot as plt
s = hspy.signals.Spectrum(np.random.rand(1024)
s.plot()
plt.savefig("testSpectrum.png")
Good Repair:
""" Loads hyperspy as a regular python library, creates a spectrum with random numbers and plots it to a file"""
import hyperspy.hspy as hspy
import numpy as np
import matplotlib.pyplot as plt
** s = hspy.signals.Spectrum(np.random.rand1024)
s.plot()
plt.savefig("testSpectrum.png")
Synthesized repair in: 6362ms
Tidyparse (valid/total): 241/444
Original error:
def opener_for(ca_bundle = None):
"""Get a urlopen() replacement that uses ca_bundle for verification"""
return urllib2.build_opener(
VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()))
).open
Bad Repair: invalid syntax (<unknown>, line 1):
** def opener_for(ca_bundle = None:
"""Get a urlopen() replacement that uses ca_bundle for verification"""
return urllib2.build_opener(
VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()))
).open
Synthesized repair in: 36033ms
Tidyparse (valid/total): 241/445
Original error:
def load_model(path_to_object):
"""Load a pickled prediction model."""
return load(open(path_to_object)
Good Repair:
def load_model(path_to_object):
"""Load a pickled prediction model."""
** return load(openpath_to_object)
Synthesized repair in: 17170ms
Tidyparse (valid/total): 242/446
Original error:
def ndnb_enumerate(names):
out = bytearray()
for name in names:
out += ndnb.dtag(ndnb.DTAG_LINK, name.get_ndnb()))
return ndnb.dtag(ndnb.DTAG_COLLECTION, out)
Good Repair:
def ndnb_enumerate(names):
out = bytearray()
for name in names:
** out += ndnb.dtag(ndnb.DTAG_LINK, name.get_ndnb())
return ndnb.dtag(ndnb.DTAG_COLLECTION, out)
Synthesized repair in: 11678ms
Tidyparse (valid/total): 243/447
Original error:
def retranslateUi(self, About):
About.setWindowTitle(QtGui.QApplication.translate("About", "About Polygon Area", None, QtGui.QApplication.UnicodeUTF8))
self.titleLabel.setText(QtGui.QApplication.translate("About", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, About):
About.setWindowTitle(QtGui.QApplication.translate("About", "About Polygon Area", None, QtGui.QApplication.UnicodeUTF8))
** self.titleLabel.setText(QtGui.QApplication.translate)"About", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 54185ms
Tidyparse (valid/total): 243/448
Original error:
def _render_begin(self):
self._pygame_surface = pygame.Surface(self._size, pygame.SRCALPHA, 32)
self._pygame_surface.fill((0, 0, 0, 0)
Good Repair:
def _render_begin(self):
self._pygame_surface = pygame.Surface(self._size, pygame.SRCALPHA, 32)
** self._pygame_surface.fill(0, 0, 0, 0)
Synthesized repair in: 39207ms
Tidyparse (valid/total): 244/449
Original error:
def startfile(self):
with open(self.filename, 'a') as f:
f.write('<?xml version="1.0"?> \n'
Bad Repair: invalid syntax (<unknown>, line 3):
def startfile(self):
with open(self.filename, 'a') as f:
** f.write'<?xml version="1.0"?> \n'
Synthesized repair in: 33672ms
Tidyparse (valid/total): 244/450
Original error:
class Pokemon(Base):
__tablename__ = 'pokemon'
id = sa.Column(sa.Integer, primary_key = True)
pokemon_name = sa.Column(sa.String)
user_id = sa.Column(sa.Integer, sa.ForeignKey('players.id')
Good Repair:
class Pokemon(Base):
__tablename__ = 'pokemon'
id = sa.Column(sa.Integer, primary_key = True)
pokemon_name = sa.Column(sa.String)
** user_id = sa.Columnsa.Integer, sa.ForeignKey('players.id')
Synthesized repair in: 33085ms
Tidyparse (valid/total): 245/451
Original error:
def get_sentence(self):
indices = self.node_dict.keys()
indices.sort()
sentence = ' '.join([self.node_dict[k].word for k in indices[1: ])
return sentence
Good Repair:
def get_sentence(self):
indices = self.node_dict.keys()
indices.sort()
** sentence = ' '.join(self.node_dict[k].word for k in indices[1: ])
return sentence
Synthesized repair in: 141000ms
Tidyparse (valid/total): 246/452
Original error:
def clean_basepaths_list(a):
b = []
for x in a:
b.append(clean_basepath(x)))
return b
Good Repair:
def clean_basepaths_list(a):
b = []
for x in a:
** b.append(clean_basepath(x))
return b
Synthesized repair in: 16585ms
Tidyparse (valid/total): 247/453
Original error:
def form_invalid(self, form):
"""If the form is invalid, re-render the context data with the"""
return self.render_to_response(self.get_context_data(form = form)
Bad Repair: expression cannot contain assignment, perhaps you meant "=="? (<unknown>, line 3):
def form_invalid(self, form):
"""If the form is invalid, re-render the context data with the"""
** return self.render_to_response(self.get_context_dataform = form)
Synthesized repair in: 16140ms
Tidyparse (valid/total): 247/454
Original error:
def _parse_args():
from optparse import OptionParser
parser = OptionParser(usage = """(1) %prog [options] PATHNAME DENSITY"""
Bad Repair: unexpected EOF while parsing (<unknown>, line 3):
def _parse_args():
from optparse import OptionParser
** parser = OptionParser(usage = """1) %prog [options] PATHNAME DENSITY"""
Synthesized repair in: 25016ms
Tidyparse (valid/total): 247/455
Original error:
def get_icon(name):
path = os.path.dirname(os.path.realpath(__file__)
path = os.path.join(path, "icons/%s.png" % name)
icon = QtGui.QIcon(path)
return icon
Bad Repair: invalid syntax (<unknown>, line 3):
def get_icon(name):
path = os.path.dirname(os.path.realpath(__file__)
** path = os.path.joinpath, "icons/%s.png" % name)
icon = QtGui.QIcon(path)
return icon
Synthesized repair in: 25135ms
Tidyparse (valid/total): 247/456
Original error:
def crenameregs(fundata, items):
"""Collate legacy register names in regular C function"""
repl = regmagic.makecrepl(fundata['name']
Good Repair:
def crenameregs(fundata, items):
"""Collate legacy register names in regular C function"""
** repl = regmagic.makecreplfundata['name']
Synthesized repair in: 20313ms
Tidyparse (valid/total): 248/457
Original error:
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
model = User
def get_permissions(self):
return(AllowAny() if self.request.method == 'POST'
Bad Repair: invalid syntax (<unknown>, line 5):
class UserViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
model = User
def get_permissions(self):
** return(AllowAny) if self.request.method == 'POST'
Synthesized repair in: 18111ms
Tidyparse (valid/total): 248/458
Original error:
def __init__(self, plugin_classes = _PLUGIN_CLASSES):
scan_command_classes_to_plugin_classes = {}
for plugin_class in plugin_classes:
for scan_command_class in plugin_class.get_available_commands():
if scan_command_class in scan_command_classes_to_plugin_classes.keys():
raise KeyError('Found duplicate scan command: {}'.format(scan_command_class)
scan_command_classes_to_plugin_classes[scan_command_class] = plugin_class
self._scan_command_classes_to_plugin_classes = scan_command_classes_to_plugin_classes
Good Repair:
def __init__(self, plugin_classes = _PLUGIN_CLASSES):
scan_command_classes_to_plugin_classes = {}
for plugin_class in plugin_classes:
for scan_command_class in plugin_class.get_available_commands():
if scan_command_class in scan_command_classes_to_plugin_classes.keys():
** raise KeyError('Found duplicate scan command: {}'.formatscan_command_class)
scan_command_classes_to_plugin_classes[scan_command_class] = plugin_class
self._scan_command_classes_to_plugin_classes = scan_command_classes_to_plugin_classes
Synthesized repair in: 148482ms
Tidyparse (valid/total): 249/459
Original error:
def retranslateUi(self, DialogAbout):
DialogAbout.setWindowTitle(QtGui.QApplication.translate("DialogAbout", "About SIDD", None, QtGui.QApplication.UnicodeUTF8))
self.lb_description.setText(QtGui.QApplication.translate("DialogAbout", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, DialogAbout):
DialogAbout.setWindowTitle(QtGui.QApplication.translate("DialogAbout", "About SIDD", None, QtGui.QApplication.UnicodeUTF8))
** self.lb_description.setText(QtGui.QApplication.translate)"DialogAbout", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 38135ms
Tidyparse (valid/total): 249/460
Original error:
def from_kegg(compound_id):
return Compound.from_inchi('KEGG', compound_id,
Compound.get_inchi(compound_id)
Bad Repair: invalid syntax (<unknown>, line 2):
def from_kegg(compound_id):
** return Compound.from_inchi'KEGG', compound_id,
Compound.get_inchi(compound_id)
Synthesized repair in: 14652ms
Tidyparse (valid/total): 249/461
Original error:
class SourceFile(basic.SourceFile):
templates = dict(
string = ''' %(FileHeader)s''',
c_header = ''' #ifdef __cplusplus'''
Bad Repair: unexpected indent (<unknown>, line 3):
class SourceFile(basic.SourceFile):
** templates = dict
string = ''' %(FileHeader)s''',
c_header = ''' #ifdef __cplusplus'''
Synthesized repair in: 4355ms
Tidyparse (valid/total): 249/462
Original error:
def cksum(buf):
"""Return computed CRC-32c checksum."""
return done(add(0xffffffff, buf)
Good Repair:
def cksum(buf):
"""Return computed CRC-32c checksum."""
** return doneadd(0xffffffff, buf)
Synthesized repair in: 3870ms
Tidyparse (valid/total): 250/463
Original error:
def check_exists(fips_dir):
"""check if nacl sdk is installed"""
return os.path.isdir(get_naclsdk_dir(fips_dir)
Good Repair:
def check_exists(fips_dir):
"""check if nacl sdk is installed"""
** return os.path.isdir(get_naclsdk_dirfips_dir)
Synthesized repair in: 11170ms
Tidyparse (valid/total): 251/464
Original error:
def rastrigin_skew(variable):
"""Skewed Rastrigin test objective function."""
N = len(variable)
return 10 * N + sum((10 * x if x > 0 else x) ** 2
Good Repair:
def rastrigin_skew(variable):
"""Skewed Rastrigin test objective function."""
N = len(variable)
** return 10 * N + sum(10 * x if x > 0 else x) ** 2
Synthesized repair in: 31579ms
Tidyparse (valid/total): 252/465
Original error:
def add_arguments(self, parser):
parser.add_argument(
"-c", "--compile",
action = "store_true",
dest = "compile",
default = False,
help = "Compile the PO-files."
),
parser.add_argument(
"-t", "--pot-file",
action = "store_true",
dest = "pot-file",
default = False,
help = "Create a POT-file."
Bad Repair: unexpected indent (<unknown>, line 10):
def add_arguments(self, parser):
parser.add_argument(
"-c", "--compile",
action = "store_true",
dest = "compile",
default = False,
help = "Compile the PO-files."
),
** parser.add_argument
"-t", "--pot-file",
action = "store_true",
dest = "pot-file",
default = False,
help = "Create a POT-file."
Synthesized repair in: 8096ms
Tidyparse (valid/total): 252/466
Original error:
"""wrapper.py implements an end-to-end wrapper that classifies an image read"""
import numpy as np
import os
from skimage import io
from skimage import transform
import caffe
IMAGE_DIM = 256
CROPPED_DIM = 227
IMAGENET_MEAN = np.load(
os.path.join(os.path.dirname(__file__), 'ilsvrc_2012_mean.npy')
Good Repair:
"""wrapper.py implements an end-to-end wrapper that classifies an image read"""
import numpy as np
import os
from skimage import io
from skimage import transform
import caffe
IMAGE_DIM = 256
CROPPED_DIM = 227
IMAGENET_MEAN = np.load(
** os.path.joinos.path.dirname(__file__), 'ilsvrc_2012_mean.npy')
Synthesized repair in: 2040ms
Tidyparse (valid/total): 253/467
Original error:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
print(os.path.join(BASE_DIR, 'db.sqlite3')
Good Repair:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
** print(os.path.joinBASE_DIR, 'db.sqlite3')
Synthesized repair in: 16194ms
Tidyparse (valid/total): 254/468
Original error:
def _connected(self, link_uri):
"""Callback when the Crazyflie has been connected"""
logger.debug("Crazyflie connected to{}".format(link_uri)
Good Repair:
def _connected(self, link_uri):
"""Callback when the Crazyflie has been connected"""
** logger.debug("Crazyflie connected to{}".formatlink_uri)
Synthesized repair in: 18232ms
Tidyparse (valid/total): 255/469
Original error:
def write(filepath, data):
with open filepath, 'wb') as f:
for i in data:
f.write(i)
Bad Repair: invalid syntax (<unknown>, line 2):
** def write(filepath, data:
with open filepath, 'wb') as f:
for i in data:
f.write(i)
Synthesized repair in: 33527ms
Tidyparse (valid/total): 255/470
Original error:
def print_list(l):
"""Prints the contents of a list"""
print("{",
print(", ".join([e.__unicode__() for e in l]), )
print("}")
Bad Repair: invalid syntax (<unknown>, line 5):
def print_list(l):
"""Prints the contents of a list"""
print("{",
print(", ".join([e.__unicode__() for e in l]), )
** print"}")
Synthesized repair in: 1837608ms
Tidyparse (valid/total): 255/471
Original error:
class SmarterEncoder(jsonutils.json.JSONEncoder):
"""Help for JSON encoding dict-like objects."""
def default(self, obj):
if not isinstance(obj, dict) and hasattr(obj, 'iteritems'):
return dict(obj.iteritems()
return super(SmarterEncoder, self).default(obj)
Good Repair:
class SmarterEncoder(jsonutils.json.JSONEncoder):
"""Help for JSON encoding dict-like objects."""
def default(self, obj):
if not isinstance(obj, dict) and hasattr(obj, 'iteritems'):
** return dictobj.iteritems()
return super(SmarterEncoder, self).default(obj)
Synthesized repair in: 192489ms
Tidyparse (valid/total): 256/472
Original error:
def leftMotor(self, power):
""" Set left motor power, -1 to 1."""
if power <= 1.0 and power >= - 1.0:
self.extInstruction(0x50 + int(power * 10)
Good Repair:
def leftMotor(self, power):
""" Set left motor power, -1 to 1."""
if power <= 1.0 and power >= - 1.0:
** self.extInstruction0x50 + int(power * 10)
Synthesized repair in: 21732ms
Tidyparse (valid/total): 257/473
Original error:
def _create_vframe(text):
frame = VFrame(Label(text)
frame.spacing = 5
frame.align = ALIGN_LEFT
return frame
Good Repair:
def _create_vframe(text):
** frame = VFrameLabel(text)
frame.spacing = 5
frame.align = ALIGN_LEFT
return frame
Synthesized repair in: 23748ms
Tidyparse (valid/total): 258/474
Original error:
def retranslateUi(self, error):
error.setWindowTitle(_translate("error", "Error", None))
self.label.setText(_translate("error", "Error al realizar las cuentas. \n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, error):
error.setWindowTitle(_translate("error", "Error", None))
** self.label.setText(_translate)"error", "Error al realizar las cuentas. \n"
Synthesized repair in: 112847ms
Tidyparse (valid/total): 258/475
Original error:
def raise_if_not_match(result):
if result != 'match':
expected_diff, actual_diff = result
raise AssertionError(
"Expected %s\nBut Got %s" %(expected_diff,
actual_diff)
Bad Repair: unexpected indent (<unknown>, line 5):
def raise_if_not_match(result):
if result != 'match':
expected_diff, actual_diff = result
** raise AssertionError
"Expected %s\nBut Got %s" %(expected_diff,
actual_diff)
Synthesized repair in: 3884ms
Tidyparse (valid/total): 258/476
Original error:
def main(argv = None):
parser = ArgumentParser(description = '%s -- relabel header for pick_otu.py' %
(os.path.basename(sys.argv[0])),
epilog = 'created by Philipp Sehnert',
parser.add_argument('--minlength', type = int, dest = 'minlength', default = 150, required = True,
help = 'Drop the read if it is below a specified length')
parser.add_argument('input', nargs = '+', action = 'store',
help = 'single or paired input files in <fasta> format')
args = parser.parse_args()
Bad Repair: invalid syntax (<unknown>, line 7):
def main(argv = None):
parser = ArgumentParser(description = '%s -- relabel header for pick_otu.py' %
(os.path.basename(sys.argv[0])),
epilog = 'created by Philipp Sehnert',
parser.add_argument('--minlength', type = int, dest = 'minlength', default = 150, required = True,
help = 'Drop the read if it is below a specified length')
parser.add_argument('input', nargs = '+', action = 'store',
help = 'single or paired input files in <fasta> format')
** args = parser.parse_args)
Synthesized repair in: 51208ms
Tidyparse (valid/total): 258/477
Original error:
def __init__(self, filename):
with open(filename, 'r') as fd:
self._parse(fd.readlines()
Good Repair:
def __init__(self, filename):
with open(filename, 'r') as fd:
** self._parsefd.readlines()
Synthesized repair in: 70854ms
Tidyparse (valid/total): 259/478
Original error:
def api_root(request, format = None):
return Response({
'content_template': reverse('content-template-list', request = request, format = format)
Bad Repair: invalid syntax (<unknown>, line 3):
def api_root(request, format = None):
return Response({
** 'content_template': reverse}'content-template-list', request = request, format = format)
Synthesized repair in: 19311ms
Tidyparse (valid/total): 259/479
Original error:
from __future__ import unicode_literals, print_function, absolute_import
from decimal import Decimal
import os.path
import re
from django.utils.translation import ugettext_lazy as _
import environ
env = environ.Env()
BASE = os.path.dirname(os.path.abspath(__file__)))
Good Repair:
from __future__ import unicode_literals, print_function, absolute_import
from decimal import Decimal
import os.path
import re
from django.utils.translation import ugettext_lazy as _
import environ
env = environ.Env()
** BASE = os.path.dirname(os.path.abspath(__file__))
Synthesized repair in: 3093ms
Tidyparse (valid/total): 260/480
Original error:
def m1():
something)
a.Get().Foo()
Bad Repair: invalid syntax (<unknown>, line 1):
** def m1(:
something)
a.Get().Foo()
Synthesized repair in: 6678ms
Tidyparse (valid/total): 260/481
Original error:
def __init__(self, entry, left = empty, right = empty):
for branch in(left, right):
assert isinstance(branch, BinaryTree) or branch.is_empty
Tree.__init__(self, entry, (left, right)
self.is_empty = False
Good Repair:
def __init__(self, entry, left = empty, right = empty):
for branch in(left, right):
assert isinstance(branch, BinaryTree) or branch.is_empty
** Tree.__init__self, entry, (left, right)
self.is_empty = False
Synthesized repair in: 182715ms
Tidyparse (valid/total): 261/482
Original error:
def OnDblClick(self, shift):
"""User dbl-clicked in the view"""
word = self.GetCurrentWord()
if not word: word = "<None>"
print("OnDblClick, shift=%d, current word=%s" %(shift, word)
return True
Good Repair:
def OnDblClick(self, shift):
"""User dbl-clicked in the view"""
word = self.GetCurrentWord()
if not word: word = "<None>"
** print("OnDblClick, shift=%d, current word=%s" %shift, word)
return True
Synthesized repair in: 43758ms
Tidyparse (valid/total): 262/483
Original error:
def test_get_schema_names(self):
insp = inspect(testing.db)
self.assert_(testing.config.test_schema in insp.get_schema_names()
Good Repair:
def test_get_schema_names(self):
insp = inspect(testing.db)
** self.assert_(testing.config.test_schema in insp.get_schema_names)
Synthesized repair in: 14551ms
Tidyparse (valid/total): 263/484
Original error:
def create_tax(self, name, amount):
return self.env['account.tax'].create({
'name': name,
'amount': amount
Bad Repair: unexpected indent (<unknown>, line 3):
def create_tax(self, name, amount):
** return self.env['account.tax'].create()
'name': name,
'amount': amount
Synthesized repair in: 49860ms
Tidyparse (valid/total): 263/485
Original error:
x = int(input())
m1 = m2 = m3 = - 100000
while x != 0:
if x > m1:
m1, m2, m3 = x, m1, m2
m1_n, m2_n, m3_n = 1, m1_n, m2_n
elif x == m1:
m1_n += 1
elif x > m2:
m2, m3 = x, m2
m2_n, m3_n = 1, m2_n
elif x == m2:
m2_n += 1
elif x > m3:
m3 = x
m3_n = 1
elif x == m3:
m3_n += 1
x = int(input
Good Repair:
x = int(input())
m1 = m2 = m3 = - 100000
while x != 0:
if x > m1:
m1, m2, m3 = x, m1, m2
m1_n, m2_n, m3_n = 1, m1_n, m2_n
elif x == m1:
m1_n += 1
elif x > m2:
m2, m3 = x, m2
m2_n, m3_n = 1, m2_n
elif x == m2:
m2_n += 1
elif x > m3:
m3 = x
m3_n = 1
elif x == m3:
m3_n += 1
** x = intinput
Synthesized repair in: 3021ms
Tidyparse (valid/total): 264/486
Original error:
__author__ = 'Jason'
import os, re, csv, ast, csv
import math
import jinja2
jinja_environment = jinja2.Environment(autoescape = True, loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))
import flask
from features import attr_str2dict
from utils import *
MAX_MONTH = 1000
Good Repair:
__author__ = 'Jason'
import os, re, csv, ast, csv
import math
import jinja2
** jinja_environment = jinja2.Environment(autoescape = True, loader = jinja2.FileSystemLoader(os.path.join(os.path.dirname__file__), 'templates'))
import flask
from features import attr_str2dict
from utils import *
MAX_MONTH = 1000
Synthesized repair in: 12652ms
Tidyparse (valid/total): 265/487
Original error:
from django.conf.urls import patterns
from django.conf.urls import url
from api import DStatCSVEndpoint
urlpatterns = patterns('', url(r'^log.csv$', DStatCSVEndpoint.as_view())
Bad Repair: invalid syntax (<unknown>, line 4):
from django.conf.urls import patterns
from django.conf.urls import url
from api import DStatCSVEndpoint
** urlpatterns = patterns('', urlr'^log.csv$', DStatCSVEndpoint.as_view())
Synthesized repair in: 4528ms
Tidyparse (valid/total): 265/488
Original error:
def unknown_endtag(self, tag):
if tag not in self.elements_no_end_tag:
self.pieces.append("</%(tag)s>" % locals()
Good Repair:
def unknown_endtag(self, tag):
if tag not in self.elements_no_end_tag:
** self.pieces.append("</%(tag)s>" % locals)
Synthesized repair in: 11539ms
Tidyparse (valid/total): 266/489
Original error:
def retranslateUi(self, pdfsearchDialog):
pdfsearchDialog.setWindowTitle(QtGui.QApplication.translate("pdfsearchDialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.pdfListWidget.setToolTip(QtGui.QApplication.translate("pdfsearchDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, pdfsearchDialog):
pdfsearchDialog.setWindowTitle(QtGui.QApplication.translate("pdfsearchDialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
** self.pdfListWidget.setToolTip(QtGui.QApplication.translate)"pdfsearchDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 97206ms
Tidyparse (valid/total): 266/490
Original error:
def add_tag(self, key, tags):
for t in tags:
self.tags_lookup.setdefault(t, set().add(key)
Good Repair:
def add_tag(self, key, tags):
for t in tags:
** self.tags_lookup.setdefault(t, set().addkey)
Synthesized repair in: 4504ms
Tidyparse (valid/total): 267/491
Original error:
[[[cog
import sys
sys.path.append('/opt/robocomp/python')
import cog
Bad Repair: invalid syntax (<unknown>, line 3):
** cog
import sys
** sys.path.append[]'/opt/robocomp/python'(
import cog
** )
Synthesized repair in: 20848ms
Tidyparse (valid/total): 267/492
Original error:
def register_snippet_source(self, name, snippet_source):
"""Registers a new 'snippet_source' with the given 'name'.The given"""
self._snippet_sources.append((name, snippet_source)
Good Repair:
def register_snippet_source(self, name, snippet_source):
"""Registers a new 'snippet_source' with the given 'name'.The given"""
** self._snippet_sources.append(name, snippet_source)
Synthesized repair in: 4131ms
Tidyparse (valid/total): 268/493
Original error:
def get_privatekey_from_string(string):
"""Returns the private key from the contents of this string"""
leap_assert(string, "We need something to load")
pkey = None
try:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, string)
except Exception as e:
logger.error("Something went wrong while loading the certificate: %r"
%(e, )
return pkey
Bad Repair: invalid syntax (<unknown>, line 8):
def get_privatekey_from_string(string):
"""Returns the private key from the contents of this string"""
leap_assert(string, "We need something to load")
pkey = None
try:
pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, string)
except Exception as e:
** logger.error"Something went wrong while loading the certificate: %r"
%(e, )
return pkey
Synthesized repair in: 68451ms
Tidyparse (valid/total): 268/494
Original error:
def _can_exit(self, dest):
if self._saved == False: return self.can_exit(dest))
return True
Good Repair:
def _can_exit(self, dest):
** if self._saved == False: return self.can_exit(dest)
return True
Synthesized repair in: 6182ms
Tidyparse (valid/total): 269/495
Original error:
def log_time_info(self, text = ""):
t, d, e = self.gettime3()
print("==> %s%9.3fs%9.3fs %s" %(t, d, e, text)
Bad Repair: invalid syntax (<unknown>, line 3):
def log_time_info(self, text = ""):
t, d, e = self.gettime3()
** print"==> %s%9.3fs%9.3fs %s" %(t, d, e, text)
Synthesized repair in: 18758ms
Tidyparse (valid/total): 269/496
Original error:
import abelfunctions
import getopt
import sys
import unittest
import warnings
exec(open('abelfunctions/version.py').read()
Good Repair:
import abelfunctions
import getopt
import sys
import unittest
import warnings
** execopen('abelfunctions/version.py').read()
Synthesized repair in: 3265ms
Tidyparse (valid/total): 270/497
Original error:
def get_island(self, point):
"""Returns the island for that coordinate.If none is found, returns None."""
return self.island_map.get(point.to_tuple()
Good Repair:
def get_island(self, point):
"""Returns the island for that coordinate.If none is found, returns None."""
** return self.island_map.get(point.to_tuple)
Synthesized repair in: 4114ms
Tidyparse (valid/total): 271/498
Original error:
def damage(self, dmg):
self.hp = max(0, self.hp - int(dmg)
if not self.hp:
self.kill()
return True
else:
return False
Good Repair:
def damage(self, dmg):
** self.hp = max0, self.hp - int(dmg)
if not self.hp:
self.kill()
return True
else:
return False
Synthesized repair in: 6696ms
Tidyparse (valid/total): 272/499
Original error:
from datetime import datetime
from flask import(
Blueprint
)
from flask import current_app, g, redirect, url_for, request, abort
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.menu import MenuLink
< % if(package.flask.sqlalchemy){% >
from flask_admin.contrib.sqla import ModelView
from < %= package.pythonName % >.models.user import User
Bad Repair: invalid syntax (<unknown>, line 8):
from datetime import datetime
from flask import(
Blueprint
)
from flask import current_app, g, redirect, url_for, request, abort
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.menu import MenuLink
** < % if(package.flask.sqlalchemy)% >
from flask_admin.contrib.sqla import ModelView
from < %= package.pythonName % >.models.user import User
Synthesized repair in: 4840ms
Tidyparse (valid/total): 272/500
Original error:
class HTTPError(Exception):
"""Exception thrown for an unsuccessful HTTP request."""
def __init__(self, code, message = None, response = None):
self.code = code
message = message or httplib.responses.get(code, "Unknown")
self.response = response
Exception.__init__(self, "HTTP %d: %s" %(self.code, message)
Good Repair:
class HTTPError(Exception):
"""Exception thrown for an unsuccessful HTTP request."""
def __init__(self, code, message = None, response = None):
self.code = code
message = message or httplib.responses.get(code, "Unknown")
self.response = response
** Exception.__init__(self, "HTTP %d: %s" %self.code, message)
Synthesized repair in: 16030ms
Tidyparse (valid/total): 273/501
Original error:
def get_items(self):
if self.fields is None:
self.fields = AusPatAdapter.__scrape_auspat_response(self.get_response()
return self.fields
Good Repair:
def get_items(self):
if self.fields is None:
** self.fields = AusPatAdapter.__scrape_auspat_responseself.get_response()
return self.fields
Synthesized repair in: 5851ms
Tidyparse (valid/total): 274/502
Original error:
def switch_12(myValue):
r = random()
return{
"1": "liar",
"2": "22",
"3": "liar" if r < 0.3 else "15",
"4": "liar" if r < 0.3 else "15",
"5": "15",
"*": "15"
Bad Repair: invalid syntax (<unknown>, line 4):
def switch_12(myValue):
r = random()
** return
"1": "liar",
"2": "22",
"3": "liar" if r < 0.3 else "15",
"4": "liar" if r < 0.3 else "15",
"5": "15",
"*": "15"
Synthesized repair in: 6722ms
Tidyparse (valid/total): 274/503
Original error:
def lookup_bus_index(self, bus_name):
for index, bus in enumerate(self.valid_buses():
if bus_name == bus.name:
return index
return None
Good Repair:
def lookup_bus_index(self, bus_name):
** for index, bus in enumerateself.valid_buses():
if bus_name == bus.name:
return index
return None
Synthesized repair in: 3077ms
Tidyparse (valid/total): 275/504
Original error:
def get_infos(self):
"""Returns a dict full of key/value string pairs with information about"""
return self.ctl.info_storage_volume(self.storage_pool,
self.getfilename()
Good Repair:
def get_infos(self):
"""Returns a dict full of key/value string pairs with information about"""
return self.ctl.info_storage_volume(self.storage_pool,
** self.getfilename)
Synthesized repair in: 3890ms
Tidyparse (valid/total): 276/505
Original error:
def _fill_bones_section(bone_list):
"""Fills up "Bones" section."""
section = _SectionData("Bones")
for bone in bone_list:
section.data.append(("__string__", bone.name)
return section
Good Repair:
def _fill_bones_section(bone_list):
"""Fills up "Bones" section."""
section = _SectionData("Bones")
for bone in bone_list:
** section.data.append("__string__", bone.name)
return section
Synthesized repair in: 24067ms
Tidyparse (valid/total): 277/506
Original error:
class LoaderResult(object):
ERROR_NOT_FOUND = 'not_found'
ERROR_UPSTREAM = 'upstream'
ERROR_TIMEOUT = 'timeout'
def __init__(self, buffer = None, successful = True, error = None, metadata = dict():
''': param buffer: The media buffer'''
self.buffer = buffer
self.successful = successful
self.error = error
self.metadata = metadata
Good Repair:
class LoaderResult(object):
ERROR_NOT_FOUND = 'not_found'
ERROR_UPSTREAM = 'upstream'
ERROR_TIMEOUT = 'timeout'
** def __init__(self, buffer = None, successful = True, error = None, metadata = dict):
''': param buffer: The media buffer'''
self.buffer = buffer
self.successful = successful
self.error = error
self.metadata = metadata
Synthesized repair in: 2577ms
Tidyparse (valid/total): 278/507
Original error:
def get_shortest_paths(self, src, to_list):
d = []
for dst in to_list:
d.append(self.get_shortest_path(src, dst)
return d
Good Repair:
def get_shortest_paths(self, src, to_list):
d = []
for dst in to_list:
** d.append(self.get_shortest_pathsrc, dst)
return d
Synthesized repair in: 5578ms
Tidyparse (valid/total): 279/508
Original error:
def get_total_score(tag):
try:
return sum(tag.scores.values()
except:
return 0
Good Repair:
def get_total_score(tag):
try:
** return sum(tag.scores.values)
except:
return 0
Synthesized repair in: 3858ms
Tidyparse (valid/total): 280/509
Original error:
def retranslateUi(self, MetadataBulkDialog):
MetadataBulkDialog.setWindowTitle(_("Edit Meta information"))
self.label_2.setText(_("&Author(s): "))
self.auto_author_sort.setToolTip(_("This will cause the author sort field to be automatically updated\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, MetadataBulkDialog):
MetadataBulkDialog.setWindowTitle(_("Edit Meta information"))
self.label_2.setText(_("&Author(s): "))
** self.auto_author_sort.setToolTip(_)"This will cause the author sort field to be automatically updated\n"
Synthesized repair in: 278560ms
Tidyparse (valid/total): 280/510
Original error:
def isConnected(self):
""" Returns True if this object has a TWS connection."""
return bool(self.connection and self.connection.isConnected()
Good Repair:
def isConnected(self):
""" Returns True if this object has a TWS connection."""
** return bool(self.connection and self.connection.isConnected)
Synthesized repair in: 6671ms
Tidyparse (valid/total): 281/511
Original error:
def main():
snmp_data = snmp.helper.snmp_get_oid_v3(pynet_rtr2, snmp_user, '1.3.6.1.4.1.9.9.43.1.1.1.0'
print(snmp_data)
Good Repair:
def main():
** snmp_data = snmp.helper.snmp_get_oid_v3pynet_rtr2, snmp_user, '1.3.6.1.4.1.9.9.43.1.1.1.0'
print(snmp_data)
Synthesized repair in: 2368ms
Tidyparse (valid/total): 282/512
Original error:
def is_connected(host, user = None, remote_user = None):
"""Determines whether there is an active connection to a host as a specific"""
for conn in _connections:
if conn.host == host:
if((user is None or user == conn.local_user) and
(remote_user is None or remote_user == conn.remote_user):
return True
return False
Bad Repair: invalid syntax (<unknown>, line 5):
def is_connected(host, user = None, remote_user = None):
"""Determines whether there is an active connection to a host as a specific"""
for conn in _connections:
if conn.host == host:
** if(user is None or user == conn.local_user) and
(remote_user is None or remote_user == conn.remote_user):
return True
return False
Synthesized repair in: 12039ms
Tidyparse (valid/total): 282/513
Original error:
def merge(cls, ws_list):
"""Merge a set of WeightedSequence objects."""
return sum(ws_list, cls()
Good Repair:
def merge(cls, ws_list):
"""Merge a set of WeightedSequence objects."""
** return sum(ws_list, cls)
Synthesized repair in: 3837ms
Tidyparse (valid/total): 283/514
Original error:
"""WSGI config for cobble project."""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cobble.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application()
Good Repair:
"""WSGI config for cobble project."""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cobble.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
** application = Clingget_wsgi_application()
Synthesized repair in: 6476ms
Tidyparse (valid/total): 284/515
Original error:
def Can_render_function_passed_as_arg__test():
assert_rendered_program_equals(
"""int fn1( int unused, double n );""",
"""import sys"""
Bad Repair: unexpected indent (<unknown>, line 3):
def Can_render_function_passed_as_arg__test():
** assert_rendered_program_equals
"""int fn1( int unused, double n );""",
"""import sys"""
Synthesized repair in: 8538ms
Tidyparse (valid/total): 284/516
Original error:
def version(self):
"""Print database's current migration level"""
print(migration.db_version(db_api.get_engine(),
db_migration.MIGRATE_REPO_PATH,
db_migration.INIT_VERSION)
Good Repair:
def version(self):
"""Print database's current migration level"""
** printmigration.db_version(db_api.get_engine(),
db_migration.MIGRATE_REPO_PATH,
db_migration.INIT_VERSION)
Synthesized repair in: 16797ms
Tidyparse (valid/total): 285/517
Original error:
def tags(self):
"""Tags for this item."""
return iter(self._item.tags()
Good Repair:
def tags(self):
"""Tags for this item."""
** return iter(self._item.tags)
Synthesized repair in: 12137ms
Tidyparse (valid/total): 286/518
Original error:
def test_validate_ok(self):
tc = cluster.TroveCluster('cluster', self.rsrc_defn, self.stack)
self.assertIsNone(tc.validate()
Good Repair:
def test_validate_ok(self):
tc = cluster.TroveCluster('cluster', self.rsrc_defn, self.stack)
** self.assertIsNonetc.validate()
Synthesized repair in: 14710ms
Tidyparse (valid/total): 287/519
Original error:
def api_value(self, value):
from.base import BaseApiModel
values = super(ManyToManyField, self).api_value(value)
for i in range(len(values):
if isinstance(value, BaseApiModel):
value = value.get_pk()
values[i] = value
return values
Bad Repair: invalid syntax (<unknown>, line 4):
def api_value(self, value):
from.base import BaseApiModel
values = super(ManyToManyField, self).api_value(value)
for i in range(len(values):
** if isinstancevalue, BaseApiModel):
value = value.get_pk()
values[i] = value
return values
Synthesized repair in: 245855ms
Tidyparse (valid/total): 287/520
Original error:
def testBasic2(self):
smtp = smtplib.SMTP("%s: %s" %(HOST, self.port)
smtp.close()
Bad Repair: invalid syntax (<unknown>, line 2):
def testBasic2(self):
** smtp = smtplib.SMTP"%s: %s" %(HOST, self.port)
smtp.close()
Synthesized repair in: 13460ms
Tidyparse (valid/total): 287/521
Original error:
def current_price(self):
"""Return the current price object for an item."""
return self.price_at(datetime.utcnow()
Good Repair:
def current_price(self):
"""Return the current price object for an item."""
** return self.price_at(datetime.utcnow)
Synthesized repair in: 17855ms
Tidyparse (valid/total): 288/522
Original error:
class SizesType(models.Model):
dressSize = DressSizeTypeField("dressSize", null = True)
mediumDressSize = MediumDressSizeTypeField("mediumDressSize", null = True)
smallDressSize = SmallDressSizeTypeField("smallDressSize", null = True)
smlxSize = SMLXSizeTypeField(
"small\n"
Bad Repair: unexpected indent (<unknown>, line 6):
class SizesType(models.Model):
dressSize = DressSizeTypeField("dressSize", null = True)
mediumDressSize = MediumDressSizeTypeField("mediumDressSize", null = True)
smallDressSize = SmallDressSizeTypeField("smallDressSize", null = True)
** smlxSize = SMLXSizeTypeField
"small\n"
Synthesized repair in: 100668ms
Tidyparse (valid/total): 288/523
Original error:
def usage():
print('Usage: ', argv[
0], '[--truncate-mprecision 0.95 | --ignore-class name_of_reject_class ] < matrices.cmat'
Bad Repair: invalid syntax (<unknown>, line 2):
def usage():
** print'Usage: ', argv[
0], '[--truncate-mprecision 0.95 | --ignore-class name_of_reject_class ] < matrices.cmat'
Synthesized repair in: 27703ms
Tidyparse (valid/total): 288/524
Original error:
def get_mathjax_header(https = False):
"""Return the snippet of HTML code to put in HTML HEAD tag, in order to"""
if CFG_MATHJAX_HOSTING.lower() == 'cdn':
if https:
mathjax_path = "https://d3eoax9i5htok0.cloudfront.net/mathjax/1.1-latest"
else:
mathjax_path = "http://cdn.mathjax.org/mathjax/1.1-latest"
else:
mathjax_path = "/MathJax"
return """<script type="text/x-mathjax-config">""" %{
'mathjax_path': mathjax_path
Bad Repair: invalid syntax (<unknown>, line 10):
def get_mathjax_header(https = False):
"""Return the snippet of HTML code to put in HTML HEAD tag, in order to"""
if CFG_MATHJAX_HOSTING.lower() == 'cdn':
if https:
mathjax_path = "https://d3eoax9i5htok0.cloudfront.net/mathjax/1.1-latest"
else:
mathjax_path = "http://cdn.mathjax.org/mathjax/1.1-latest"
else:
mathjax_path = "/MathJax"
** return """<script type="text/x-mathjax-config">""" %
'mathjax_path': mathjax_path
Synthesized repair in: 27641ms
Tidyparse (valid/total): 288/525
Original error:
def json_error_response(error_message):
return HttpResponse(simplejson.dumps(dict(success = False,
error_message = error_message))
Good Repair:
def json_error_response(error_message):
** return HttpResponse(simplejson.dumps(dictsuccess = False,
error_message = error_message))
Synthesized repair in: 5373ms
Tidyparse (valid/total): 289/526
Original error:
def make_models_improve():
with open("core/modesl.py", 'a') as f:
f.write("""from django.db.models.signals import post_save"""
Bad Repair: invalid syntax (<unknown>, line 3):
def make_models_improve():
with open("core/modesl.py", 'a') as f:
** f.write"""from django.db.models.signals import post_save"""
Synthesized repair in: 6538ms
Tidyparse (valid/total): 289/527
Original error:
def get_favorite_list(self):
if not self._favorite_list:
self._favorite_list = FavoriteList(os.path.join(self._get_cache_path(), 'favorites')
pass
return self._favorite_list
Good Repair:
def get_favorite_list(self):
if not self._favorite_list:
** self._favorite_list = FavoriteList(os.path.joinself._get_cache_path(), 'favorites')
pass
return self._favorite_list
Synthesized repair in: 5273ms
Tidyparse (valid/total): 290/528
Original error:
def load_config():
jo = json.load(open(path + '/config.json')
return jo
Good Repair:
def load_config():
** jo = json.load(openpath + '/config.json')
return jo
Synthesized repair in: 17901ms
Tidyparse (valid/total): 291/529
Original error:
def sqs(self):
if self._sqs is None:
self._sqs = self._aws_connect_to(SQSConnection, _sqs.regions()
return self._sqs
Good Repair:
def sqs(self):
if self._sqs is None:
** self._sqs = self._aws_connect_to(SQSConnection, _sqs.regions)
return self._sqs
Synthesized repair in: 8616ms
Tidyparse (valid/total): 292/530
Original error:
def tmtuple(tmsecs = None):
""" Return a time tuple."""
if - 86400 <= tmsecs <= 86400:
tmsecs = 0
return time.gmtime(tmsecs or time.time()
Good Repair:
def tmtuple(tmsecs = None):
""" Return a time tuple."""
if - 86400 <= tmsecs <= 86400:
tmsecs = 0
** return time.gmtimetmsecs or time.time()
Synthesized repair in: 8082ms
Tidyparse (valid/total): 293/531
Original error:
def serialize(cls, value, * args, ** kwargs):
if value is None:
return ''
return types.UnicodeType(value.isoformat()
Good Repair:
def serialize(cls, value, * args, ** kwargs):
if value is None:
return ''
** return types.UnicodeType(value.isoformat)
Synthesized repair in: 6001ms
Tidyparse (valid/total): 294/532
Original error:
import csv
patent_info = {"feature": [abstract, number, inventor, phone, [litigation, listt]}
say its highly litigated, or lowly litigated, you know.Say that analytic for a patent
view similarly litigated patents
yeah all that
Bad Repair: invalid syntax (<unknown>, line 3):
import csv
** patent_info = {"feature": [abstract, number, inventor, phone, litigation, listt]}
say its highly litigated, or lowly litigated, you know.Say that analytic for a patent
view similarly litigated patents
yeah all that
Synthesized repair in: 2955ms
Tidyparse (valid/total): 294/533
Original error:
def test_ToEPCTagUri(self):
print("***==== Test To EPC Tag Uri Value ====***"
epc = self._grai96.encode(self._companyPrefix, None, self._assetType, self._filter, self._serialNumber)
print(epc.toEPCTagUri())
print("***==== END Test To EPC Tag Uri Value ====***"
print(""
Bad Repair: invalid syntax (<unknown>, line 3):
def test_ToEPCTagUri(self):
print("***==== Test To EPC Tag Uri Value ====***"
epc = self._grai96.encode(self._companyPrefix, None, self._assetType, self._filter, self._serialNumber)
** print(epc.toEPCTagUri))
print("***==== END Test To EPC Tag Uri Value ====***"
** print)""
Synthesized repair in: 773062ms
Tidyparse (valid/total): 294/534
Original error:
def main():
limit = 28123
print(sum_of_non_abundant_integers(limit)
Good Repair:
def main():
limit = 28123
** printsum_of_non_abundant_integers(limit)
Synthesized repair in: 6558ms
Tidyparse (valid/total): 295/535
Original error:
import datajoint as dj
import pandas as pd
from.import mice
import numpy as np
from distutils.version import StrictVersion
import os
from commons import lab
assert StrictVersion(dj.__version__) >= StrictVersion('0.2.7')
schema = dj.schema('pipeline_experiment', locals()
Good Repair:
import datajoint as dj
import pandas as pd
from.import mice
import numpy as np
from distutils.version import StrictVersion
import os
from commons import lab
assert StrictVersion(dj.__version__) >= StrictVersion('0.2.7')
** schema = dj.schema('pipeline_experiment', locals)
Synthesized repair in: 58372ms
Tidyparse (valid/total): 296/536
Original error:
def reload(self):
if not self.config_file:
return
self.update(self.load()
Good Repair:
def reload(self):
if not self.config_file:
return
** self.update(self.load)
Synthesized repair in: 11887ms
Tidyparse (valid/total): 297/537
Original error:
def scale(self, alpha):
"""Returns the scalar-vector product of self vector with the specified scalar."""
SparseVector c = new SparseVector(self._d)
for(int i: self.self._st.keys(): c.put(i, alpha * self.get(i))
return c
Bad Repair: invalid syntax (<unknown>, line 3):
def scale(self, alpha):
"""Returns the scalar-vector product of self vector with the specified scalar."""
SparseVector c = new SparseVector(self._d)
** for(int i: self.self._st.keys(): c.puti, alpha * self.get(i))
return c
Synthesized repair in: 19656ms
Tidyparse (valid/total): 297/538
Original error:
def subjects(request):
return{
'subjects': Subject.objects.all()
Bad Repair: illegal target for annotation (<unknown>, line 3):
def subjects(request):
** return
'subjects': Subject.objects.all()
Synthesized repair in: 3909ms
Tidyparse (valid/total): 297/539
Original error:
class Setup:
def __init__(self, r):
r.metric(MUX()
Good Repair:
class Setup:
def __init__(self, r):
** r.metric(MUX)
Synthesized repair in: 2870ms
Tidyparse (valid/total): 298/540
Original error:
def _compose_url(self, location):
"""Generate API URL."""
query = {
'street': location,
'candidates': self.candidates
}
return '?'.join((
self.api,
"&".join(("=".join(('auth-token', self.auth_token)), urlencode(query)))
Bad Repair: unexpected indent (<unknown>, line 8):
def _compose_url(self, location):
"""Generate API URL."""
query = {
'street': location,
'candidates': self.candidates
}
** return '?'.join()
self.api,
"&".join(("=".join(('auth-token', self.auth_token)), urlencode(query)))
Synthesized repair in: 160119ms
Tidyparse (valid/total): 298/541
Original error:
def __init__(self, ** kwargs):
self.url = "http: //yourewinner.com/"
self.api = xmlrpclib.ServerProxy(self.url + "mobiquo/mobiquo.php", transport = RequestsTransport()
self.logged_in = False
self.session_id = None
self.session_var = None
self.session = RequestsTransport.session
Good Repair:
def __init__(self, ** kwargs):
self.url = "http: //yourewinner.com/"
** self.api = xmlrpclib.ServerProxy(self.url + "mobiquo/mobiquo.php", transport = RequestsTransport)
self.logged_in = False
self.session_id = None
self.session_var = None
self.session = RequestsTransport.session
Synthesized repair in: 6256ms
Tidyparse (valid/total): 299/542
Original error:
"""pyxt.nmi_mask - Non-maskable interrupt mask register...really."""
from six.moves import range
from pyxt.bus import Device
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler()
Good Repair:
"""pyxt.nmi_mask - Non-maskable interrupt mask register...really."""
from six.moves import range
from pyxt.bus import Device
import logging
log = logging.getLogger(__name__)
** log.addHandler(logging.NullHandler)
Synthesized repair in: 3953ms
Tidyparse (valid/total): 300/543
Original error:
from distutils.core import setup
from Cython.Build import cythonize
import os
from sys import platform
if platform.lower() == 'darwin':
os.environ['CC'] = 'gcc-5'
setup(ext_modules = cythonize('userB.pyx')
Bad Repair: invalid syntax (<unknown>, line 7):
from distutils.core import setup
from Cython.Build import cythonize
import os
from sys import platform
if platform.lower() == 'darwin':
os.environ['CC'] = 'gcc-5'
** setup(ext_modules = cythonize'userB.pyx')
Synthesized repair in: 18432ms
Tidyparse (valid/total): 300/544
Original error:
def default_key_expiration():
"""Returns the default number of seconds a key should"""
return int(get_settings_option("memcached_default_key_expiration", default = 86400)
Good Repair:
def default_key_expiration():
"""Returns the default number of seconds a key should"""
** return intget_settings_option("memcached_default_key_expiration", default = 86400)
Synthesized repair in: 11464ms
Tidyparse (valid/total): 301/545
Original error:
class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('park', 'objectionable_content')
widgets = dict(rating = forms.RadioSelect()
Good Repair:
class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('park', 'objectionable_content')
** widgets = dictrating = forms.RadioSelect()
Synthesized repair in: 17114ms
Tidyparse (valid/total): 302/546
Original error:
def run_while_true(server_class = BaseHTTPServer.HTTPServer, handler_class = BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('',
httpd = server_class(server_address, handler_class)
while True:
httpd.handle_request()
Bad Repair: invalid syntax (<unknown>, line 3):
def run_while_true(server_class = BaseHTTPServer.HTTPServer, handler_class = BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('',
** httpd = server_classserver_address, handler_class)
while True:
httpd.handle_request()
Synthesized repair in: 5611ms
Tidyparse (valid/total): 302/547
Original error:
import re
import sys
import os.path
from textwrap import TextWrapper
try:
from lxml import etree
except ImportError:
sys.stderr.write("Please install lxml to run this script.")
sys.exit(1)
DEPRECATED_COMMANDS = ["volume"]
SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__)
Good Repair:
import re
import sys
import os.path
from textwrap import TextWrapper
try:
from lxml import etree
except ImportError:
sys.stderr.write("Please install lxml to run this script.")
sys.exit(1)
DEPRECATED_COMMANDS = ["volume"]
** SCRIPT_PATH = os.path.dirnameos.path.realpath(__file__)
Synthesized repair in: 120506ms
Tidyparse (valid/total): 303/548
Original error:
def _install_trace():
global _trace_thread_count
sys.setprofile(_thread_trace_func(_trace_thread_count)
_trace_thread_count += 1
Good Repair:
def _install_trace():
global _trace_thread_count
** sys.setprofile(_thread_trace_func_trace_thread_count)
_trace_thread_count += 1
Synthesized repair in: 18180ms
Tidyparse (valid/total): 304/549
Original error:
def get_floating_ip(self, context, id):
"""Returns a floating IP as a dict."""
return dict(floating_ip_obj.FloatingIP.get_by_id(
context, id).iteritems()
Good Repair:
def get_floating_ip(self, context, id):
"""Returns a floating IP as a dict."""
return dict(floating_ip_obj.FloatingIP.get_by_id(
** context, id).iteritems)
Synthesized repair in: 6280ms
Tidyparse (valid/total): 305/550
Original error:
def create_url(self, anchor):
"""Helper method to create URL back to document"""
file_path = self.file_being_used.replace(self.info['download_path'], '')
return self.info['doc_base_url'].format('{}{}'.format(file_path, anchor)
Bad Repair: invalid syntax (<unknown>, line 4):
def create_url(self, anchor):
"""Helper method to create URL back to document"""
file_path = self.file_being_used.replace(self.info['download_path'], '')
** return self.info['doc_base_url'].format'{}{}'.format(file_path, anchor)
Synthesized repair in: 357989ms
Tidyparse (valid/total): 305/551
Original error:
def get_properties(self):
return{
"full-path": self.full_path,
"date-created": self.created_on,
"date-modified": self.last_modified,
"date-accessed": self.last_accessed
})
Good Repair:
def get_properties(self):
return{
"full-path": self.full_path,
"date-created": self.created_on,
"date-modified": self.last_modified,
"date-accessed": self.last_accessed
** }
Synthesized repair in: 6813ms
Tidyparse (valid/total): 306/552
Original error:
class osx_install_data(install_data):
def finalize_options(self):
self.set_undefined_options('install', ('install_lib', 'install_dir')
install_data.finalize_options(self)
Bad Repair: invalid syntax (<unknown>, line 3):
class osx_install_data(install_data):
def finalize_options(self):
** self.set_undefined_options'install', ('install_lib', 'install_dir')
install_data.finalize_options(self)
Synthesized repair in: 9493ms
Tidyparse (valid/total): 306/553
Original error:
def main():
import sys
print(len(sys.argv)
Good Repair:
def main():
import sys
** print(lensys.argv)
Synthesized repair in: 11636ms
Tidyparse (valid/total): 307/554
Original error:
def upgrade():
op.add_column('messages', sa.Column('msg_id', sa.UnicodeText, nullable = True,
unique = True, default = None)
pass
Bad Repair: invalid syntax (<unknown>, line 2):
def upgrade():
** op.add_column('messages', sa.Column'msg_id', sa.UnicodeText, nullable = True,
unique = True, default = None)
pass
Synthesized repair in: 14242ms
Tidyparse (valid/total): 307/555
Original error:
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils import json
hosts = ["10.11.12.66"]
example_inventory = ansible.inventory.Inventory(hosts)
pm = ansible.runner.Runner(
module_name = 'command',
module_args = 'uname -a',
timeout = 5,
inventory = example_inventory,
subset = 'all'
out = pm.run()
Bad Repair: invalid syntax (<unknown>, line 5):
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils import json
hosts = ["10.11.12.66"]
example_inventory = ansible.inventory.Inventory(hosts)
** pm = ansible.runner.Runner
module_name = 'command',
module_args = 'uname -a',
timeout = 5,
inventory = example_inventory,
subset = 'all'
out = pm.run()
Synthesized repair in: 33463ms
Tidyparse (valid/total): 307/556
Original error:
def Now_evaluates_now_but_otherwise_not__test():
"""If we render some stuff that could be evaluated at"""
assert_rendered_program_equals(
r"""#include <stdio.h>""",
"""print( 3 * 2 )"""
Bad Repair: unexpected EOF while parsing (<unknown>, line 5):
def Now_evaluates_now_but_otherwise_not__test():
"""If we render some stuff that could be evaluated at"""
assert_rendered_program_equals(
r"""#include <stdio.h>""",
** """print 3 * 2 )"""
Synthesized repair in: 10336ms
Tidyparse (valid/total): 307/557
Original error:
import logging
from os.path import basename
from.Qt import QtCore, QtGui
from..experiment import Procedure
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler()
Good Repair:
import logging
from os.path import basename
from.Qt import QtCore, QtGui
from..experiment import Procedure
log = logging.getLogger(__name__)
** log.addHandlerlogging.NullHandler()
Synthesized repair in: 2916ms
Tidyparse (valid/total): 308/558
Original error:
def solve():
"""Solve the problem and return the result"""
sequence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nth_permute_lexicographically(sequence, 1000000)
result = ''
for i in range(len(sequence))):
result += str(sequence[i])
return result
Bad Repair: invalid syntax (<unknown>, line 5):
def solve():
"""Solve the problem and return the result"""
sequence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
** nth_permute_lexicographically(sequence, 1000000
result = ''
for i in range(len(sequence))):
result += str(sequence[i])
return result
Synthesized repair in: 85500ms
Tidyparse (valid/total): 308/559
Original error:
def allowed(self, request, instance = None):
return((instance.status in ACTIVE_STATES
or instance.status == 'SHUTDOWN')
Good Repair:
def allowed(self, request, instance = None):
** return(instance.status in ACTIVE_STATES
or instance.status == 'SHUTDOWN')
Synthesized repair in: 3073ms
Tidyparse (valid/total): 309/560
Original error:
def makeMaf(inHalPath, outDir, step, overwrite, doMaf):
srcHalPath = inHalPath
if step > 0:
srcHalPath = makePath(inHalPath, outDir, step, "lod", "hal")
outMafPath = makePath(inHalPath, outDir, step, "out", "maf")
if doMaf and(overwrite or not os.path.isfile(outMafPath)):
runShellCommand("hal2maf %s %s" %(srcHalPath, outMafPath)))
Bad Repair: invalid syntax (<unknown>, line 6):
def makeMaf(inHalPath, outDir, step, overwrite, doMaf):
srcHalPath = inHalPath
if step > 0:
srcHalPath = makePath(inHalPath, outDir, step, "lod", "hal")
outMafPath = makePath(inHalPath, outDir, step, "out", "maf")
** if doMaf and(overwrite or not os.path.isfile(outMafPath):
runShellCommand("hal2maf %s %s" %(srcHalPath, outMafPath)))
Synthesized repair in: 44274ms
Tidyparse (valid/total): 309/561
Original error:
def getSpec(self):
return dict(type = self.name,
of = self.of.getSpec()
Good Repair:
def getSpec(self):
return dict(type = self.name,
** of = self.of.getSpec)
Synthesized repair in: 6926ms
Tidyparse (valid/total): 310/562
Original error:
sum = 0
Num = int(input("Ingrese un número:\n"))
for i in range(1, Num + 1):
sum = sum + i
print(sum
Good Repair:
sum = 0
Num = int(input("Ingrese un número:\n"))
for i in range(1, Num + 1):
sum = sum + i
** printsum
Synthesized repair in: 26654ms
Tidyparse (valid/total): 311/563
Original error:
def atomic(self):
return not any(dep for dep in self.dependencies
if dep is not AssetExists()
Good Repair:
def atomic(self):
return not any(dep for dep in self.dependencies
** if dep is not AssetExists)
Synthesized repair in: 8473ms
Tidyparse (valid/total): 312/564
Original error:
def switch_15(myValue):
r = random()
return{
"1": "liar" if r < 0.6 else "21",
"2": "liar" if r < 0.6 else "22",
"3": "liar" if r < 0.6 else "23",
"4": "liar" if r < 0.6 else "24",
"5": "25",
"*": "25"
Bad Repair: invalid syntax (<unknown>, line 4):
def switch_15(myValue):
r = random()
** return
"1": "liar" if r < 0.6 else "21",
"2": "liar" if r < 0.6 else "22",
"3": "liar" if r < 0.6 else "23",
"4": "liar" if r < 0.6 else "24",
"5": "25",
"*": "25"
Synthesized repair in: 3962ms
Tidyparse (valid/total): 312/565
Original error:
def retranslateUi(self, Tab):
_translate = QtCore.QCoreApplication.translate
Tab.setWindowTitle(_translate("Tab", "Form"))
self.btn_loadOriImage.setText(_translate("Tab", "Load Original \n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, Tab):
_translate = QtCore.QCoreApplication.translate
Tab.setWindowTitle(_translate("Tab", "Form"))
** self.btn_loadOriImage.setText(_translate)"Tab", "Load Original \n"
Synthesized repair in: 330711ms
Tidyparse (valid/total): 312/566
Original error:
import json
import urllib2
import csv
import pandas as pd
json_data = json.load(urllib2.urlopen('https: //seeclickfix.com/api/v2/issues?address="New%20Haven"&page=1&per_page=100'))
df = pd.read_json(json.loads(json_data)
Good Repair:
import json
import urllib2
import csv
import pandas as pd
json_data = json.load(urllib2.urlopen('https: //seeclickfix.com/api/v2/issues?address="New%20Haven"&page=1&per_page=100'))
** df = pd.read_json(json.loadsjson_data)
Synthesized repair in: 24125ms
Tidyparse (valid/total): 313/567
Original error:
def testSetPageSize(self):
httpClient = utils.makeHttpClient()
self.assertIsNone(httpClient.getPageSize()
for pageSize in[1, 10, 100]:
httpClient.setPageSize(pageSize)
self.assertEqual(httpClient.getPageSize(), pageSize)
Good Repair:
def testSetPageSize(self):
httpClient = utils.makeHttpClient()
** self.assertIsNone(httpClient.getPageSize)
for pageSize in[1, 10, 100]:
httpClient.setPageSize(pageSize)
self.assertEqual(httpClient.getPageSize(), pageSize)
Synthesized repair in: 36096ms
Tidyparse (valid/total): 314/568
Original error:
def affected(self, source, sites):
"""Returns the sites within the integration distance from the source, """
source_sites = list(self([source], sites)
if source_sites:
return source_sites[0][1]
Good Repair:
def affected(self, source, sites):
"""Returns the sites within the integration distance from the source, """
** source_sites = list(self[source], sites)
if source_sites:
return source_sites[0][1]
Synthesized repair in: 132252ms
Tidyparse (valid/total): 315/569
Original error:
def redirect_example():
response = redirect(url_for('index')
response.set_cookie('test_cookie', '1')
return response
Bad Repair: invalid syntax (<unknown>, line 3):
def redirect_example():
response = redirect(url_for('index')
** response.set_cookie'test_cookie', '1')
return response
Synthesized repair in: 4933ms
Tidyparse (valid/total): 315/570
Original error:
class Solution(object):
def twoSum(self, nums, target):
""": type nums: List[int]"""
d = {}
for i, n1 in enumerate(nums):
n2 = target - n1
if n2 in d:
return[i, d[n2]
else:
d[n1] = i
Good Repair:
class Solution(object):
def twoSum(self, nums, target):
""": type nums: List[int]"""
d = {}
for i, n1 in enumerate(nums):
n2 = target - n1
if n2 in d:
** returni, d[n2]
else:
d[n1] = i
Synthesized repair in: 235699ms
Tidyparse (valid/total): 316/571
Original error:
def output_stream_generator(self):
p = pyaudio.PyAudio()
return p.open(
format = pyaudio.paFloat32,
channels = 1,
rate = self.sample_rate,
output = 2
Bad Repair: unexpected indent (<unknown>, line 4):
def output_stream_generator(self):
p = pyaudio.PyAudio()
** return p.open
format = pyaudio.paFloat32,
channels = 1,
rate = self.sample_rate,
output = 2
Synthesized repair in: 31245ms
Tidyparse (valid/total): 316/572
Original error:
def new_id(self):
self.sessionid = str(uuid.UUID(bytes = ssl.RAND_bytes(16))
return self.sessionid
Bad Repair: expression cannot contain assignment, perhaps you meant "=="? (<unknown>, line 2):
def new_id(self):
** self.sessionid = str(uuid.UUIDbytes = ssl.RAND_bytes(16))
return self.sessionid
Synthesized repair in: 13279ms
Tidyparse (valid/total): 316/573
Original error:
def state_forwards(self, app_label, state):
if not self.preserve_default:
field = self.field.clone()
field.default = NOT_PROVIDED
else:
field = self.field
state.models[app_label, self.model_name_lower].fields.append((self.name, field)
delay = not field.is_relation
state.reload_model(app_label, self.model_name_lower, delay = delay)
Good Repair:
def state_forwards(self, app_label, state):
if not self.preserve_default:
field = self.field.clone()
field.default = NOT_PROVIDED
else:
field = self.field
** state.models[app_label, self.model_name_lower].fields.append(self.name, field)
delay = not field.is_relation
state.reload_model(app_label, self.model_name_lower, delay = delay)
Synthesized repair in: 27922ms
Tidyparse (valid/total): 317/574
Original error:
def banner():
os.system("clear")
print('''%s###########################################'''
Bad Repair: invalid syntax (<unknown>, line 3):
def banner():
os.system("clear")
** print'''%s###########################################'''
Synthesized repair in: 17441ms
Tidyparse (valid/total): 317/575
Original error:
def _get_unlockable_item_count(self):
items = [3,
8,
22,
33,
45,
58,
72,
88,
101,
115,
132
]
config = Configuration.get_instance()
for i in range(0, len(items))):
if config.unlocked_level < items[i]:
return i
return len(items)
Bad Repair: invalid syntax (<unknown>, line 15):
def _get_unlockable_item_count(self):
items = [3,
8,
22,
33,
45,
58,
72,
88,
101,
115,
132
]
** config = Configuration.get_instance(
for i in range(0, len(items))):
if config.unlocked_level < items[i]:
return i
return len(items)
Synthesized repair in: 32876ms
Tidyparse (valid/total): 317/576
Original error:
def _crop(self, image, width, height, x_offset, y_offset):
return image.crop((x_offset, y_offset,
width + x_offset, height + y_offset)
Good Repair:
def _crop(self, image, width, height, x_offset, y_offset):
** return image.crop(x_offset, y_offset,
width + x_offset, height + y_offset)
Synthesized repair in: 2762ms
Tidyparse (valid/total): 318/577
Original error:
import os
import argparse
import boto.iam
import boto.ec2
import boto.ec2.elb
import boto.cloudformation
import boto.utils
import boto.rds2
import json
import base64
import yaml
import requests
import hashlib
from requests.auth import HTTPBasicAuth
from pprint import pprint
import string
BASE_LIST = string.digits + string.letters
BASE_DICT = dict((c, i) for i, c in enumerate(BASE_LIST)
Bad Repair: invalid syntax (<unknown>, line 18):
import os
import argparse
import boto.iam
import boto.ec2
import boto.ec2.elb
import boto.cloudformation
import boto.utils
import boto.rds2
import json
import base64
import yaml
import requests
import hashlib
from requests.auth import HTTPBasicAuth
from pprint import pprint
import string
BASE_LIST = string.digits + string.letters
** BASE_DICT = dict(c, i) for i, c in enumerate(BASE_LIST)
Synthesized repair in: 2186ms
Tidyparse (valid/total): 318/578
Original error:
def drive_licence():
print("licence_no : string of 15 characters atmost\n"
+ "sin : string of 15 characters atmost\n"
+ "class : string of 10 characters atmost\n")
+ "photo : BLOB\n"
+ "issuing_date : yyyy/mm/dd format\n"
+ "expiring_date : yyyy/mm/dd format\n")
Bad Repair: invalid syntax (<unknown>, line 1):
** def drive_licence(:
print("licence_no : string of 15 characters atmost\n"
+ "sin : string of 15 characters atmost\n"
+ "class : string of 10 characters atmost\n")
+ "photo : BLOB\n"
+ "issuing_date : yyyy/mm/dd format\n"
+ "expiring_date : yyyy/mm/dd format\n")
Synthesized repair in: 2659ms
Tidyparse (valid/total): 318/579
Original error:
def make_rna_paths(struct_name, prop_name, enum_name):
"""Create RNA "paths" from given names."""
src = src_rna = src_enum = ""
if struct_name:
if prop_name:
src = src_rna = ".".join((struct_name, prop_name)
if enum_name:
src = src_enum = "%s: '%s'" %(src_rna, enum_name)
else:
src = src_rna = struct_name
return src, src_rna, src_enum
Good Repair:
def make_rna_paths(struct_name, prop_name, enum_name):
"""Create RNA "paths" from given names."""
src = src_rna = src_enum = ""
if struct_name:
if prop_name:
** src = src_rna = ".".join(struct_name, prop_name)
if enum_name:
src = src_enum = "%s: '%s'" %(src_rna, enum_name)
else:
src = src_rna = struct_name
return src, src_rna, src_enum
Synthesized repair in: 22554ms
Tidyparse (valid/total): 319/580
Original error:
def decode(self, filt):
try:
filt.write(self.get_payload(decode = True)
except:
pass
return self.getencoding()
Bad Repair: expression cannot contain assignment, perhaps you meant "=="? (<unknown>, line 3):
def decode(self, filt):
try:
** filt.write(self.get_payloaddecode = True)
except:
pass
return self.getencoding()
Synthesized repair in: 5340ms
Tidyparse (valid/total): 319/581
Original error:
def swap_xapi_host(url, host_addr):
"""Replace the XenServer address present in 'url' with 'host_addr'."""
temp_url = urlparse.urlparse(url)
_netloc, sep, port = temp_url.netloc.partition(': ')
return url.replace(temp_url.netloc, '%s%s%s' %(host_addr, sep, port)
Good Repair:
def swap_xapi_host(url, host_addr):
"""Replace the XenServer address present in 'url' with 'host_addr'."""
temp_url = urlparse.urlparse(url)
_netloc, sep, port = temp_url.netloc.partition(': ')
** return url.replacetemp_url.netloc, '%s%s%s' %(host_addr, sep, port)
Synthesized repair in: 125756ms
Tidyparse (valid/total): 320/582
Original error:
def def_path_type_alias(self):
label_string = self.sub.type + '_type'
if self.sub.subset_type_labels:
label_string += ': ' + ': '.join(map(key_for_cypher, self.sub.subset_type_labels)
return '{}: {}'.format(self.path_type_alias, label_string)
Good Repair:
def def_path_type_alias(self):
label_string = self.sub.type + '_type'
if self.sub.subset_type_labels:
** label_string += ': ' + ': '.joinmap(key_for_cypher, self.sub.subset_type_labels)
return '{}: {}'.format(self.path_type_alias, label_string)
Synthesized repair in: 18253ms
Tidyparse (valid/total): 321/583
Original error:
def find_ofc_item(session, resource, ofc_id):
try:
model = _get_resource_model(resource)
params = dict(ofc_id = ofc_id)
return(session.query(model).filter_by(** params).one()))
except sa.orm.exc.NoResultFound:
return None
Good Repair:
def find_ofc_item(session, resource, ofc_id):
try:
model = _get_resource_model(resource)
params = dict(ofc_id = ofc_id)
** return(session.query(model).filter_by(** params).one())
except sa.orm.exc.NoResultFound:
return None
Synthesized repair in: 15879ms
Tidyparse (valid/total): 322/584
Original error:
def expand_image(self):
""" This function expands the image to three times it's default size """
self.image = pygame.transform.scale(self.image, (self.image.get_width() * 3, self.image.get_height() * 3)))
Good Repair:
def expand_image(self):
""" This function expands the image to three times it's default size """
** self.image = pygame.transform.scale(self.image, (self.image.get_width() * 3, self.image.get_height() * 3))
Synthesized repair in: 7666ms
Tidyparse (valid/total): 323/585
Original error:
class Solution(object):
def reverse(self, x):
"""Actually it's almost cheating to solve this by Python"""
s = str(x).strip('-')[: : - 1]
rv = int(copysign(int(s), x)
rv = rv if - 2 ** 31 <= rv <= 2 ** 31 - 1 else 0
return rv
Good Repair:
class Solution(object):
def reverse(self, x):
"""Actually it's almost cheating to solve this by Python"""
s = str(x).strip('-')[: : - 1]
** rv = int(copysign(ints), x)
rv = rv if - 2 ** 31 <= rv <= 2 ** 31 - 1 else 0
return rv
Synthesized repair in: 50667ms
Tidyparse (valid/total): 324/586
Original error:
def getTimeString(datetime):
"""Returns a string representation of the time, given a"""
return str(datetime.time()
Good Repair:
def getTimeString(datetime):
"""Returns a string representation of the time, given a"""
** return str(datetime.time)
Synthesized repair in: 17215ms
Tidyparse (valid/total): 325/587
Original error:
def parameters(self):
"""Tuple of parameter arrays of all registered functions."""
return tuple(param.data for param in self.params()
Good Repair:
def parameters(self):
"""Tuple of parameter arrays of all registered functions."""
** return tuple(param.data for param in self.params)
Synthesized repair in: 3496ms
Tidyparse (valid/total): 326/588
Original error:
def printxml(tree):
"""Helper function for debugging xml content"""
print(etree.tostring(tree, pretty_print(= True))
return
Bad Repair: invalid syntax (<unknown>, line 3):
def printxml(tree):
"""Helper function for debugging xml content"""
** print(etree.tostringtree, pretty_print(= True))
return
Synthesized repair in: 23515ms
Tidyparse (valid/total): 326/589
Original error:
def value_str(self):
"""return a string containig the value of the current neasure formmatted according to the format defined with the str_property format.By default if uses the simple floaf format"""
return self.str_format %(self.value()
Good Repair:
def value_str(self):
"""return a string containig the value of the current neasure formmatted according to the format defined with the str_property format.By default if uses the simple floaf format"""
** return self.str_format %(self.value)
Synthesized repair in: 11924ms
Tidyparse (valid/total): 327/590
Original error:
def savePicture(self):
""" Insert the picture into database """
db.pictures.insert(self.objectSelf()
Good Repair:
def savePicture(self):
""" Insert the picture into database """
** db.pictures.insert(self.objectSelf)
Synthesized repair in: 8603ms
Tidyparse (valid/total): 328/591
Original error:
def retranslateUi(self, DoctorDialog):
_translate = QtCore.QCoreApplication.translate
DoctorDialog.setWindowTitle(_translate("DoctorDialog", "GNS3 Doctor"))
self.label.setText(_translate("DoctorDialog", "<html><head/><body><p>This will list potential problem in your GNS3 installation:</p></body></html>"))
self.uiDoctorResultTextEdit.setHtml(_translate("DoctorDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 5):
def retranslateUi(self, DoctorDialog):
_translate = QtCore.QCoreApplication.translate
DoctorDialog.setWindowTitle(_translate("DoctorDialog", "GNS3 Doctor"))
self.label.setText(_translate("DoctorDialog", "<html><head/><body><p>This will list potential problem in your GNS3 installation:</p></body></html>"))
** self.uiDoctorResultTextEdit.setHtml(_translate)"DoctorDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 683220ms
Tidyparse (valid/total): 328/592
Original error:
def gamer_load_post(context):
""" Initialize GAMer addon """
print("load post handler: gamer_load_post() called"
Bad Repair: invalid syntax (<unknown>, line 3):
def gamer_load_post(context):
""" Initialize GAMer addon """
** print"load post handler: gamer_load_post() called"
Synthesized repair in: 5748ms
Tidyparse (valid/total): 328/593
Original error:
from fabric.api import *
import os
project_dir = os.path.join(os.path.dirname(sys.argv[0])
Good Repair:
from fabric.api import *
import os
** project_dir = os.path.join(os.path.dirnamesys.argv[0])
Synthesized repair in: 6643ms
Tidyparse (valid/total): 329/594
Original error:
def kind_name(self):
"""Return the kind name specified by this entity's key."""
return self.key_to_kind(self.key()
Good Repair:
def kind_name(self):
"""Return the kind name specified by this entity's key."""
** return self.key_to_kindself.key()
Synthesized repair in: 2850ms
Tidyparse (valid/total): 330/595
Original error:
def canonize(cls, arg, k = 0):
k = sympify(k)
if not k.is_Integer or k.is_negative:
raise ValueError("Error: the second argument of DiracDelta must be a non-negative integer, %s given instead." %(k, )
arg = sympify(arg)
if arg is S.NaN:
return S.NaN
if arg.is_positive or arg.is_negative:
return S.Zero
elif arg.is_zero:
return S.Infinity
Bad Repair: invalid syntax (<unknown>, line 5):
def canonize(cls, arg, k = 0):
k = sympify(k)
if not k.is_Integer or k.is_negative:
raise ValueError("Error: the second argument of DiracDelta must be a non-negative integer, %s given instead." %(k, )
** arg = sympifyarg)
if arg is S.NaN:
return S.NaN
if arg.is_positive or arg.is_negative:
return S.Zero
elif arg.is_zero:
return S.Infinity
Synthesized repair in: 52442ms
Tidyparse (valid/total): 330/596
Original error:
def test_delitem_keyerror(self):
e = EntryBase(req_()
del e['missing_key']
Good Repair:
def test_delitem_keyerror(self):
** e = EntryBase(req_)
del e['missing_key']
Synthesized repair in: 38862ms
Tidyparse (valid/total): 331/597
Original error:
def preinitialize(self, mesh):
"""Setup integrators for each element family (material/quadrature,"""
raise NotImplementedError, "initialize() not implemented."
return
Bad Repair: invalid syntax (<unknown>, line 3):
def preinitialize(self, mesh):
"""Setup integrators for each element family (material/quadrature,"""
** raise NotImplementedError, "initialize) not implemented."
return
Synthesized repair in: 14346ms
Tidyparse (valid/total): 331/598
Original error:
def run_stringtie_expression(data):
"""Calculate transcript and gene level FPKM with Stringtie"""
data = stringtie.run_stringtie_expression(data)
return[[data]
Good Repair:
def run_stringtie_expression(data):
"""Calculate transcript and gene level FPKM with Stringtie"""
data = stringtie.run_stringtie_expression(data)
** return[data]
Synthesized repair in: 8002ms
Tidyparse (valid/total): 332/599
Original error:
class tempState:
""" {u'type': u'temp',"""
def __init__(self, d):
self.current = d['current']
self.high = d['high']
self.low = d['low']
def __str__(self):
return 'current: %d, high: %d low: %d' %(self.current, self.high, self.low)
Bad Repair: expected an indented block (<unknown>, line 4):
class tempState:
** """ u'type': u'temp',"""
def __init__(self, d):
self.current = d['current']
self.high = d['high']
self.low = d['low']
def __str__(self):
return 'current: %d, high: %d low: %d' %(self.current, self.high, self.low)
Synthesized repair in: 160083ms
Tidyparse (valid/total): 332/600
Original error:
def is_in_tree(self, val):
if self.value == val:
return True
elif self.value > val:
if self.left_node == None:
return False
else:
return self.left_node.is_in_tree(val))
else:
if self.right_node == None:
return False
else:
return self.right_node.is_in_tree(val)
Good Repair:
def is_in_tree(self, val):
if self.value == val:
return True
elif self.value > val:
if self.left_node == None:
return False
else:
** return self.left_node.is_in_tree(val)
else:
if self.right_node == None:
return False
else:
return self.right_node.is_in_tree(val)
Synthesized repair in: 12751ms
Tidyparse (valid/total): 333/601
Original error:
def boundary_markers_load_post(context):
""" If this is on old gamer_upy file, transfer pure ID boundaries to RNA """
print("load post handler: boundary_markers_load_post() called"
Bad Repair: unexpected EOF while parsing (<unknown>, line 3):
def boundary_markers_load_post(context):
""" If this is on old gamer_upy file, transfer pure ID boundaries to RNA """
** print("load post handler: boundary_markers_load_post) called"
Synthesized repair in: 21989ms
Tidyparse (valid/total): 333/602
Original error:
def test_plug_iovisor(self, device_exists):
device_exists.return_value = True
d = vif.LibvirtGenericVIFDriver(self._get_conn(ver = 9010)
with mock.patch.object(utils, 'execute') as execute:
execute.side_effect = processutils.ProcessExecutionError
instance = {
'name': 'instance-name',
'uuid': 'instance-uuid',
'project_id': 'myproject'
}
d.plug_iovisor(instance, self.vif_ivs)
Good Repair:
def test_plug_iovisor(self, device_exists):
device_exists.return_value = True
** d = vif.LibvirtGenericVIFDriverself._get_conn(ver = 9010)
with mock.patch.object(utils, 'execute') as execute:
execute.side_effect = processutils.ProcessExecutionError
instance = {
'name': 'instance-name',
'uuid': 'instance-uuid',
'project_id': 'myproject'
}
d.plug_iovisor(instance, self.vif_ivs)
Synthesized repair in: 52534ms
Tidyparse (valid/total): 334/603
Original error:
def add_unchecked(self, binsha, mode, name):
"""Add the given item to the tree, its correctness is assumed, which"""
self._cache.append((binsha, mode, name)
Good Repair:
def add_unchecked(self, binsha, mode, name):
"""Add the given item to the tree, its correctness is assumed, which"""
** self._cache.append(binsha, mode, name)
Synthesized repair in: 6552ms
Tidyparse (valid/total): 335/604
Original error:
def children(cls, source = None):
"""Recursively collect all subclasses of ``cls``, not just direct"""
source = source or cls
result = source.__subclasses__()
for child in result:
result.extend(cls.children(source = child)
return result
Bad Repair: expression cannot contain assignment, perhaps you meant "=="? (<unknown>, line 6):
def children(cls, source = None):
"""Recursively collect all subclasses of ``cls``, not just direct"""
source = source or cls
result = source.__subclasses__()
for child in result:
** result.extend(cls.childrensource = child)
return result
Synthesized repair in: 20685ms
Tidyparse (valid/total): 335/605
Original error:
def test():
return Response(
"""alert("load");"""
, mimetype = 'text/javascript'
Bad Repair: unexpected EOF while parsing (<unknown>, line 4):
def test():
return Response(
** """alert"load");"""
, mimetype = 'text/javascript'
Synthesized repair in: 10650ms
Tidyparse (valid/total): 335/606
Original error:
def setUp(self):
get_graph().remove((None, None, None)
self.resolver = CtsCapitainsLocalResolver(["./tests/testing_data/latinLit2"])
Good Repair:
def setUp(self):
** get_graph().remove(None, None, None)
self.resolver = CtsCapitainsLocalResolver(["./tests/testing_data/latinLit2"])
Synthesized repair in: 50863ms
Tidyparse (valid/total): 336/607
Original error:
"""Test that GETting a tiddler in some form."""
import simplejson
from base64 import b64encode
from.fixtures import reset_textstore, _teststore, initialize_app, get_http
from tiddlyweb.model.user import User
from tiddlyweb.model.bag import Bag
authorization = b64encode('cdent: cowpig'.encode('utf-8')
from tiddlyweb.web.validator import InvalidTiddlerError
import tiddlyweb.web.validator
http = get_http()
Bad Repair: invalid syntax (<unknown>, line 7):
"""Test that GETting a tiddler in some form."""
import simplejson
from base64 import b64encode
from.fixtures import reset_textstore, _teststore, initialize_app, get_http
from tiddlyweb.model.user import User
from tiddlyweb.model.bag import Bag
** authorization = b64encode'cdent: cowpig'.encode('utf-8')
from tiddlyweb.web.validator import InvalidTiddlerError
import tiddlyweb.web.validator
http = get_http()
Synthesized repair in: 10862ms
Tidyparse (valid/total): 336/608
Original error:
def test_load_file_object(self):
od = canopen.import_od(open(EDS_PATH)
self.assertTrue(len(od) > 0)
Good Repair:
def test_load_file_object(self):
** od = canopen.import_od(openEDS_PATH)
self.assertTrue(len(od) > 0)
Synthesized repair in: 9901ms
Tidyparse (valid/total): 337/609
Original error:
def count(self):
""" Count how many lines we have in this import."""
return len(self.urls.splitlines()
Good Repair:
def count(self):
""" Count how many lines we have in this import."""
** return len(self.urls.splitlines)
Synthesized repair in: 16624ms
Tidyparse (valid/total): 338/610
Original error:
def user_has_perm(self, user):
"""Return if a user is allowed to access an instance."""
if user.is_superuser:
return True
return bool(set(user.groups.all() & set(self.groups.all()))
Good Repair:
def user_has_perm(self, user):
"""Return if a user is allowed to access an instance."""
if user.is_superuser:
return True
** return bool(set(user.groups.all() & setself.groups.all()))
Synthesized repair in: 28165ms
Tidyparse (valid/total): 339/611
Original error:
def test_replace(self):
spec = E.field(
E.field(name = "replacement"),
name = "target", position = "replace")
self.View.apply_inheritance_specs(self.base_arch, spec, None)
self.assertEqual(
self.base_arch,
E.form(E.field(name = "replacement"), string = "Title")
Bad Repair: expression cannot contain assignment, perhaps you meant "=="? (<unknown>, line 8):
def test_replace(self):
spec = E.field(
E.field(name = "replacement"),
name = "target", position = "replace")
self.View.apply_inheritance_specs(self.base_arch, spec, None)
self.assertEqual(
self.base_arch,
** E.form(E.fieldname = "replacement"), string = "Title")
Synthesized repair in: 79881ms
Tidyparse (valid/total): 339/612
Original error:
def display_instruction():
'''Выводит инструкцию.'''
print('Инструкция')
print(
'''Йо!'''
Good Repair:
def display_instruction():
'''Выводит инструкцию.'''
print('Инструкция')
** print
'''Йо!'''
Synthesized repair in: 26241ms
Tidyparse (valid/total): 340/613
Original error:
def delete_type_A_record(domain, ** kwargs):
"""Delete A record to domain"""
current_app.logger.debug(
u'Called "delete_type_A_record" domain: {}, params: {}'.format(
domain, kwargs)))
Good Repair:
def delete_type_A_record(domain, ** kwargs):
"""Delete A record to domain"""
current_app.logger.debug(
u'Called "delete_type_A_record" domain: {}, params: {}'.format(
** domain, kwargs))
Synthesized repair in: 12709ms
Tidyparse (valid/total): 341/614
Original error:
def test_open_incorrect_filename():
with pytest.raises(OSError):
l = read(egfn("sampleXXXDOES NOT EXIST.las")
Good Repair:
def test_open_incorrect_filename():
with pytest.raises(OSError):
** l = readegfn("sampleXXXDOES NOT EXIST.las")
Synthesized repair in: 67838ms
Tidyparse (valid/total): 342/615
Original error:
class IdListSchema(SequenceSchema):
"""Schema definition for a List of "ids"."""
id = SchemaNode(Integer()
Good Repair:
class IdListSchema(SequenceSchema):
"""Schema definition for a List of "ids"."""
** id = SchemaNodeInteger()
Synthesized repair in: 15709ms
Tidyparse (valid/total): 343/616
Original error:
def utf8_encode_dict(d):
def enc(a):
if a is None: return None
else: return a.encode('utf8')
return dict((enc(k), enc(v)) for k, v in d.items()
Bad Repair: invalid syntax (<unknown>, line 5):
def utf8_encode_dict(d):
def enc(a):
if a is None: return None
else: return a.encode('utf8')
** return dict(enc(k), enc(v)) for k, v in d.items()
Synthesized repair in: 172745ms
Tidyparse (valid/total): 343/617
Original error:
def load(config_path):
fap = _open_config_file(config_path)
config = copy.deepcopy(DEFAULTS)
config.update(_parse_config_file(fap)
return config
Good Repair:
def load(config_path):
fap = _open_config_file(config_path)
config = copy.deepcopy(DEFAULTS)
** config.update(_parse_config_filefap)
return config
Synthesized repair in: 14788ms
Tidyparse (valid/total): 344/618
Original error:
def retranslateUi(self, SaveImagesDialog):
SaveImagesDialog.setWindowTitle(QtGui.QApplication.translate("SaveImagesDialog", "ChooseImagesToSave", None, QtGui.QApplication.UnicodeUTF8))
self.overwriteCheckBox.setText(QtGui.QApplication.translate("SaveImagesDialog", "overwrite files\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, SaveImagesDialog):
SaveImagesDialog.setWindowTitle(QtGui.QApplication.translate("SaveImagesDialog", "ChooseImagesToSave", None, QtGui.QApplication.UnicodeUTF8))
** self.overwriteCheckBox.setText(QtGui.QApplication.translate)"SaveImagesDialog", "overwrite files\n"
Synthesized repair in: 244987ms
Tidyparse (valid/total): 344/619
Original error:
def receiveEventHandler(self, channel, method, properties, body):
"""Receives messages through the message bus, annotates the event"""
event = JSONObject(str(body)
if event.ceType in self.eventDescriptions:
if self.rm.args.triplestore:
ThreadedTriplestoreAdapter.getOrMake(self.eventDescriptions[event.ceType].graphName)
Good Repair:
def receiveEventHandler(self, channel, method, properties, body):
"""Receives messages through the message bus, annotates the event"""
** event = JSONObjectstr(body)
if event.ceType in self.eventDescriptions:
if self.rm.args.triplestore:
ThreadedTriplestoreAdapter.getOrMake(self.eventDescriptions[event.ceType].graphName)
Synthesized repair in: 9488ms
Tidyparse (valid/total): 345/620
Original error:
def switch_11(myValue):
r = random()
return{
"1": "21",
"2": "liar" if r < 0.5 else "15",
"3": "liar" if r < 0.5 else "15",
"4": "liar" if r < 0.5 else "15" if r < 0.85 else "14",
"5": "15",
"*": "15"
Bad Repair: invalid syntax (<unknown>, line 4):
def switch_11(myValue):
r = random()
** return
"1": "21",
"2": "liar" if r < 0.5 else "15",
"3": "liar" if r < 0.5 else "15",
"4": "liar" if r < 0.5 else "15" if r < 0.85 else "14",
"5": "15",
"*": "15"
Synthesized repair in: 15844ms
Tidyparse (valid/total): 345/621
Original error:
def get_result_by_id(result_id):
"""Get a result by id."""
return JsonResponse(Result.objects(id = result_id).first()))
Good Repair:
def get_result_by_id(result_id):
"""Get a result by id."""
** return JsonResponse(Result.objects(id = result_id).first())
Synthesized repair in: 8014ms
Tidyparse (valid/total): 346/622
Original error:
def update(self, dt):
if self.volume_add is None:
return
self.volume += self.volume_add
self.sound.volume = self.volume
if self.volume < 0.0 or self.volume > 1.0:
self.volume = max(0.0, min(1.0, self.volume)
self.volume_add = None
self.stop()
Bad Repair: invalid syntax (<unknown>, line 8):
def update(self, dt):
if self.volume_add is None:
return
self.volume += self.volume_add
self.sound.volume = self.volume
if self.volume < 0.0 or self.volume > 1.0:
self.volume = max(0.0, min(1.0, self.volume)
self.volume_add = None
** self.stop)
Synthesized repair in: 33328ms
Tidyparse (valid/total): 346/623
Original error:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost')
channel = connection.channel()
channel.queue_declare(queue = 'hello')
Bad Repair: invalid syntax (<unknown>, line 3):
import pika
** connection = pika.BlockingConnection(pika.ConnectionParameters
'localhost')
channel = connection.channel()
channel.queue_declare(queue = 'hello')
Synthesized repair in: 3898ms
Tidyparse (valid/total): 346/624
Original error:
def reset_outlets(self):
"""Set the values of the simulation sequences of all outlet nodes to"""
for(name, node) in self.nodes:
if((node in self.element.outlets) or
Bad Repair: invalid syntax (<unknown>, line 4):
def reset_outlets(self):
"""Set the values of the simulation sequences of all outlet nodes to"""
for(name, node) in self.nodes:
** if(node in self.element.outlets) or
Synthesized repair in: 17571ms
Tidyparse (valid/total): 346/625
Original error:
def Search(term):
""" Will return a dictornary containing info from NYT data base based on relevent search term"""
page = requests.get("https://api.nytimes.com/svc/search/v2/articlesearch.json", params = ({
'api-key': NYT_key,
'q': term
Bad Repair: invalid syntax (<unknown>, line 3):
def Search(term):
""" Will return a dictornary containing info from NYT data base based on relevent search term"""
** page = requests.get("https://api.nytimes.com/svc/search/v2/articlesearch.json", params = )
'api-key': NYT_key,
'q': term
Synthesized repair in: 47652ms
Tidyparse (valid/total): 346/626
Original error:
def quick_add(self, from_method, frame, interpreter, bytecode_index):
interpreter._send(from_method, frame, interpreter._add_symbol,
self.get_class(interpreter.get_universe(),
bytecode_index)
Bad Repair: unexpected indent (<unknown>, line 3):
def quick_add(self, from_method, frame, interpreter, bytecode_index):
** interpreter._sendfrom_method, frame, interpreter._add_symbol,
self.get_class(interpreter.get_universe(),
bytecode_index)
Synthesized repair in: 12866ms
Tidyparse (valid/total): 346/627
Original error:
def cleanup_error(self, exception):
"""error during cleanup"""
self.errors.append(exception.get_msg()
Good Repair:
def cleanup_error(self, exception):
"""error during cleanup"""
** self.errors.appendexception.get_msg()
Synthesized repair in: 3833ms
Tidyparse (valid/total): 347/628
Original error:
def mousePressEvent(self, event):
"""Push"""
self.last_pos = QtCore.QPoint(event.pos()
Good Repair:
def mousePressEvent(self, event):
"""Push"""
** self.last_pos = QtCore.QPointevent.pos()
Synthesized repair in: 2777ms
Tidyparse (valid/total): 348/629
Original error:
def __is_bad_pick(t_planet, pl_list):
if(t_planet.x + t_planet.rad >= DISP_W - 1) or(t_planet.x - t_planet.rad <= 0):
return True
if(t_planet.y + self.rad >= DISP_H - 1) or(t_planet.y - self.rad <= BORDER_UP):
return True
for oth_planet in pl_list:
if t_planet.overlaps(self.__overlaps(t_planet):
return True
return False
Good Repair:
def __is_bad_pick(t_planet, pl_list):
if(t_planet.x + t_planet.rad >= DISP_W - 1) or(t_planet.x - t_planet.rad <= 0):
return True
if(t_planet.y + self.rad >= DISP_H - 1) or(t_planet.y - self.rad <= BORDER_UP):
return True
for oth_planet in pl_list:
** if t_planet.overlapsself.__overlaps(t_planet):
return True
return False
Synthesized repair in: 91153ms
Tidyparse (valid/total): 349/630
Original error:
import os
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import sklearn
from skimage import exposure
import data
import ipcv
from ipcv import josi_hist
import features
from joblib import Memory
memory = Memory(cachedir = os.environ['CACHE_ROOT'],
verbose = int(os.environ['VERBOSITY'])
Good Repair:
import os
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import sklearn
from skimage import exposure
import data
import ipcv
from ipcv import josi_hist
import features
from joblib import Memory
memory = Memory(cachedir = os.environ['CACHE_ROOT'],
** verbose = intos.environ['VERBOSITY'])
Synthesized repair in: 11111ms
Tidyparse (valid/total): 350/631
Original error:
def on_password_icon_clicked(self, entry, icon_pos, event):
"""Called by Gtk callback when the icon of a password entry is clicked."""
set_password_visibility(entry, not entry.get_visibility()
Good Repair:
def on_password_icon_clicked(self, entry, icon_pos, event):
"""Called by Gtk callback when the icon of a password entry is clicked."""
** set_password_visibility(entry, not entry.get_visibility)
Synthesized repair in: 11563ms
Tidyparse (valid/total): 351/632
Original error:
def __iter__(self):
"""Retorna un iterador en base a las claves del archivo shelve."""
return iter(self.dic.keys()
Good Repair:
def __iter__(self):
"""Retorna un iterador en base a las claves del archivo shelve."""
** return iter(self.dic.keys)
Synthesized repair in: 3325ms
Tidyparse (valid/total): 352/633
Original error:
def format_url(cls, url):
parsed_url = urlparse(url.strip()
return '%s: //%s%s' %(parsed_url.scheme or 'http', parsed_url.netloc, parsed_url.path)
Bad Repair: invalid syntax (<unknown>, line 3):
def format_url(cls, url):
parsed_url = urlparse(url.strip()
** return '%s: //%s%s' %parsed_url.scheme or 'http', parsed_url.netloc, parsed_url.path)
Synthesized repair in: 13519ms
Tidyparse (valid/total): 352/634
Original error:
def puaq():
print("Usage: %s contents" % os.path.basename(__file__)
sys.exit(1)
Good Repair:
def puaq():
** print("Usage: %s contents" % os.path.basename__file__)
sys.exit(1)
Synthesized repair in: 12371ms
Tidyparse (valid/total): 353/635
Original error:
def inv_rel_dist(self, J):
'''function that calculates'''
return 1 + 0.033 * math.cos(2 * math.pi * J / 365))
Bad Repair: invalid syntax (<unknown>, line 3):
** def inv_rel_dist(self, J:
'''function that calculates'''
return 1 + 0.033 * math.cos(2 * math.pi * J / 365))
Synthesized repair in: 19950ms
Tidyparse (valid/total): 353/636
Original error:
def _parse_opts(self, line, data, tree, outsecs):
key, val = line, []
for line in data:
if line in outsecs:
break
val.append(line)
n, t = key.split()
tree[(n, t.strip('()')] = " ".join(val)
Bad Repair: invalid syntax (<unknown>, line 8):
def _parse_opts(self, line, data, tree, outsecs):
key, val = line, []
for line in data:
if line in outsecs:
break
val.append(line)
n, t = key.split()
** tree[(n, t.strip'()')] = " ".join(val)
Synthesized repair in: 291128ms
Tidyparse (valid/total): 353/637
Original error:
def meeting(intervals):
if not intervals: return 0
hq = []
heappush(hq
return
Good Repair:
def meeting(intervals):
if not intervals: return 0
hq = []
** heappushhq
return
Synthesized repair in: 25873ms
Tidyparse (valid/total): 354/638
Original error:
def on_actionAbout_triggered(self):
QtGui.QMessageBox.about(self, "About WebBrowser",
"This Example has been created using the ActiveQt integration into Qt Designer.\n"
"It demonstrates the use of QAxWidget to embed the Internet Explorer ActiveX\n"
"control into a Qt application."))
Good Repair:
def on_actionAbout_triggered(self):
QtGui.QMessageBox.about(self, "About WebBrowser",
"This Example has been created using the ActiveQt integration into Qt Designer.\n"
"It demonstrates the use of QAxWidget to embed the Internet Explorer ActiveX\n"
** "control into a Qt application.")
Synthesized repair in: 2251ms
Tidyparse (valid/total): 355/639
Original error:
def checkOk(self):
try:
return str(self.blockNameEdit.text() != ""
except:
return False
Good Repair:
def checkOk(self):
try:
** return strself.blockNameEdit.text() != ""
except:
return False
Synthesized repair in: 2833ms
Tidyparse (valid/total): 356/640
Original error:
def unknown_endtag(self, tag, * args):
if tag != 'skunkdoc':
t = self.STACK.pop()
if t.tag != tag:
print("****end tag doesn't match start s:%s, e:%s" %(
tag, t.tag), self.lineno
raise ParsingError, 'ACK!'
Bad Repair: invalid syntax (<unknown>, line 7):
def unknown_endtag(self, tag, * args):
if tag != 'skunkdoc':
t = self.STACK.pop()
if t.tag != tag:
** print("****end tag doesn't match start s:%s, e:%s" %
tag, t.tag), self.lineno
raise ParsingError, 'ACK!'
Synthesized repair in: 35200ms
Tidyparse (valid/total): 356/641
Original error:
def remote_getdatabases():
return{
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'SETUP',
'USER': 'SETUP',
'PASSWORD': 'SETUP2012',
'HOST': '127.0.0.1',
'PORT': '',
}
Bad Repair: invalid syntax (<unknown>, line 4):
def remote_getdatabases():
return{
** 'default':
'ENGINE': 'django.db.backends.mysql',
'NAME': 'SETUP',
'USER': 'SETUP',
'PASSWORD': 'SETUP2012',
'HOST': '127.0.0.1',
'PORT': '',
}
Synthesized repair in: 6618ms
Tidyparse (valid/total): 356/642
Original error:
def debug(fmt, * arg):
global debug_logfile
if debug_logfile:
fmt = fmt + '\n'
debug_logfile.write(fmt.format(* arg)
debug_logfile.flush()
Good Repair:
def debug(fmt, * arg):
global debug_logfile
if debug_logfile:
fmt = fmt + '\n'
** debug_logfile.writefmt.format(* arg)
debug_logfile.flush()
Synthesized repair in: 4598ms
Tidyparse (valid/total): 357/643
Original error:
"""pgoapi - Pokemon Go API"""
import os
import sys
import json
import time
import pprint
import logging
import getpass
import argparse
sys.path.append(os.path.dirname(os.path.realpath(__file__))
from pgoapi import pgoapi
from pgoapi import utilities as util
log = logging.getLogger(__name__)
Good Repair:
"""pgoapi - Pokemon Go API"""
import os
import sys
import json
import time
import pprint
import logging
import getpass
import argparse
** sys.path.appendos.path.dirname(os.path.realpath(__file__))
from pgoapi import pgoapi
from pgoapi import utilities as util
log = logging.getLogger(__name__)
Synthesized repair in: 5858ms
Tidyparse (valid/total): 358/644
Original error:
class ParseError(Exception):
"""Parsing failure converted to an exception."""
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return 'ParseError({})'.format(repr(self.message)))
Bad Repair: invalid syntax (<unknown>, line 6):
class ParseError(Exception):
"""Parsing failure converted to an exception."""
def __init__(self, message: str):
self.message = message
** def __str__(self:
return self.message
def __repr__(self):
return 'ParseError({})'.format(repr(self.message)))
Synthesized repair in: 22271ms
Tidyparse (valid/total): 358/645
Original error:
def validate_tearDownClass():
if at_exit_set:
LOG.error(
"tearDownClass does not call the super's "
"tearDownClass in these classes: \n"
+ str(at_exit_set)
Bad Repair: unexpected indent (<unknown>, line 4):
def validate_tearDownClass():
if at_exit_set:
** LOG.error
"tearDownClass does not call the super's "
"tearDownClass in these classes: \n"
+ str(at_exit_set)
Synthesized repair in: 16577ms
Tidyparse (valid/total): 358/646
Original error:
def make_client(self):
"""Creates a new `oauth2` Client object with the token attached."""
return oauth2.Client(self._consumer, self.get_request_token()
Good Repair:
def make_client(self):
"""Creates a new `oauth2` Client object with the token attached."""
** return oauth2.Client(self._consumer, self.get_request_token)
Synthesized repair in: 3471ms
Tidyparse (valid/total): 359/647
Original error:
def _zforce(self, R, z, phi = 0., t = 0.):
"""NAME:"""
if t < self._tform:
smooth = 0.
elif t < self._tsteady:
deltat = t - self._tform
xi = 2. * deltat /(self._tsteady - self._tform) - 1.
smooth = (3. / 16. * xi ** 5. - 5. / 8 * xi ** 3. + 15. / 16. * xi + .5)
else:
smooth = 1.
r = numpy.sqrt(R ** 2. + z ** 2.)
if r <= self._rb:
return - self._af * smooth * numpy.cos(2. *(phi - self._omegab * t
Bad Repair: invalid syntax (<unknown>, line 13):
def _zforce(self, R, z, phi = 0., t = 0.):
"""NAME:"""
if t < self._tform:
smooth = 0.
elif t < self._tsteady:
deltat = t - self._tform
xi = 2. * deltat /(self._tsteady - self._tform) - 1.
smooth = (3. / 16. * xi ** 5. - 5. / 8 * xi ** 3. + 15. / 16. * xi + .5)
else:
smooth = 1.
r = numpy.sqrt(R ** 2. + z ** 2.)
if r <= self._rb:
** return - self._af * smooth * numpy.cos(2. *)phi - self._omegab * t
Synthesized repair in: 334513ms
Tidyparse (valid/total): 359/648
Original error:
def retranslateUi(self, NoDevicesDialog_base):
NoDevicesDialog_base.setWindowTitle(QtGui.QApplication.translate("NoDevicesDialog_base", "HP Device Manager - No Installed HP Devices Found", None, QtGui.QApplication.UnicodeUTF8))
self.textLabel7.setText(QtGui.QApplication.translate("NoDevicesDialog_base", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, NoDevicesDialog_base):
NoDevicesDialog_base.setWindowTitle(QtGui.QApplication.translate("NoDevicesDialog_base", "HP Device Manager - No Installed HP Devices Found", None, QtGui.QApplication.UnicodeUTF8))
** self.textLabel7.setText(QtGui.QApplication.translate)"NoDevicesDialog_base", "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
Synthesized repair in: 144389ms
Tidyparse (valid/total): 359/649
Original error:
def get_available_layouts(self):
"""A list of layouts"""
with self._layout_infos_lock:
return list(self._layout_infos.keys()
Good Repair:
def get_available_layouts(self):
"""A list of layouts"""
with self._layout_infos_lock:
** return list(self._layout_infos.keys)
Synthesized repair in: 3571ms
Tidyparse (valid/total): 360/650
Original error:
def run_sql(self, sql, port = os.environ.get('PGPORT', 5432):
return subprocess.Popen(['psql',
'-c', sql,
'-p', port],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
Bad Repair: invalid syntax (<unknown>, line 1):
** def run_sql(self, sql, port = os.environ.get'PGPORT', 5432):
return subprocess.Popen(['psql',
'-c', sql,
'-p', port],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
Synthesized repair in: 20849ms
Tidyparse (valid/total): 360/651
Original error:
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[: 16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc[16: ])))
Good Repair:
def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[: 16]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
** return unpad(cipher.decrypt(enc[16: ]))
Synthesized repair in: 175069ms
Tidyparse (valid/total): 361/652
Original error:
def Can_render_function_taking_function_as_arg__test():
assert_rendered_program_equals(
"""int fn1( double a, double b );""",
"""import sys"""
Bad Repair: unexpected indent (<unknown>, line 3):
def Can_render_function_taking_function_as_arg__test():
** assert_rendered_program_equals
"""int fn1( double a, double b );""",
"""import sys"""
Synthesized repair in: 15471ms
Tidyparse (valid/total): 361/653
Original error:
def test_path(self):
"""test the paths routine"""
self.assertEquals([0, 6, 8, 9, 10, 14, 17, 22, 25, 26, 28, 29, 31, 32, 37, 39, 41, 43, 44, 45, 50, 51, 53, 54, 55, 61, 66, 69, 72, 73, 79, 80, 85, 86, 88, 89, 91, 97, 99, 101]
Good Repair:
def test_path(self):
"""test the paths routine"""
** self.assertEquals[0, 6, 8, 9, 10, 14, 17, 22, 25, 26, 28, 29, 31, 32, 37, 39, 41, 43, 44, 45, 50, 51, 53, 54, 55, 61, 66, 69, 72, 73, 79, 80, 85, 86, 88, 89, 91, 97, 99, 101]
Synthesized repair in: 4180ms
Tidyparse (valid/total): 362/654
Original error:
def switch_14(myValue):
r = random()
return{
"1": "liar" if r < 0.58 else "15",
"2": "liar" if r < 0.58 else "15",
"3": "liar" if r < 0.58 else "15",
"4": "24",
"5": "15",
"*": "15"
Bad Repair: invalid syntax (<unknown>, line 4):
def switch_14(myValue):
r = random()
** return
"1": "liar" if r < 0.58 else "15",
"2": "liar" if r < 0.58 else "15",
"3": "liar" if r < 0.58 else "15",
"4": "24",
"5": "15",
"*": "15"
Synthesized repair in: 3556ms
Tidyparse (valid/total): 362/655
Original error:
def get_aerospike_tuple(self, session_key):
"""Get the Aerospike Tuple"""
namespace = self.aero_namespace
set = self.aero_set
return((namespace, set, session_key)
Good Repair:
def get_aerospike_tuple(self, session_key):
"""Get the Aerospike Tuple"""
namespace = self.aero_namespace
set = self.aero_set
** return(namespace, set, session_key)
Synthesized repair in: 14467ms
Tidyparse (valid/total): 363/656
Original error:
def rearpNetwork(self, args):
import os
import sys
sys.path.append("../")
import subprocess
GATEWAY = args
package_dir = os.path.dirname(os.path.dirname(__file__))) + '/packages/'
process = subprocess.Popen('python ' + package_dir + 'arpmitm/arpmitm.py -r ' + GATEWAY + ' &', shell = True)
return process.pid
Bad Repair: invalid syntax (<unknown>, line 5):
def rearpNetwork(self, args):
import os
import sys
** sys.path.append("../"
import subprocess
GATEWAY = args
package_dir = os.path.dirname(os.path.dirname(__file__))) + '/packages/'
process = subprocess.Popen('python ' + package_dir + 'arpmitm/arpmitm.py -r ' + GATEWAY + ' &', shell = True)
return process.pid
Synthesized repair in: 42248ms
Tidyparse (valid/total): 363/657
Original error:
def _get_sld_dom(self):
if self._sld_dom is None:
self._sld_dom = self.catalog.get_xml(self.body_href()
return self._sld_dom
Good Repair:
def _get_sld_dom(self):
if self._sld_dom is None:
** self._sld_dom = self.catalog.get_xmlself.body_href()
return self._sld_dom
Synthesized repair in: 7549ms
Tidyparse (valid/total): 364/658
Original error:
def checkKeywords(dic, legalKeywords, what = 'argument'):
"""Verify no illegal keyword arguments were passed to a function."""
for k in dic.keys():
if k not in legalKeywords:
raise TypeError("'%s' is not a valid %s" %(k, what)
Good Repair:
def checkKeywords(dic, legalKeywords, what = 'argument'):
"""Verify no illegal keyword arguments were passed to a function."""
for k in dic.keys():
if k not in legalKeywords:
** raise TypeError("'%s' is not a valid %s" %k, what)
Synthesized repair in: 45658ms
Tidyparse (valid/total): 365/659
Original error:
def SyncTransactionLog(self):
if not NannyController.synced:
_winreg.FlushKey(self._GetKey()
NannyController.synced = True
Good Repair:
def SyncTransactionLog(self):
if not NannyController.synced:
** _winreg.FlushKeyself._GetKey()
NannyController.synced = True
Synthesized repair in: 12710ms
Tidyparse (valid/total): 366/660
Original error:
def includeme(config):
"""Initialize the model for a Pyramid app."""
settings = config.get_settings()
config.include('pyramid_tm')
session_factory = get_session_factory(get_engine(settings)
config.registry['dbsession_factory'] = session_factory
config.add_request_method(
lambda r: get_tm_session(session_factory, r.tm),
'dbsession',
reify = True
)
Bad Repair: invalid syntax (<unknown>, line 6):
def includeme(config):
"""Initialize the model for a Pyramid app."""
settings = config.get_settings()
config.include('pyramid_tm')
session_factory = get_session_factory(get_engine(settings)
config.registry['dbsession_factory'] = session_factory
config.add_request_method(
** lambda r: get_tm_sessionsession_factory, r.tm),
'dbsession',
reify = True
)
Synthesized repair in: 75157ms
Tidyparse (valid/total): 366/661
Original error:
def createReturnValue(header, body, parse):
if parse and body.strip() != '':
body = parse_xml(StringIO(body)
return header, body
Good Repair:
def createReturnValue(header, body, parse):
if parse and body.strip() != '':
** body = parse_xml(StringIObody)
return header, body
Synthesized repair in: 18816ms
Tidyparse (valid/total): 367/662
Original error:
def get_new_task_id(cls):
"""Get a unique id for a new page task, given it's"""
return str(uuid.uuid1()
Good Repair:
def get_new_task_id(cls):
"""Get a unique id for a new page task, given it's"""
** return str(uuid.uuid1)
Synthesized repair in: 12853ms
Tidyparse (valid/total): 368/663
Original error:
def builder_action_distribute_define_args(self, called_as, log):
return[
'install',
'INSTALL_TOP={}'.format(self.calculate_dst_install_prefix()),
'MYCFLAGS=-std=gnu99',
'MYLDFLAGS=-ltinfow'
Bad Repair: unexpected indent (<unknown>, line 3):
def builder_action_distribute_define_args(self, called_as, log):
** return
'install',
'INSTALL_TOP={}'.format(self.calculate_dst_install_prefix()),
'MYCFLAGS=-std=gnu99',
'MYLDFLAGS=-ltinfow'
Synthesized repair in: 74117ms
Tidyparse (valid/total): 368/664
Original error:
def moderate_comment(sender, comment, request, ** kwargs):
ak = akismet.Akismet(
key = settings.AKISMET_API_KEY,
blog_url = 'http://%s/' % Site.objects.get_current().domain
Bad Repair: unexpected indent (<unknown>, line 3):
def moderate_comment(sender, comment, request, ** kwargs):
** ak = akismet.Akismet
key = settings.AKISMET_API_KEY,
blog_url = 'http://%s/' % Site.objects.get_current().domain
Synthesized repair in: 6283ms
Tidyparse (valid/total): 368/665
Original error:
def guessbackgroundlevel(self):
"""Estimates the background level.This could be used to fill pixels in large cosmics."""
if self.backgroundlevel is None:
self.backgroundlevel = np.median(self.rawarray.ravel()
return self.backgroundlevel
Good Repair:
def guessbackgroundlevel(self):
"""Estimates the background level.This could be used to fill pixels in large cosmics."""
if self.backgroundlevel is None:
** self.backgroundlevel = np.median(self.rawarray.ravel)
return self.backgroundlevel
Synthesized repair in: 15978ms
Tidyparse (valid/total): 369/666
Original error:
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__()
Good Repair:
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
** self.__dict__.update(other.__getstate__)
Synthesized repair in: 7208ms
Tidyparse (valid/total): 370/667
Original error:
def test_reverse(self):
m = self.populate_MessageOfTypes()
m2 = dict_to_protobuf(MessageOfTypes, protobuf_to_dict(m)
assert m == m2
m2.dubl = 0
assert m2 != m
Good Repair:
def test_reverse(self):
m = self.populate_MessageOfTypes()
** m2 = dict_to_protobufMessageOfTypes, protobuf_to_dict(m)
assert m == m2
m2.dubl = 0
assert m2 != m
Synthesized repair in: 40744ms
Tidyparse (valid/total): 371/668
Original error:
class _cdirent(ctypes.Structure):
_fields_ = [
("ino_t", ctypes.c_ulong),
("off_t", ctypes.c_ulong),
("d_reclen", ctypes.c_short),
("d_type", ctypes.c_ubyte),
("d_name", ctypes.c_char * 4000)
Bad Repair: invalid syntax (<unknown>, line 2):
class _cdirent(ctypes.Structure):
** _fields_ =
("ino_t", ctypes.c_ulong),
("off_t", ctypes.c_ulong),
("d_reclen", ctypes.c_short),
("d_type", ctypes.c_ubyte),
("d_name", ctypes.c_char * 4000)
Synthesized repair in: 207519ms
Tidyparse (valid/total): 371/669
Original error:
def print_metadata_name(name):
print(js.dumps({
"name": name
Bad Repair: unexpected indent (<unknown>, line 3):
def print_metadata_name(name):
** print(js.dumps())
"name": name
Synthesized repair in: 20356ms
Tidyparse (valid/total): 371/670
Original error:
def on_task_input(self, task, config):
"""Generates and returns a list of entries from the deluge daemon."""
self.entries = []
self.connect(task, self.prepare_config(config)
return self.entries
Good Repair:
def on_task_input(self, task, config):
"""Generates and returns a list of entries from the deluge daemon."""
self.entries = []
** self.connecttask, self.prepare_config(config)
return self.entries
Synthesized repair in: 20761ms
Tidyparse (valid/total): 372/671
Original error:
def copy_to(self, to):
'''Copy some attribute to another touch object.'''
for attr in self.__attrs__:
to.__setattr__(attr, copy(self.__getattribute__(attr))
Good Repair:
def copy_to(self, to):
'''Copy some attribute to another touch object.'''
for attr in self.__attrs__:
** to.__setattr__(attr, copy(self.__getattribute__attr))
Synthesized repair in: 5913ms
Tidyparse (valid/total): 373/672
Original error:
def pad_all():
for infile in sys.argv[1: ]:
pad_file(infile, 'out/' + infile
Good Repair:
def pad_all():
for infile in sys.argv[1: ]:
** pad_fileinfile, 'out/' + infile
Synthesized repair in: 16591ms
Tidyparse (valid/total): 374/673
Original error:
def retranslateUi(self, AddFileDialog):
_translate = QtCore.QCoreApplication.translate
AddFileDialog.setWindowTitle(_translate("AddFileDialog", "Add Files"))
AddFileDialog.setWhatsThis(_translate("AddFileDialog", "<b>Add Files Dialog</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, AddFileDialog):
_translate = QtCore.QCoreApplication.translate
AddFileDialog.setWindowTitle(_translate("AddFileDialog", "Add Files"))
** AddFileDialog.setWhatsThis(_translate)"AddFileDialog", "<b>Add Files Dialog</b>\n"
Synthesized repair in: 65919ms
Tidyparse (valid/total): 374/674
Original error:
def __init__(self, pstFile):
self.pst_parser = pst.py_pst(pstFile)
self.pst_contacts = iter(self.pst_parser.get_contacts()
Good Repair:
def __init__(self, pstFile):
self.pst_parser = pst.py_pst(pstFile)
** self.pst_contacts = iter(self.pst_parser.get_contacts)
Synthesized repair in: 7583ms
Tidyparse (valid/total): 375/675
Original error:
def register(func, * targs, ** kargs):
"""register a function to be executed upon normal program termination"""
_exithandlers.append((func, targs, kargs)
Good Repair:
def register(func, * targs, ** kargs):
"""register a function to be executed upon normal program termination"""
** _exithandlers.append(func, targs, kargs)
Synthesized repair in: 8239ms
Tidyparse (valid/total): 376/676
Original error:
def onclick(self, event):
"""Mouse click handler."""
mouseevent = event.mouseevent
self.coords.append((mouseevent.xdata, mouseevent.ydata)
Good Repair:
def onclick(self, event):
"""Mouse click handler."""
mouseevent = event.mouseevent
** self.coords.append(mouseevent.xdata, mouseevent.ydata)
Synthesized repair in: 2444ms
Tidyparse (valid/total): 377/677
Original error:
def test_destroy(self):
new_tag = self.create_tag()
self.assertTrue(self.client.tags.destroy(new_tag.id)
Good Repair:
def test_destroy(self):
new_tag = self.create_tag()
** self.assertTrueself.client.tags.destroy(new_tag.id)
Synthesized repair in: 6366ms
Tidyparse (valid/total): 378/678
Original error:
def switch_13(myValue):
r = random()
return{
"1": "liar" if r < 0.58 else "15",
"2": "liar" if r < 0.58 else "15",
"3": "23",
"4": "liar" if r < 0.58 else "15",
"5": "15",
"*": "15"
Bad Repair: invalid syntax (<unknown>, line 4):
def switch_13(myValue):
r = random()
** return
"1": "liar" if r < 0.58 else "15",
"2": "liar" if r < 0.58 else "15",
"3": "23",
"4": "liar" if r < 0.58 else "15",
"5": "15",
"*": "15"
Synthesized repair in: 7287ms
Tidyparse (valid/total): 378/679
Original error:
def serialize_header(self, headers):
headers = headers or{}
result = self._headers_rw.write(headers, io.BytesIO().getvalue()
return result
Good Repair:
def serialize_header(self, headers):
headers = headers or{}
** result = self._headers_rw.write(headers, io.BytesIO).getvalue()
return result
Synthesized repair in: 21168ms
Tidyparse (valid/total): 379/680
Original error:
import smbus
import config
import os
import time
import threading
bus = smbus.SMBus(1)
sections = list(config.sections()
Good Repair:
import smbus
import config
import os
import time
import threading
bus = smbus.SMBus(1)
** sections = listconfig.sections()
Synthesized repair in: 3685ms
Tidyparse (valid/total): 380/681
Original error:
def test_default_is_empty(self):
"""Verify a new default collection is empty."""
assert len(self._get_collection() == 0
Good Repair:
def test_default_is_empty(self):
"""Verify a new default collection is empty."""
** assert len(self._get_collection) == 0
Synthesized repair in: 5571ms
Tidyparse (valid/total): 381/682
Original error:
"""Utility functions for Talos"""
import os
import time
import urlparse
import string
import urllib
import json
import re
import platform
from mozlog import get_proxy_logger
here = os.path.dirname(os.path.realpath(__file__)
LOG = get_proxy_logger()
Bad Repair: invalid syntax (<unknown>, line 12):
"""Utility functions for Talos"""
import os
import time
import urlparse
import string
import urllib
import json
import re
import platform
from mozlog import get_proxy_logger
here = os.path.dirname(os.path.realpath(__file__)
** LOG = get_proxy_logger)
Synthesized repair in: 3188ms
Tidyparse (valid/total): 381/683
Original error:
def by_key(key):
for question in get(lambda x: x.key == key, get_all():
return question
Bad Repair: invalid syntax (<unknown>, line 2):
def by_key(key):
** for question in getlambda x: x.key == key, get_all():
return question
Synthesized repair in: 7346ms
Tidyparse (valid/total): 381/684
Original error:
def main(files):
print('citing_doi, ts')
for f in files:
json_str = open(f).read()
paper = json.loads(json_str)
print(paper.get('id') + ', ' + paper.get('date')
Good Repair:
def main(files):
print('citing_doi, ts')
for f in files:
json_str = open(f).read()
paper = json.loads(json_str)
** printpaper.get('id') + ', ' + paper.get('date')
Synthesized repair in: 117722ms
Tidyparse (valid/total): 382/685
Original error:
def __image_changed(self):
"""Handle thumbnail change.If the image is not to be included, make the"""
self.__image_on_side.set_available(self.__include_images.get_value()
Good Repair:
def __image_changed(self):
"""Handle thumbnail change.If the image is not to be included, make the"""
** self.__image_on_side.set_available(self.__include_images.get_value)
Synthesized repair in: 2969ms
Tidyparse (valid/total): 383/686
Original error:
def moderadio_cb(self, action, current):
self.scanmode = action.get_current_value()
print("Changing scan mode to " + str(self.scanmode)
Bad Repair: invalid syntax (<unknown>, line 3):
def moderadio_cb(self, action, current):
self.scanmode = action.get_current_value()
** print"Changing scan mode to " + str(self.scanmode)
Synthesized repair in: 34149ms
Tidyparse (valid/total): 383/687
Original error:
def __str__(self):
return("<function bpy.ops.%s.%s at 0x%x'>" %
(self._module, self._func, id(self))
Good Repair:
def __str__(self):
return("<function bpy.ops.%s.%s at 0x%x'>" %
** self._module, self._func, id(self))
Synthesized repair in: 5485ms
Tidyparse (valid/total): 384/688
Original error:
def show(self):
page_menu = self.get_page_menu_with_chosen()
test_str = """------------""" %(self.current_page, self.page_count, self.num_pager_buttons
Good Repair:
def show(self):
page_menu = self.get_page_menu_with_chosen()
** test_str = """------------""" %self.current_page, self.page_count, self.num_pager_buttons
Synthesized repair in: 11678ms
Tidyparse (valid/total): 385/689
Original error:
def test_load_top_level_by_name(self):
proc = self.runIn(
'such',
'-v',
'--plugin=nose2.plugins.layers',
'test_such.A system with complex setup.should do something')
self.assertTestRunOutputMatches(proc, stderr = 'Ran 1 test')
self.assertEqual(proc.poll(), 0, proc.stderr.getvalue()
Good Repair:
def test_load_top_level_by_name(self):
proc = self.runIn(
'such',
'-v',
'--plugin=nose2.plugins.layers',
'test_such.A system with complex setup.should do something')
self.assertTestRunOutputMatches(proc, stderr = 'Ran 1 test')
** self.assertEqualproc.poll(), 0, proc.stderr.getvalue()
Synthesized repair in: 157500ms
Tidyparse (valid/total): 386/690
Original error:
def add_task(self, func, * args, ** kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs)
Good Repair:
def add_task(self, func, * args, ** kargs):
"""Add a task to the queue"""
** self.tasks.put(func, args, kargs)
Synthesized repair in: 7768ms
Tidyparse (valid/total): 387/691
Original error:
def get_response_json(self):
from django.http import JsonResponse
return JsonResponse(self.get_response()
Good Repair:
def get_response_json(self):
from django.http import JsonResponse
** return JsonResponseself.get_response()
Synthesized repair in: 3161ms
Tidyparse (valid/total): 388/692
Original error:
def __init__(self:
self.maxram = 0x20 * 0x20
self.sfr = array.array('B')
self.clear()
Bad Repair: invalid syntax (<unknown>, line 3):
def __init__(self:
self.maxram = 0x20 * 0x20
self.sfr = array.array('B')
** self.clear)
Synthesized repair in: 5780ms
Tidyparse (valid/total): 388/693
Original error:
def hasParameter(cls, param_name):
"""Checks whether this data provider has a parameter named param_name."""
return param_name in(param.name for param in cls.getParametersList()
Good Repair:
def hasParameter(cls, param_name):
"""Checks whether this data provider has a parameter named param_name."""
** return param_name in(param.name for param in cls.getParametersList)
Synthesized repair in: 2149ms
Tidyparse (valid/total): 389/694
Original error:
def terminate(self, signal_number, stack_frame):
""" Signal handler for end-process signals."""
exception = SystemExit(
"Terminating on signal %(signal_number)r"
% vars()
raise exception
Good Repair:
def terminate(self, signal_number, stack_frame):
""" Signal handler for end-process signals."""
exception = SystemExit(
"Terminating on signal %(signal_number)r"
** % vars)
raise exception
Synthesized repair in: 22023ms
Tidyparse (valid/total): 390/695
Original error:
def __str__(self):
s = 'FermiSurface -> Number of pieces %s.\n' % self.npiece
s += str(self.pieces.keys()
return s
Good Repair:
def __str__(self):
s = 'FermiSurface -> Number of pieces %s.\n' % self.npiece
** s += str(self.pieces.keys)
return s
Synthesized repair in: 14131ms
Tidyparse (valid/total): 391/696
Original error:
def getdatabases():
return{
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'acappella',
'USER': 'acappella',
'PASSWORD': 'password',
'HOST': '',
'PORT': '',
}
Bad Repair: invalid syntax (<unknown>, line 4):
def getdatabases():
return{
** 'default':
'ENGINE': 'django.db.backends.mysql',
'NAME': 'acappella',
'USER': 'acappella',
'PASSWORD': 'password',
'HOST': '',
'PORT': '',
}
Synthesized repair in: 3379ms
Tidyparse (valid/total): 391/697
Original error:
"""Unit-test chrome_app.apis."""
from __future__ import print_function, division, unicode_literals
import collections
import os
import sys
import unittest
import mock
import caterpillar_test
import chrome_app.apis
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))
Good Repair:
"""Unit-test chrome_app.apis."""
from __future__ import print_function, division, unicode_literals
import collections
import os
import sys
import unittest
import mock
import caterpillar_test
import chrome_app.apis
** ROOT_DIR = os.path.dirname(os.path.dirnameos.path.realpath(__file__))
Synthesized repair in: 2433ms
Tidyparse (valid/total): 392/698
Original error:
def set_default_automail_booking_value(self):
config = self.env["ir.model.data"].xmlid_to_object("carrent_booking.configuration")
config.write({
"default_auto_booking_mail": self.default_auto_booking_mail
Bad Repair: unexpected indent (<unknown>, line 4):
def set_default_automail_booking_value(self):
config = self.env["ir.model.data"].xmlid_to_object("carrent_booking.configuration")
** config.write()
"default_auto_booking_mail": self.default_auto_booking_mail
Synthesized repair in: 74116ms
Tidyparse (valid/total): 392/699
Original error:
def matchmark(colitem, markexpr):
"""Tries to match on any marker names, attached to the given colitem."""
return eval(markexpr, {}, MarkMapping(colitem.keywords)
Good Repair:
def matchmark(colitem, markexpr):
"""Tries to match on any marker names, attached to the given colitem."""
** return eval(markexpr, {}, MarkMappingcolitem.keywords)
Synthesized repair in: 23775ms
Tidyparse (valid/total): 393/700
Original error:
class CoordLimits(namedtuple('CoordLimits', ['coord', 'start', 'end', 'constraint_function']):
"""Holds the start and end values for subsetting limits."""
pass
Bad Repair: invalid syntax (<unknown>, line 1):
** class CoordLimits(namedtuple'CoordLimits', ['coord', 'start', 'end', 'constraint_function']):
"""Holds the start and end values for subsetting limits."""
pass
Synthesized repair in: 14524ms
Tidyparse (valid/total): 393/701
Original error:
def setUp(self):
print(self.id()
PexpectTestCase.PexpectTestCase.setUp(self)
Bad Repair: invalid syntax (<unknown>, line 3):
def setUp(self):
print(self.id()
** PexpectTestCase.PexpectTestCase.setUpself)
Synthesized repair in: 12173ms
Tidyparse (valid/total): 393/702
Original error:
def show_html(self):
for obj in self.ui_objects:
print(obj.get_html()
Good Repair:
def show_html(self):
for obj in self.ui_objects:
** printobj.get_html()
Synthesized repair in: 6514ms
Tidyparse (valid/total): 394/703
Original error:
def isAlive():
ans = None;
if connection:
ans = connection.sr1(ModbusADU(transId = getTransId() / ModbusPDU01_Read_Coils(), timeout = timeout)
if ans:
return True
else:
return False
Good Repair:
def isAlive():
ans = None;
if connection:
** ans = connection.sr1(ModbusADU(transId = getTransId() / ModbusPDU01_Read_Coils), timeout = timeout)
if ans:
return True
else:
return False
Synthesized repair in: 21992ms
Tidyparse (valid/total): 395/704
Original error:
from tools.load import LoadMatrix
from numpy import where
lm = LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list = [[traindat, testdat, 1.5, 1.0], [traindat, testdat, 1.0, 1.5]
Good Repair:
from tools.load import LoadMatrix
from numpy import where
lm = LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
** parameter_list = [traindat, testdat, 1.5, 1.0], [traindat, testdat, 1.0, 1.5]
Synthesized repair in: 66959ms
Tidyparse (valid/total): 396/705
Original error:
< % if(isPaymentPackage){% > from django.views.generic import RedirectView, View
import oscar
from oscar.core.loading import get_class, get_model
PaymentDetailsView = get_class('checkout.views', 'PaymentDetailsView')
CheckoutSessionMixin = get_class('checkout.session', 'CheckoutSessionMixin')
Bad Repair: invalid syntax (<unknown>, line 1):
** < % if(isPaymentPackage)% > from django.views.generic import RedirectView, View
import oscar
from oscar.core.loading import get_class, get_model
PaymentDetailsView = get_class('checkout.views', 'PaymentDetailsView')
CheckoutSessionMixin = get_class('checkout.session', 'CheckoutSessionMixin')
Synthesized repair in: 23318ms
Tidyparse (valid/total): 396/706
Original error:
def test_all_attribute_reads_are_caught(self):
catcher = self.CatchAllAttributeReads()
self.assertMatch("Someone called 'foobar' and it could not be found"
Bad Repair: invalid syntax (<unknown>, line 3):
def test_all_attribute_reads_are_caught(self):
catcher = self.CatchAllAttributeReads()
** self.assertMatch"Someone called 'foobar' and it could not be found"
Synthesized repair in: 25707ms
Tidyparse (valid/total): 396/707
Original error:
def test_connect_should_call_connect_socket_method_with_server_and_port(self):
server = 'irc.rizon.net'
port = 6667
self.__ircSocket.connect(server, port)
self.__socketMock.connect.assert_called_once_with((server, port)))
Bad Repair: invalid syntax (<unknown>, line 5):
def test_connect_should_call_connect_socket_method_with_server_and_port(self):
server = 'irc.rizon.net'
port = 6667
** self.__ircSocket.connect(server, port
self.__socketMock.connect.assert_called_once_with((server, port)))
Synthesized repair in: 22654ms
Tidyparse (valid/total): 396/708
Original error:
class Curve(object):
def __init__(self, coeffs, y):
self.coeffs = coeffs
self.y = y
return
def derivative(self):
new_curve = None
order = len(self.coeffs)
d_coeffs = [
return new_curve
Bad Repair: invalid syntax (<unknown>, line 9):
class Curve(object):
def __init__(self, coeffs, y):
self.coeffs = coeffs
self.y = y
return
def derivative(self):
new_curve = None
order = len(self.coeffs)
** d_coeffs =
return new_curve
Synthesized repair in: 433633ms
Tidyparse (valid/total): 396/709
Original error:
def redirect_to_schedule(self):
"""Shortcut for redirecting to the schedule page of the current barcamp."""
return self.redirect_to(reverse('barcamp: schedule',
args = [self.barcamp.slug])))
Good Repair:
def redirect_to_schedule(self):
"""Shortcut for redirecting to the schedule page of the current barcamp."""
return self.redirect_to(reverse('barcamp: schedule',
** args = [self.barcamp.slug]))
Synthesized repair in: 7050ms
Tidyparse (valid/total): 397/710
Original error:
def kill_ie():
"""kill ie"""
return render_template('utils/kill-ie.html', blog_name = Setting.get_setting('blog_name', 'Plog')
Bad Repair: invalid syntax (<unknown>, line 3):
def kill_ie():
"""kill ie"""
** return render_template'utils/kill-ie.html', blog_name = Setting.get_setting('blog_name', 'Plog')
Synthesized repair in: 10862ms
Tidyparse (valid/total): 397/711
Original error:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls),
)
Good Repair:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
** url(r'^admin/', includeadmin.site.urls),
)
Synthesized repair in: 21921ms
Tidyparse (valid/total): 398/712
Original error:
"""a simple test script"""
import sys
from mininet.node import Host, Switch, Controller, Node
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import ensureRoot, waitListening, dumpNodeConnections
from mininet.log import setLogLevel, info, warn, output
ensureRoot()
myHost = Host('myHostName', cls = Host, ip = '10.0.0.200')
myHost.addIntf(
print("ip is", myHost.IP())
Bad Repair: invalid syntax (<unknown>, line 11):
"""a simple test script"""
import sys
from mininet.node import Host, Switch, Controller, Node
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import ensureRoot, waitListening, dumpNodeConnections
from mininet.log import setLogLevel, info, warn, output
ensureRoot()
myHost = Host('myHostName', cls = Host, ip = '10.0.0.200')
myHost.addIntf(
** print"ip is", myHost.IP())
Synthesized repair in: 10495ms
Tidyparse (valid/total): 398/713
Original error:
def __init__(self, grid_id = None):
self.fs = gridfs.GridFS(_get_db()
self.newfile = None
self.grid_id = grid_id
Good Repair:
def __init__(self, grid_id = None):
** self.fs = gridfs.GridFS_get_db()
self.newfile = None
self.grid_id = grid_id
Synthesized repair in: 18793ms
Tidyparse (valid/total): 399/714
Original error:
def interrupt(self, cmd):
self.halt = True
self.client.close()
cmd.set_results(CommandResult(1, "", "command on host " + self.targetHost + " interrupted ", False, False)
Good Repair:
def interrupt(self, cmd):
self.halt = True
self.client.close()
** cmd.set_resultsCommandResult(1, "", "command on host " + self.targetHost + " interrupted ", False, False)
Synthesized repair in: 13433ms
Tidyparse (valid/total): 400/715
Original error:
def real_path(path):
"""Returns: the canonicalized absolute pathname.The resulting path will have no symbolic link, '/./' or '/../' components."""
return ek.ek(os.path.normpath, ek.ek(os.path.normcase, ek.ek(os.path.realpath, path))))
Good Repair:
def real_path(path):
"""Returns: the canonicalized absolute pathname.The resulting path will have no symbolic link, '/./' or '/../' components."""
** return ek.ek(os.path.normpath, ek.ek(os.path.normcase, ek.ek(os.path.realpath, path)))
Synthesized repair in: 11492ms
Tidyparse (valid/total): 401/716
Original error:
def to_str(self):
"""Returns the string representation of the model"""
return pformat(self.to_dict()
Good Repair:
def to_str(self):
"""Returns the string representation of the model"""
** return pformat(self.to_dict)
Synthesized repair in: 17367ms
Tidyparse (valid/total): 402/717
Original error:
def endElement(self, name):
if name == "context":
self.in_context = False
self.sentences.append((self.lexelt,
self.head_count,
self.cur_sentence,
self.instance_id)
if name == "head":
self.cur_sentence += "</head>"
Good Repair:
def endElement(self, name):
if name == "context":
self.in_context = False
** self.sentences.append(self.lexelt,
self.head_count,
self.cur_sentence,
self.instance_id)
if name == "head":
self.cur_sentence += "</head>"
Synthesized repair in: 2275ms
Tidyparse (valid/total): 403/718
Original error:
def test_compute_cpu_kernel_percent(self):
c = self._process_notification(cpu.CpuKernelPercent(None)
self.assertEqual('compute.node.cpu.kernel.percent', c.name)
self.assertEqual(0.5841204961898534, c.volume)
Bad Repair: invalid syntax (<unknown>, line 3):
def test_compute_cpu_kernel_percent(self):
c = self._process_notification(cpu.CpuKernelPercent(None)
self.assertEqual('compute.node.cpu.kernel.percent', c.name)
** self.assertEqual0.5841204961898534, c.volume)
Synthesized repair in: 46745ms
Tidyparse (valid/total): 403/719
Original error:
def toOperational(self):
self.finished_flag = False
self.printer_state = 3
if self.buffer and len(self.buffer) != 0:
with self.buffer_lock:
self.buffer.clear()
self.unbuffered_gcodes("\n".join(self.profile['end_gcodes'])
Bad Repair: invalid syntax (<unknown>, line 7):
def toOperational(self):
self.finished_flag = False
self.printer_state = 3
if self.buffer and len(self.buffer) != 0:
with self.buffer_lock:
self.buffer.clear()
** self.unbuffered_gcodes"\n".join(self.profile['end_gcodes'])
Synthesized repair in: 67484ms
Tidyparse (valid/total): 403/720
Original error:
def loadProgram(filename):
with open(filename, 'r') as f:
return "".join(f.readlines()
Good Repair:
def loadProgram(filename):
with open(filename, 'r') as f:
** return "".join(f.readlines)
Synthesized repair in: 26566ms
Tidyparse (valid/total): 404/721
Original error:
import getpass
import os
import pymysql
import pymysql.cursors
def connection(wiki,
defaults_file = os.path.expanduser("~/.my.cnf"),
user = getpass.getuser():
return pymysql.connect(
host = "analytics-store.eqiad.wmnet",
database = wiki,
user = user,
read_default_file = defaults_file
)
Bad Repair: invalid syntax (<unknown>, line 7):
import getpass
import os
import pymysql
import pymysql.cursors
def connection(wiki,
defaults_file = os.path.expanduser("~/.my.cnf"),
user = getpass.getuser():
** return pymysql.connect
host = "analytics-store.eqiad.wmnet",
database = wiki,
user = user,
read_default_file = defaults_file
)
Synthesized repair in: 4184ms
Tidyparse (valid/total): 404/722
Original error:
import os
import sys
from ctk_cli import CLIArgumentParser
sys.path.append(os.path.join(os.environ['ITK_BUILD_DIR'],
'Wrapping/Generators/Python'))
sys.path.append(os.path.join(os.environ['ITK_BUILD_DIR'], 'lib')
sys.path.append(os.environ['TUBETK_BUILD_DIR'], 'TubeTK-build/lib/TubeTK')
import itk
from itk import TubeTKITK as itktube
Good Repair:
import os
import sys
from ctk_cli import CLIArgumentParser
sys.path.append(os.path.join(os.environ['ITK_BUILD_DIR'],
'Wrapping/Generators/Python'))
** sys.path.append(os.path.joinos.environ['ITK_BUILD_DIR'], 'lib')
sys.path.append(os.environ['TUBETK_BUILD_DIR'], 'TubeTK-build/lib/TubeTK')
import itk
from itk import TubeTKITK as itktube
Synthesized repair in: 159634ms
Tidyparse (valid/total): 405/723
Original error:
def test_format_datetime():
from datetime import datetime
from ringo.lib.helpers import format_datetime
result = format_datetime(datetime(1977, 3, 12, 0, 0, 0)
assert result == u"1977-03-12 00: 00"
Good Repair:
def test_format_datetime():
from datetime import datetime
from ringo.lib.helpers import format_datetime
** result = format_datetimedatetime(1977, 3, 12, 0, 0, 0)
assert result == u"1977-03-12 00: 00"
Synthesized repair in: 13469ms
Tidyparse (valid/total): 406/724
Original error:
def usage_footer():
"""Simply prints a footer information, used with the `usage` method."""
print("""--See more information about this project at:""" %{
'url': constants.App.URL,
'source_url': constants.App.SOURCE_URL,
}
Bad Repair: invalid syntax (<unknown>, line 3):
def usage_footer():
"""Simply prints a footer information, used with the `usage` method."""
** print"""--See more information about this project at:""" %{
'url': constants.App.URL,
'source_url': constants.App.SOURCE_URL,
}
Synthesized repair in: 2913ms
Tidyparse (valid/total): 406/725
Original error:
def _get_pv(self):
key = self._post_pv_by_id_cache_key % self.id
cached = int(rd.get(key) if rd.get(key) else None
if cached is not None:
return cached
rd.set(key, self.pv_)
return self.pv_
Bad Repair: invalid syntax (<unknown>, line 3):
def _get_pv(self):
key = self._post_pv_by_id_cache_key % self.id
** cached = int(rd.get(key) if rd.getkey) else None
if cached is not None:
return cached
rd.set(key, self.pv_)
return self.pv_
Synthesized repair in: 12195ms
Tidyparse (valid/total): 406/726
Original error:
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
infourl = urllib.addinfourl(fp, headers, req.get_full_url()
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
Good Repair:
class NoRedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_302(self, req, fp, code, msg, headers):
** infourl = urllib.addinfourl(fp, headers, req.get_full_url)
infourl.status = code
infourl.code = code
return infourl
http_error_300 = http_error_302
http_error_301 = http_error_302
http_error_303 = http_error_302
http_error_307 = http_error_302
Synthesized repair in: 16242ms
Tidyparse (valid/total): 407/727
Original error:
def set_origin(self, ui_loc):
"""Set the origin to the upper-incisor location in global space."""
self.origin = mathutils.Vector((ui_loc)
self.ui_origin = True
Good Repair:
def set_origin(self, ui_loc):
"""Set the origin to the upper-incisor location in global space."""
** self.origin = mathutils.Vector(ui_loc)
self.ui_origin = True
Synthesized repair in: 13132ms
Tidyparse (valid/total): 408/728
Original error:
def patch_test():
data = {
"type": "statereminder",
"id": "8",
"attributes": {
"event": "Exit"
}
Bad Repair: invalid syntax (<unknown>, line 2):
def patch_test():
** data =
"type": "statereminder",
"id": "8",
"attributes": {
"event": "Exit"
}
Synthesized repair in: 5769ms
Tidyparse (valid/total): 408/729
Original error:
def _read_fixed_body(self, content_length, delegate):
while content_length > 0:
body = yield self.stream.read_bytes(
min(self.params.chunk_size, content_length), partial = True)
content_length -= len(body)
if not self._write_finished or self.is_client:
with _ExceptionLoggingContext(app_log):
yield gen.maybe_future(delegate.data_received(body)
Good Repair:
def _read_fixed_body(self, content_length, delegate):
while content_length > 0:
body = yield self.stream.read_bytes(
min(self.params.chunk_size, content_length), partial = True)
content_length -= len(body)
if not self._write_finished or self.is_client:
with _ExceptionLoggingContext(app_log):
** yield gen.maybe_futuredelegate.data_received(body)
Synthesized repair in: 246757ms
Tidyparse (valid/total): 409/730
Original error:
print("Hello World!")
print("print (something else")
for i in range(10)
print(i)
Bad Repair: invalid syntax (<unknown>, line 2):
print("Hello World!")
** print"print (something else")
for i in range(10)
print(i)
Synthesized repair in: 24838ms
Tidyparse (valid/total): 409/731
Original error:
def moderate_comment(comment, request):
ak = akismet.Akismet(
key = settings.AKISMET_API_KEY,
blog_url = 'http://%s/' % Site.objects.get_current().domain
Good Repair:
def moderate_comment(comment, request):
ak = akismet.Akismet(
key = settings.AKISMET_API_KEY,
** blog_url = 'http://%s/' % Site.objects.get_current).domain
Synthesized repair in: 8053ms
Tidyparse (valid/total): 410/732
Original error:
def addContent(self, content):
"""Add content to this value"""
self._buffer.extend(content.encode()
Good Repair:
def addContent(self, content):
"""Add content to this value"""
** self._buffer.extendcontent.encode()
Synthesized repair in: 3782ms
Tidyparse (valid/total): 411/733
Original error:
def appendData(self, content):
if not content.isspace():
raise TypeError("%s does not hold text" % type(self)
Good Repair:
def appendData(self, content):
if not content.isspace():
** raise TypeError("%s does not hold text" % typeself)
Synthesized repair in: 22447ms
Tidyparse (valid/total): 412/734
Original error:
def total_buildings(self):
"""The total number of buildings."""
return sum(self.buildings.values()
Good Repair:
def total_buildings(self):
"""The total number of buildings."""
** return sum(self.buildings.values)
Synthesized repair in: 3590ms
Tidyparse (valid/total): 413/735
Original error:
def numberOfProtocols(self):
if self.protocols:
return len(self.protocols()
else:
return 0
Good Repair:
def numberOfProtocols(self):
if self.protocols:
** return lenself.protocols()
else:
return 0
Synthesized repair in: 2402ms
Tidyparse (valid/total): 414/736
Original error:
def set_composer(self, to_be_set_name):
'''Sets the current composer.'''
current_composer = self.current_composer()
self.cursor.execute('''SELECT name'''
Bad Repair: invalid syntax (<unknown>, line 4):
def set_composer(self, to_be_set_name):
'''Sets the current composer.'''
current_composer = self.current_composer()
** self.cursor.execute'''SELECT name'''
Synthesized repair in: 3381ms
Tidyparse (valid/total): 414/737
Original error:
def _handleAuthenticate(self):
""" Handle click on form.button.Save """
client_id = self.flattr.customer_key
if client_id:
callback_uri = '%s/collective_flattr' % self.context.absolute_url()
self.request.response.redirect('%s?scope=thing&response_type=code'
'&redirect_uri=%s&client_id=%s' %(
self.flattr.authorize_url,
callback_uri,
client_id)
return True
IStatusMessage(self.request).add(_(u'Unable to create authorize '
'url.consumer and consumer_secret not configured: ('),
type = 'error')
return False
Bad Repair: invalid syntax (<unknown>, line 11):
def _handleAuthenticate(self):
""" Handle click on form.button.Save """
client_id = self.flattr.customer_key
if client_id:
callback_uri = '%s/collective_flattr' % self.context.absolute_url()
self.request.response.redirect('%s?scope=thing&response_type=code'
'&redirect_uri=%s&client_id=%s' %(
self.flattr.authorize_url,
callback_uri,
client_id)
return True
IStatusMessage(self.request).add(_(u'Unable to create authorize '
** 'url.consumer and consumer_secret not configured: )'),
type = 'error')
return False
Synthesized repair in: 380549ms
Tidyparse (valid/total): 414/738
Original error:
def loaddata(dfile = 'gaussian_mix.dat'):
data = np.genfromtxt(file(dfile)
return data
Good Repair:
def loaddata(dfile = 'gaussian_mix.dat'):
** data = np.genfromtxt(filedfile)
return data
Synthesized repair in: 22356ms
Tidyparse (valid/total): 415/739
Original error:
def rowAsList(self, index):
"""Get the data vals in a particular row by index."""
output = []
for obj in self._collection:
output.append(obj.getValue(index)
return output
Good Repair:
def rowAsList(self, index):
"""Get the data vals in a particular row by index."""
output = []
for obj in self._collection:
** output.append(obj.getValueindex)
return output
Synthesized repair in: 31997ms
Tidyparse (valid/total): 416/740
Original error:
def can_get_url(self, url):
try:
urllib2.urlopen(urllib2.Request(url)
return True
except:
return False
Good Repair:
def can_get_url(self, url):
try:
** urllib2.urlopen(urllib2.Requesturl)
return True
except:
return False
Synthesized repair in: 11819ms
Tidyparse (valid/total): 417/741
Original error:
def get_font(font_family, point_size):
font = pango.FontDescription('%s %d' %(font_family, point_size)
return font
Bad Repair: invalid syntax (<unknown>, line 2):
def get_font(font_family, point_size):
** font = pango.FontDescription'%s %d' %(font_family, point_size)
return font
Synthesized repair in: 3109ms
Tidyparse (valid/total): 417/742
Original error:
def test_action_missing_container_names(self):
data = '''{'''
with mock.patch.object(BlockadeManager,
'blockade_exists',
return_value = True):
result = self.client.post('/blockade/%s/action' % self.name,
headers = self.headers,
data = data)
self.assertEqual(400, result.status_code)
Bad Repair: unexpected indent (<unknown>, line 9):
def test_action_missing_container_names(self):
** data = ''''''
with mock.patch.object(BlockadeManager,
'blockade_exists',
return_value = True):
result = self.client.post('/blockade/%s/action' % self.name,
headers = self.headers,
data = data)
self.assertEqual(400, result.status_code)
Synthesized repair in: 52946ms
Tidyparse (valid/total): 417/743
Original error:
def get_instance_link(datum):
if datum.instance_type == 'compute':
return reverse("horizon: project: instances: detail",
args = (datum.instance_id, )
else:
return None
Bad Repair: invalid syntax (<unknown>, line 3):
def get_instance_link(datum):
if datum.instance_type == 'compute':
** return reverse"horizon: project: instances: detail",
args = (datum.instance_id, )
else:
return None
Synthesized repair in: 3822ms
Tidyparse (valid/total): 417/744
Original error:
def get(self, workflow_id, email_id):
"""Get information about an individual Automation workflow email."""
self.workflow_id = workflow_id
self.email_id = email_id
return self._mc_client._get(url = self._build_path(workflow_id, 'emails', email_id)
Bad Repair: invalid syntax (<unknown>, line 5):
def get(self, workflow_id, email_id):
"""Get information about an individual Automation workflow email."""
self.workflow_id = workflow_id
self.email_id = email_id
** return self._mc_client._geturl = self._build_path(workflow_id, 'emails', email_id)
Synthesized repair in: 6646ms
Tidyparse (valid/total): 417/745
Original error:
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')
lib_name = 'openerp'
Good Repair:
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
** execfile(joindirname(__file__), 'openerp', 'release.py')
lib_name = 'openerp'
Synthesized repair in: 2374ms
Tidyparse (valid/total): 418/746
Original error:
def position(d, n):
""" Defines the(x, y)position of the rose(d, n)."""
return[(1.1 *(2 * i - .6) * rose_radius) for i in[d, n]]]
Good Repair:
def position(d, n):
""" Defines the(x, y)position of the rose(d, n)."""
** return[(1.1 *(2 * i - .6) * rose_radius) for i in[d, n]]
Synthesized repair in: 41343ms
Tidyparse (valid/total): 419/747
Original error:
def _CreateAndConnectBrowserInspectorWebsocketIfNeeded(self):
if not self._browser_inspector_websocket:
self._browser_inspector_websocket = (
inspector_websocket.InspectorWebsocket()
self._browser_inspector_websocket.Connect(
BROWSER_INSPECTOR_WEBSOCKET_URL % self._devtools_port, timeout = 10)
Good Repair:
def _CreateAndConnectBrowserInspectorWebsocketIfNeeded(self):
if not self._browser_inspector_websocket:
self._browser_inspector_websocket = (
** inspector_websocket.InspectorWebsocket)
self._browser_inspector_websocket.Connect(
BROWSER_INSPECTOR_WEBSOCKET_URL % self._devtools_port, timeout = 10)
Synthesized repair in: 29973ms
Tidyparse (valid/total): 420/748
Original error:
def evaluate(batch_size, tag, epoch, sketch, img_dim = [64, 64, 1]):
model, model_name = edge2color(img_dim, batch_size = batch_size)
model.load_weights('%s/%s_weights_epoch_%s.h5' %(model_name, tag, epoch)
print('Load Model Complete')
plot_batch_eval(model, img_dim[0], batch_size = batch_size, sketch = sketch, tag = tag)
Bad Repair: invalid syntax (<unknown>, line 4):
def evaluate(batch_size, tag, epoch, sketch, img_dim = [64, 64, 1]):
model, model_name = edge2color(img_dim, batch_size = batch_size)
model.load_weights('%s/%s_weights_epoch_%s.h5' %(model_name, tag, epoch)
print('Load Model Complete')
** plot_batch_evalmodel, img_dim[0], batch_size = batch_size, sketch = sketch, tag = tag)
Synthesized repair in: 103458ms
Tidyparse (valid/total): 420/749
Original error:
"""Unittests for cros_list_overlays.py"""
from __future__ import print_function
import logging
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)),
'..', '..')
from chromite.lib import cros_test_lib
from chromite.lib import portage_util
from chromite.scripts import cros_list_overlays
Good Repair:
"""Unittests for cros_list_overlays.py"""
from __future__ import print_function
import logging
import os
import sys
** sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath__file__)),
'..', '..')
from chromite.lib import cros_test_lib
from chromite.lib import portage_util
from chromite.scripts import cros_list_overlays
Synthesized repair in: 4775ms
Tidyparse (valid/total): 421/750
Original error:
class BIC:
""" Bayesian Information Criterion """
def __init__(self):
self.__name = "BIC"
def getValue(self, n, df, SSE):
MSE = SSE / max(1.0, float(n)
return n * math.log(MSE) + df * log(n)
def getName(self):
return self.__name
Bad Repair: invalid syntax (<unknown>, line 7):
class BIC:
""" Bayesian Information Criterion """
def __init__(self):
self.__name = "BIC"
def getValue(self, n, df, SSE):
MSE = SSE / max(1.0, float(n)
return n * math.log(MSE) + df * log(n)
** def getNameself):
return self.__name
Synthesized repair in: 93303ms
Tidyparse (valid/total): 421/751
Original error:
def _upgrade_sort(self, mac1, mac2):
return((mac1.BEFORE_TAG == mac2.AFTER_TAG) -
(mac2.BEFORE_TAG == mac1.AFTER_TAG)
Bad Repair: invalid syntax (<unknown>, line 2):
def _upgrade_sort(self, mac1, mac2):
** return(mac1.BEFORE_TAG == mac2.AFTER_TAG) -
(mac2.BEFORE_TAG == mac1.AFTER_TAG)
Synthesized repair in: 21937ms
Tidyparse (valid/total): 421/752
Original error:
def highlight(msg, newline = True):
print('\033[92m' + msg + '\033[0m',
if newline:
print
Bad Repair: invalid syntax (<unknown>, line 2):
def highlight(msg, newline = True):
** print'\033[92m' + msg + '\033]0m',
if newline:
print
Synthesized repair in: 35255ms
Tidyparse (valid/total): 421/753
Original error:
def add_tx(self, txhash, txdata, status = TX_STATUS_UNKNOWN):
return self.execute(
"INSERT INTO tx_data(txhash, data, status)VALUES(?, ?, ?)",
(txhash, txdata, status)
Bad Repair: unexpected indent (<unknown>, line 3):
def add_tx(self, txhash, txdata, status = TX_STATUS_UNKNOWN):
** return self.execute
"INSERT INTO tx_data(txhash, data, status)VALUES(?, ?, ?)",
(txhash, txdata, status)
Synthesized repair in: 52332ms
Tidyparse (valid/total): 421/754
Original error:
def row_normalize(x):
"""Normalize rows of matrix x to unit(L2)norm."""
x_normed = x / T.sqrt(T.sum(x ** 2., axis = 1, keepdims = 1) + constFX(1e-8)
return x_normed
Good Repair:
def row_normalize(x):
"""Normalize rows of matrix x to unit(L2)norm."""
** x_normed = x / T.sqrt(T.sum(x ** 2., axis = 1, keepdims = 1) + constFX1e-8)
return x_normed
Synthesized repair in: 27962ms
Tidyparse (valid/total): 422/755
Original error:
class commandHandler:
def __init__(self):
print("commandhandler.py loaded")
def parse_question(self, user
Bad Repair: invalid syntax (<unknown>, line 4):
class commandHandler:
def __init__(self):
print("commandhandler.py loaded")
** def parse_questionself, user
Synthesized repair in: 35402ms
Tidyparse (valid/total): 422/756
Original error:
def set_debug(self, new):
"""Set debug mode."""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new)
old = self.debug
self.debug = new
self.stick.set_debug(new)
return old
Bad Repair: invalid syntax (<unknown>, line 6):
def set_debug(self, new):
"""Set debug mode."""
if type(new) is not bool:
raise pyhsm.exception.YHSM_WrongInputType(
'new', bool, type(new)
old = self.debug
self.debug = new
** self.stick.set_debugnew)
return old
Synthesized repair in: 13634ms
Tidyparse (valid/total): 422/757
Original error:
def __contains__(self, key):
HAS_ITEM = 'SELECT 1 FROM "%s" WHERE key = ?' % self.tablename
return self.conn.select_one(HAS_ITEM, (key, ) is not None
Good Repair:
def __contains__(self, key):
HAS_ITEM = 'SELECT 1 FROM "%s" WHERE key = ?' % self.tablename
** return self.conn.select_one(HAS_ITEM, key, ) is not None
Synthesized repair in: 14845ms
Tidyparse (valid/total): 423/758
Original error:
def retranslateUi(self, PyProfileDialog):
_translate = QtCore.QCoreApplication.translate
PyProfileDialog.setWindowTitle(_translate("PyProfileDialog", "Profile Results"))
PyProfileDialog.setWhatsThis(_translate("PyProfileDialog", "<b>Profile Results</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, PyProfileDialog):
_translate = QtCore.QCoreApplication.translate
PyProfileDialog.setWindowTitle(_translate("PyProfileDialog", "Profile Results"))
** PyProfileDialog.setWhatsThis(_translate)"PyProfileDialog", "<b>Profile Results</b>\n"
Synthesized repair in: 213316ms
Tidyparse (valid/total): 423/759
Original error:
def dispatch_callback(self, callback):
"""Dispatch to the callback object"""
self.callback_queue.put(lambda: callback.func(* callback.args)
Good Repair:
def dispatch_callback(self, callback):
"""Dispatch to the callback object"""
** self.callback_queue.put(lambda: callback.func* callback.args)
Synthesized repair in: 13172ms
Tidyparse (valid/total): 424/760
Original error:
class DDPG(chainer.Chain):
def __init__(self, n_actions):
initializer = chainer.initializers.HeNormal()
fc_unit = 256
super(DDPG, self).__init__(
fe = FeatureExtractor(n_actions),
fc1 = L.Linear(None, fc_unit, initialW = initializer),
fc2 = L.Linear(fc_unit, n_actions, initialW = initializer)
Bad Repair: unexpected indent (<unknown>, line 7):
class DDPG(chainer.Chain):
def __init__(self, n_actions):
initializer = chainer.initializers.HeNormal()
fc_unit = 256
super(DDPG, self).__init__(
** fe = FeatureExtractorn_actions),
fc1 = L.Linear(None, fc_unit, initialW = initializer),
fc2 = L.Linear(fc_unit, n_actions, initialW = initializer)
Synthesized repair in: 92087ms
Tidyparse (valid/total): 424/761
Original error:
import os
import sys
import inspect
from processing.core.Processing import Processing
from pysalprovider import pysalProvider
cmd_folder = os.path.split(inspect.getfile(inspect.currentframe())[0]
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
Good Repair:
import os
import sys
import inspect
from processing.core.Processing import Processing
from pysalprovider import pysalProvider
** cmd_folder = os.path.split(inspect.getfileinspect.currentframe())[0]
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
Synthesized repair in: 13133ms
Tidyparse (valid/total): 425/762
Original error:
def _default_layout_default(self):
return TaskLayout(
left = PaneItem('example.python_script_browser_pane')
Bad Repair: unexpected indent (<unknown>, line 3):
def _default_layout_default(self):
** return TaskLayout
left = PaneItem('example.python_script_browser_pane')
Synthesized repair in: 3567ms
Tidyparse (valid/total): 425/763
Original error:
def Run(self, * args, ** kwargs):
"""Runs a command on a remote node."""
return utils.RunCmd(self.BuildCmd(* args, ** kwargs)
Good Repair:
def Run(self, * args, ** kwargs):
"""Runs a command on a remote node."""
** return utils.RunCmdself.BuildCmd(* args, ** kwargs)
Synthesized repair in: 8975ms
Tidyparse (valid/total): 426/764
Original error:
def movingaverage(interval, window_size):
window = np.ones(int(window_size) / float(window_size)
return np.convolve(interval, window, 'same')
Good Repair:
def movingaverage(interval, window_size):
** window = np.ones(int(window_size) / floatwindow_size)
return np.convolve(interval, window, 'same')
Synthesized repair in: 29927ms
Tidyparse (valid/total): 427/765
Original error:
import random
from string import printable
from crypto_library import cbc_aes_encrypt, cbc_aes_decrypt
from urllib import quote
AES_KEY = ''.join(random.choice(printable) for _ in range(16)
BLOCKSIZE = 16
PREFIX = "comment1=cooking%20MCs; userdata=1"
SUFFIX = "; comment2=%20like%20a%20pound%20of%20bacon"
Good Repair:
import random
from string import printable
from crypto_library import cbc_aes_encrypt, cbc_aes_decrypt
from urllib import quote
** AES_KEY = ''.join(random.choice(printable) for _ in range16)
BLOCKSIZE = 16
PREFIX = "comment1=cooking%20MCs; userdata=1"
SUFFIX = "; comment2=%20like%20a%20pound%20of%20bacon"
Synthesized repair in: 2878ms
Tidyparse (valid/total): 428/766
Original error:
class Ui_menu(object):
def setupUi(self, menu):
menu.setObjectName("menu")
menu.resize(30, 23)
menu.setStyleSheet("QLabel {\n"
Bad Repair: unexpected EOF while parsing (<unknown>, line 5):
class Ui_menu(object):
def setupUi(self, menu):
menu.setObjectName("menu")
menu.resize(30, 23)
** menu.setStyleSheet("QLabel )\n"
Synthesized repair in: 216010ms
Tidyparse (valid/total): 428/767
Original error:
def debug_export(self, rows):
if self.debug:
print(self.get_output(rows)
Good Repair:
def debug_export(self, rows):
if self.debug:
** printself.get_output(rows)
Synthesized repair in: 6928ms
Tidyparse (valid/total): 429/768
Original error:
def str_to_ucps(s):
'''Translate a str object into a raw escaped unicode string literal.'''
return ''.join(hex(ord(c).replace('0x', r'\u') for c in s)
Bad Repair: invalid syntax (<unknown>, line 3):
def str_to_ucps(s):
'''Translate a str object into a raw escaped unicode string literal.'''
** return ''.join(hex(ord(c).replace'0x', r'\u') for c in s)
Synthesized repair in: 10780ms
Tidyparse (valid/total): 429/769
Original error:
def get_url(self):
url = "http: //%s: %s/q?start=%s&end=%s&%s&ascii" %(self.mhost, self.mport, self.start, self.end, string.join(self.metrics, '&')
return url
Good Repair:
def get_url(self):
** url = "http: //%s: %s/q?start=%s&end=%s&%s&ascii" %self.mhost, self.mport, self.start, self.end, string.join(self.metrics, '&')
return url
Synthesized repair in: 4055ms
Tidyparse (valid/total): 430/770
Original error:
def __init__(self, parent = None, iargs *):
'''init args'''
super(Show_apps, self) __init__ * parent)
for keyword in iargs:
if keyword == "stay":
self.playstay = keyword
Bad Repair: invalid syntax (<unknown>, line 1):
def __init__(self, parent = None, iargs *):
'''init args'''
** super(Show_apps, self __init__ * parent)
for keyword in iargs:
if keyword == "stay":
self.playstay = keyword
Synthesized repair in: 3804ms
Tidyparse (valid/total): 430/771
Original error:
def send(x):
kafka = KafkaClient("localhost: 9092")
producer = SimpleProducer(kafka)
for record in x:
producer.send_messages("instacounts", str(record)))
Good Repair:
def send(x):
kafka = KafkaClient("localhost: 9092")
producer = SimpleProducer(kafka)
for record in x:
** producer.send_messages("instacounts", str(record))
Synthesized repair in: 19016ms
Tidyparse (valid/total): 431/772
Original error:
def checkDimsOfYpredAndYEqual(y, yPred, stringTrainOrVal):
if y.ndim != yPred.ndim:
raise TypeError("ERROR! y did not have the same shape as y_pred during " + stringTrainOrVal,
('y', y.type, 'y_pred', yPred.type)
Bad Repair: invalid syntax (<unknown>, line 3):
def checkDimsOfYpredAndYEqual(y, yPred, stringTrainOrVal):
if y.ndim != yPred.ndim:
** raise TypeError"ERROR! y did not have the same shape as y_pred during " + stringTrainOrVal,
('y', y.type, 'y_pred', yPred.type)
Synthesized repair in: 7003ms
Tidyparse (valid/total): 431/773
Original error:
def replfunc(match):
global path_to_prepend
return 'classname="%s%s"' %(path_to_prepend, match.group(1)
Good Repair:
def replfunc(match):
global path_to_prepend
** return 'classname="%s%s"' %path_to_prepend, match.group(1)
Synthesized repair in: 7590ms
Tidyparse (valid/total): 432/774
Original error:
def dstar_changed(self, dstared, memedit):
memedit.set_urcall_list(dstared.editor_ucall.get_callsigns()
memedit.set_repeater_list(dstared.editor_rcall.get_callsigns())
memedit.prefill()
Bad Repair: invalid syntax (<unknown>, line 3):
def dstar_changed(self, dstared, memedit):
memedit.set_urcall_list(dstared.editor_ucall.get_callsigns()
** memedit.set_repeater_list(dstared.editor_rcall.get_callsigns))
memedit.prefill()
Synthesized repair in: 30399ms
Tidyparse (valid/total): 432/775
Original error:
def static(filename):
""" return static files """
return static_file(filename, root = "%s/static" %(base)
Bad Repair: invalid syntax (<unknown>, line 3):
def static(filename):
""" return static files """
** return static_filefilename, root = "%s/static" %(base)
Synthesized repair in: 13755ms
Tidyparse (valid/total): 432/776
Original error:
def retranslateUi(self, ModularInfo_dialog):
ModularInfo_dialog.setWindowTitle(_translate("ModularInfo_dialog", "How to select the Investigation Area", None))
self.textBrowser.setHtml(_translate("ModularInfo_dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, ModularInfo_dialog):
ModularInfo_dialog.setWindowTitle(_translate("ModularInfo_dialog", "How to select the Investigation Area", None))
** self.textBrowser.setHtml(_translate)"ModularInfo_dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 56017ms
Tidyparse (valid/total): 432/777
Original error:
def retranslateUi(self, BookmarkedFilesDialog):
_translate = QtCore.QCoreApplication.translate
BookmarkedFilesDialog.setWindowTitle(_translate("BookmarkedFilesDialog", "Configure Bookmarked Files Menu"))
self.deleteButton.setToolTip(_translate("BookmarkedFilesDialog", "Delete the selected entry"))
self.deleteButton.setWhatsThis(_translate("BookmarkedFilesDialog", "<b>Delete</b>\n"
Bad Repair: invalid syntax (<unknown>, line 5):
def retranslateUi(self, BookmarkedFilesDialog):
_translate = QtCore.QCoreApplication.translate
BookmarkedFilesDialog.setWindowTitle(_translate("BookmarkedFilesDialog", "Configure Bookmarked Files Menu"))
self.deleteButton.setToolTip(_translate("BookmarkedFilesDialog", "Delete the selected entry"))
** self.deleteButton.setWhatsThis(_translate)"BookmarkedFilesDialog", "<b>Delete</b>\n"
Synthesized repair in: 841041ms
Tidyparse (valid/total): 432/778
Original error:
def addFilter(self, pattern, name):
def filter(block, handler):
return re.sub(pattern, handler.sub(name), block)
self.filters.append filter)
Bad Repair: invalid syntax (<unknown>, line 4):
def addFilter(self, pattern, name):
def filter(block, handler):
** return re.sub(pattern, handler.sub(name, block)
self.filters.append filter)
Synthesized repair in: 11148ms
Tidyparse (valid/total): 432/779
Original error:
import sys
for i, line in enumerate(sys.stdin):
print("%s: %s" %(i, line)
Good Repair:
import sys
for i, line in enumerate(sys.stdin):
** print("%s: %s" %i, line)
Synthesized repair in: 13125ms
Tidyparse (valid/total): 433/780
Original error:
}
= [x
while True:
try:
pass
except:
print('Whoops')
if msg:
errmsg = msg % progress.get(cr_dbname))
Bad Repair: invalid syntax (<unknown>, line 2):
**
** = (x
while True:
try:
pass
except:
** print'Whoops'(
if msg:
** errmsg = msg % progress.get)cr_dbname(
** ))
Synthesized repair in: 141812ms
Tidyparse (valid/total): 433/781
Original error:
import re
from ftrace.common import ParserError
from ftrace.globals import SCHED_RAVG_WINDOW
from.register import register_parser
from collections import namedtuple
TRACEPOINT = 'sched_task_load'
__all__ = [TRACEPOINT]
[
'pid',
'comm',
'sum',
'sum_scaled',
'period',
'demand',
'small',
'boost',
'reason',
'sync',
'prefer_idle',
]
)
Bad Repair: unexpected indent (<unknown>, line 8):
import re
from ftrace.common import ParserError
from ftrace.globals import SCHED_RAVG_WINDOW
from.register import register_parser
from collections import namedtuple
TRACEPOINT = 'sched_task_load'
__all__ = [TRACEPOINT]
[
'pid',
'comm',
'sum',
'sum_scaled',
'period',
'demand',
'small',
'boost',
'reason',
'sync',
'prefer_idle',
]
**
Synthesized repair in: 7189ms
Tidyparse (valid/total): 433/782
Original error:
import math
import sys
import autopy
print('Hello World \n')
print(dir(autopy)
Good Repair:
import math
import sys
import autopy
print('Hello World \n')
** printdir(autopy)
Synthesized repair in: 13652ms
Tidyparse (valid/total): 434/783
Original error:
def remove_child(self, child):
if self.has_child(child):
self.children.remove(child.get_id()
return True
return False
Good Repair:
def remove_child(self, child):
if self.has_child(child):
** self.children.remove(child.get_id)
return True
return False
Synthesized repair in: 21970ms
Tidyparse (valid/total): 435/784
Original error:
def audience(self):
"""Return audience by priority, so: All or User, Group"""
targets = filter(lambda item: item, (self.user, self.group, )
return ", ".join([unicode(t) for t in targets]) or 'No one'
Good Repair:
def audience(self):
"""Return audience by priority, so: All or User, Group"""
** targets = filter(lambda item: item, self.user, self.group, )
return ", ".join([unicode(t) for t in targets]) or 'No one'
Synthesized repair in: 67814ms
Tidyparse (valid/total): 436/785
Original error:
def add_console_handlers(self):
stdout_handler = self.add_stream_handler(sys.stdout,
level = self.stdout_level)
stdout_handler.addFilter(AllowBelowSeverity(self.stderr_level)
self.add_stream_handler(sys.stderr, self.stderr_level)
Good Repair:
def add_console_handlers(self):
stdout_handler = self.add_stream_handler(sys.stdout,
level = self.stdout_level)
** stdout_handler.addFilterAllowBelowSeverity(self.stderr_level)
self.add_stream_handler(sys.stderr, self.stderr_level)
Synthesized repair in: 39609ms
Tidyparse (valid/total): 437/786
Original error:
def get_all_credentials(tenant_id):
"""Lists all the creds for a tenant."""
session = db.get_session()
return(session.query(network_models_v2.Credential).
filter_by(tenant_id = tenant_id).all()
Bad Repair: invalid syntax (<unknown>, line 4):
def get_all_credentials(tenant_id):
"""Lists all the creds for a tenant."""
session = db.get_session()
** return(session.querynetwork_models_v2.Credential).
filter_by(tenant_id = tenant_id).all()
Synthesized repair in: 13789ms
Tidyparse (valid/total): 437/787
Original error:
def step_it_should_fail_with_result(context, result):
assert_that(context.command_result.returncode, equal_to(result)
assert_that(result, is_not(equal_to(0)))
Bad Repair: invalid syntax (<unknown>, line 3):
def step_it_should_fail_with_result(context, result):
assert_that(context.command_result.returncode, equal_to(result)
** assert_thatresult, is_not(equal_to(0)))
Synthesized repair in: 10253ms
Tidyparse (valid/total): 437/788
Original error:
def suite(self):
testSuite = unittest.TestSuite()
testSuite.addTest(unittest.makeSuite(TestOmxplayer)
return testSuite
Good Repair:
def suite(self):
testSuite = unittest.TestSuite()
** testSuite.addTestunittest.makeSuite(TestOmxplayer)
return testSuite
Synthesized repair in: 31508ms
Tidyparse (valid/total): 438/789
Original error:
def main(argmodel_to_build, argcolor_pin_mark):
global color_pin_mark
global model_to_build
global excluded_pins_xmirror
global excluded_pins_x
color_pin_mark = argcolor_pin_mark
model_to_build = argmodel_to_build
if model_to_build == "all":
for i in range(1, 4):
build_and_save(i)
else:
build_and_save(int(model_to_build)
Good Repair:
def main(argmodel_to_build, argcolor_pin_mark):
global color_pin_mark
global model_to_build
global excluded_pins_xmirror
global excluded_pins_x
color_pin_mark = argcolor_pin_mark
model_to_build = argmodel_to_build
if model_to_build == "all":
for i in range(1, 4):
build_and_save(i)
else:
** build_and_save(intmodel_to_build)
Synthesized repair in: 35177ms
Tidyparse (valid/total): 439/790
Original error:
def functionLight(bot, update):
luxes = light.value()
bot.sendMessage(update.message.chat_id, text = 'Light ' + str(luxes)
Good Repair:
def functionLight(bot, update):
luxes = light.value()
** bot.sendMessageupdate.message.chat_id, text = 'Light ' + str(luxes)
Synthesized repair in: 13596ms
Tidyparse (valid/total): 440/791
Original error:
def test_claim_bucket(self):
a = self.o.claim_bucket()
self.assertTrue(self.o.exists(a)
Good Repair:
def test_claim_bucket(self):
a = self.o.claim_bucket()
** self.assertTrueself.o.exists(a)
Synthesized repair in: 14102ms
Tidyparse (valid/total): 441/792
Original error:
def druk_af(self):
print('* regel')
for attribute, value in vars(self).iteritems():
try:
print(' ' + attribute + ': ' + str(value)
except Exception:
print(' ' + attribute + ': <not printable>')
print('')
Bad Repair: invalid syntax (<unknown>, line 6):
def druk_af(self):
print('* regel')
for attribute, value in vars(self).iteritems():
try:
print(' ' + attribute + ': ' + str(value)
except Exception:
** print' ' + attribute + ': <not printable>')
print('')
Synthesized repair in: 158147ms
Tidyparse (valid/total): 441/793
Original error:
import os
from kiki.utils.data import readlines
MECAB_DICT = '-Ochasen'
STOPWORDS = {
'jp': readlines('%s/config/locale/jp/stopwords' % os.path.dirname(os.path.abspath(__file__))
}
Good Repair:
import os
from kiki.utils.data import readlines
MECAB_DICT = '-Ochasen'
STOPWORDS = {
** 'jp': readlines('%s/config/locale/jp/stopwords' % os.path.dirname(os.path.abspath__file__))
}
Synthesized repair in: 11730ms
Tidyparse (valid/total): 442/794
Original error:
def convertBstrToDecStr(bstr):
istr = "".join(map(lambda b: format(
return bstr
Good Repair:
def convertBstrToDecStr(bstr):
** istr = "".join(map(lambda b: format))
return bstr
Synthesized repair in: 77077ms
Tidyparse (valid/total): 443/795
Original error:
def __repr__(self):
return 'rosetta.%s object at %s' %(self.__class__.__name__,
hex(id(self))
Bad Repair: unexpected indent (<unknown>, line 3):
def __repr__(self):
** return 'rosetta.%s object at %s' %self.__class__.__name__,
hex(id(self))
Synthesized repair in: 11856ms
Tidyparse (valid/total): 443/796
Original error:
def print_trace(self):
print("HighchartJsonBuilderException: [code %(code)s] %(message)s\n%(trace)s" %{
'code': self.code,
'message': self.msg,
'trace': self.trace
}
Bad Repair: unexpected EOF while parsing (<unknown>, line 7):
def print_trace(self):
** print("HighchartJsonBuilderException: [code %(code)s] %(message)s\n%trace)s" %{
'code': self.code,
'message': self.msg,
'trace': self.trace
}
Synthesized repair in: 254888ms
Tidyparse (valid/total): 443/797
Original error:
def _last_marker(f_path, l_obj):
"""Set Marker."""
return '%s&marker=%s' %(f_path, quoter(url = l_obj)
Good Repair:
def _last_marker(f_path, l_obj):
"""Set Marker."""
** return '%s&marker=%s' %f_path, quoter(url = l_obj)
Synthesized repair in: 12629ms
Tidyparse (valid/total): 444/798
Original error:
def setUp(self):
self.threshold = 3
self.loc = get_test_files()
self.expected_informative_sites = numpy.load(os.path.join(self.loc, 'chr1_918-test-cutoff-values.npy')
Good Repair:
def setUp(self):
self.threshold = 3
self.loc = get_test_files()
** self.expected_informative_sites = numpy.loados.path.join(self.loc, 'chr1_918-test-cutoff-values.npy')
Synthesized repair in: 14471ms
Tidyparse (valid/total): 445/799
Original error:
def test_validate_username(self):
"""Test that username inputs are validated."""
with self.assertRaises(click.BadParameter):
'testfile', 'http://127.0.0.1/daily_user_summary.txt.bz2',
'nonexistent_user', False)
Good Repair:
def test_validate_username(self):
"""Test that username inputs are validated."""
with self.assertRaises(click.BadParameter):
'testfile', 'http://127.0.0.1/daily_user_summary.txt.bz2',
** 'nonexistent_user', False
Synthesized repair in: 13486ms
Tidyparse (valid/total): 446/800
Original error:
def test_ToGS1(self):
print("***==== Test GS1 ====***"
epc = self._sgln96.encode(self._companyPrefix, None, self._locationReference, self._filter, self._extension)
print(epc.toGS1())
print("***==== END Test To GS1 ====***"
print(""
Bad Repair: invalid syntax (<unknown>, line 2):
def test_ToGS1(self):
** print"***==== Test GS1 ====***"
epc = self._sgln96.encode(self._companyPrefix, None, self._locationReference, self._filter, self._extension)
print(epc.toGS1())
print("***==== END Test To GS1 ====***"
** print)""
Synthesized repair in: 83696ms
Tidyparse (valid/total): 446/801
Original error:
def get_resource(filename):
import os.path
import pkg_resources
return pkg_resources.resource_filename("deluge.plugins.toggle",
os.path.join("data", filename)
Bad Repair: invalid syntax (<unknown>, line 5):
def get_resource(filename):
import os.path
import pkg_resources
return pkg_resources.resource_filename("deluge.plugins.toggle",
** os.path.join"data", filename)
Synthesized repair in: 16756ms
Tidyparse (valid/total): 446/802
Original error:
def c_2():
i = 0
while i < len(L):
bark_like_a_dog[L[i: ]
i += 1
Good Repair:
def c_2():
i = 0
while i < len(L):
** bark_like_a_dog[Li: ]
i += 1
Synthesized repair in: 23540ms
Tidyparse (valid/total): 447/803
Original error:
def update_lambda_star(self):
self.lambda_star = - 1 * np.dot(
self.xk_1,
np.dot(self.A, self.xk_1) + self.b
Good Repair:
def update_lambda_star(self):
self.lambda_star = - 1 * np.dot(
self.xk_1,
** np.dotself.A, self.xk_1) + self.b
Synthesized repair in: 8702ms
Tidyparse (valid/total): 448/804
Original error:
def test_for_update_sql_generated(self):
"""The backend's FOR UPDATE variant appears in"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update())
self.assertTrue(self.has_for_update_sql(ctx.captured_queries)
Good Repair:
def test_for_update_sql_generated(self):
"""The backend's FOR UPDATE variant appears in"""
with transaction.atomic(), CaptureQueriesContext(connection) as ctx:
list(Person.objects.all().select_for_update())
** self.assertTrueself.has_for_update_sql(ctx.captured_queries)
Synthesized repair in: 43161ms
Tidyparse (valid/total): 449/805
Original error:
def expected_parameters(self):
for lookup, title in self.lookup_choices:
self.using_params.append(self._make_param(lookup)
return self.using_params
Good Repair:
def expected_parameters(self):
for lookup, title in self.lookup_choices:
** self.using_params.appendself._make_param(lookup)
return self.using_params
Synthesized repair in: 8605ms
Tidyparse (valid/total): 450/806
Original error:
def get_endpoint_location_data():
return[{
"input": {
"node-connector-id": "openflow:3:1",
"node-id": "openflow:3",
"faas-port-ref-id": "24eb3395-6c59-443a-9048-4c0b02ce1471"
}
Bad Repair: illegal target for annotation (<unknown>, line 3):
def get_endpoint_location_data():
** return[]
"input": {
"node-connector-id": "openflow:3:1",
"node-id": "openflow:3",
"faas-port-ref-id": "24eb3395-6c59-443a-9048-4c0b02ce1471"
}
Synthesized repair in: 3667ms
Tidyparse (valid/total): 450/807
Original error:
def before_start(self, test, host = None):
self._install_clients()
self._run_clients(test, self._get_hosts(host)
Good Repair:
def before_start(self, test, host = None):
self._install_clients()
** self._run_clients(test, self._get_hostshost)
Synthesized repair in: 16910ms
Tidyparse (valid/total): 451/808
Original error:
def removeConfig(self, scope, keys):
"""Returns void"""
for
key = None
in keys) _configAccessor.remove(scope, key)
Bad Repair: invalid syntax (<unknown>, line 3):
** def removeConfig(self, scope, keys:
"""Returns void"""
for
key = None
in keys) _configAccessor.remove(scope, key)
Synthesized repair in: 7763ms
Tidyparse (valid/total): 451/809
Original error:
def _get_filename(self):
return '%s/%s-%s%s' %(self.data_dir, self.filename_prefix,
time.strftime('%Y-%m-%dT%H-%M-%SZ',
time.gmtime(),
'.gz' if self.compress else '')
Bad Repair: unexpected indent (<unknown>, line 3):
def _get_filename(self):
** return '%s/%s-%s%s' %self.data_dir, self.filename_prefix,
time.strftime('%Y-%m-%dT%H-%M-%SZ',
time.gmtime(),
'.gz' if self.compress else '')
Synthesized repair in: 12404ms
Tidyparse (valid/total): 451/810
Original error:
def login_and_get_list(self, username, password):
LOGIN_URL = "http://braintrust.iwtstudents.com/users/login"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Connection': 'keep-alive'
Bad Repair: invalid syntax (<unknown>, line 3):
def login_and_get_list(self, username, password):
LOGIN_URL = "http://braintrust.iwtstudents.com/users/login"
** headers =
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Connection': 'keep-alive'
Synthesized repair in: 8735ms
Tidyparse (valid/total): 451/811
Original error:
def print_matrix(matr):
for row in matr:
print("[",
for ent in row:
print("%2.3f " % ent, )
print("]")
Bad Repair: invalid syntax (<unknown>, line 4):
def print_matrix(matr):
for row in matr:
print("[",
for ent in row:
print("%2.3f " % ent, )
** print"]")
Synthesized repair in: 119818ms
Tidyparse (valid/total): 451/812
Original error:
def Deserialize(self, value, context):
if value == - 1:
if not self.nullable:
raise serialization.DeserializationException(
'Trying to deserialize null for non nullable type.')
return self.FromHandle(mojo_system.Handle())
return self.FromHandle(context.ClaimHandle(value)
Good Repair:
def Deserialize(self, value, context):
if value == - 1:
if not self.nullable:
raise serialization.DeserializationException(
'Trying to deserialize null for non nullable type.')
return self.FromHandle(mojo_system.Handle())
** return self.FromHandle(context.ClaimHandlevalue)
Synthesized repair in: 49880ms
Tidyparse (valid/total): 452/813
Original error:
def test_is_scenario_not_scenario(self):
scenario = dummy.Dummy()
self.assertFalse(base.Scenario.is_scenario(scenario,
"_random_fail_emitter")
Good Repair:
def test_is_scenario_not_scenario(self):
scenario = dummy.Dummy()
** self.assertFalsebase.Scenario.is_scenario(scenario,
"_random_fail_emitter")
Synthesized repair in: 16879ms
Tidyparse (valid/total): 453/814
Original error:
def pin_thread(request, course_id, thread_id):
"""given a course id and thread id, pin this thread"""
course_key = CourseKey.from_string(course_id)
user = cc.User.from_django_user(request.user)
thread = cc.Thread.find(thread_id)
thread.pin(user, thread_id)
return JsonResponse(prepare_content(thread.to_dict(), course_key)
Good Repair:
def pin_thread(request, course_id, thread_id):
"""given a course id and thread id, pin this thread"""
course_key = CourseKey.from_string(course_id)
user = cc.User.from_django_user(request.user)
thread = cc.Thread.find(thread_id)
thread.pin(user, thread_id)
** return JsonResponse(prepare_contentthread.to_dict(), course_key)
Synthesized repair in: 103670ms
Tidyparse (valid/total): 454/815
Original error:
def coerced_input(prompt, type_ = float):
"""Continue asking user for input"""
while True:
try:
return type_(input(prompt)
except ValueError:
pass
Good Repair:
def coerced_input(prompt, type_ = float):
"""Continue asking user for input"""
while True:
try:
** return type_input(prompt)
except ValueError:
pass
Synthesized repair in: 17108ms
Tidyparse (valid/total): 455/816
Original error:
class Diff(_Merge):
"""Layer that takes difference of a list of inputs."""
def _merge_function(self, inputs):
output = inputs[0]
for i in range(1, len(inputs):
output -= inputs[i]
return output
Good Repair:
class Diff(_Merge):
"""Layer that takes difference of a list of inputs."""
def _merge_function(self, inputs):
output = inputs[0]
** for i in range1, len(inputs):
output -= inputs[i]
return output
Synthesized repair in: 203562ms
Tidyparse (valid/total): 456/817
Original error:
def ExpectEq(expected, actual):
if expected != actual:
print('Expected "%s", got "%s"' %(expected, actual)
test.fail_test()
Bad Repair: invalid syntax (<unknown>, line 4):
def ExpectEq(expected, actual):
if expected != actual:
print('Expected "%s", got "%s"' %(expected, actual)
** test.fail_test)
Synthesized repair in: 4402ms
Tidyparse (valid/total): 456/818
Original error:
def get_textbook_count(self):
"""Returns the count of textbooks"""
return len(self.q(css = '.textbooks-list.textbook')
Good Repair:
def get_textbook_count(self):
"""Returns the count of textbooks"""
** return lenself.q(css = '.textbooks-list.textbook')
Synthesized repair in: 2751ms
Tidyparse (valid/total): 457/819
Original error:
class UserView(viewsets.ModelViewSet):
serializer_class = serializers.UserSerializer
model = User
def get_permissions(self):
return(AllowAny() if self.request.method == 'POST'
Bad Repair: invalid syntax (<unknown>, line 5):
class UserView(viewsets.ModelViewSet):
serializer_class = serializers.UserSerializer
model = User
def get_permissions(self):
** return(AllowAny) if self.request.method == 'POST'
Synthesized repair in: 16543ms
Tidyparse (valid/total): 457/820
Original error:
def check_protocol_version(self, client_version):
"""Requests the current protocol version implemented by the server."""
if client_version == VERSION:
self.log.debug("Client version matches server version: %s" % client_version)
else:
self.log.warn("Version MISMATCH: %s (server), %s (client)" %(VERSION, client_version)
return VERSION
Bad Repair: invalid syntax (<unknown>, line 6):
def check_protocol_version(self, client_version):
"""Requests the current protocol version implemented by the server."""
if client_version == VERSION:
self.log.debug("Client version matches server version: %s" % client_version)
else:
** self.log.warn"Version MISMATCH: %s (server), %s (client)" %(VERSION, client_version)
return VERSION
Synthesized repair in: 19207ms
Tidyparse (valid/total): 457/821
Original error:
def __init__(self, name = '', dogs = 'reliable', monkies = 'tricksy'):
self.name = name
self._critters = (('dogs', dogs), ('monkies', monkies)
Good Repair:
def __init__(self, name = '', dogs = 'reliable', monkies = 'tricksy'):
self.name = name
** self._critters = (('dogs', dogs), 'monkies', monkies)
Synthesized repair in: 6065ms
Tidyparse (valid/total): 458/822
Original error:
def test_remove_tags(ansible_tags, provider):
"""This test removes tags from the Containers Provider"""
setup_ansible_script(provider, script = 'remove_tags',
values_to_update = tags_to_add,
script_type = 'tags')
run_ansible('remove_tags')
gui_tags = str(get_smart_management(provider)
assert tags_after_deletion in gui_tags
Good Repair:
def test_remove_tags(ansible_tags, provider):
"""This test removes tags from the Containers Provider"""
setup_ansible_script(provider, script = 'remove_tags',
values_to_update = tags_to_add,
script_type = 'tags')
run_ansible('remove_tags')
** gui_tags = str(get_smart_managementprovider)
assert tags_after_deletion in gui_tags
Synthesized repair in: 35221ms
Tidyparse (valid/total): 459/823
Original error:
def dir_base(f = None, up_dir = 0):
if not f:
f = __file__
b = os.path.dirname(os.path.abspath(f)
for i in range(up_dir):
b = os.path.join(b, '../')
return b
Bad Repair: invalid syntax (<unknown>, line 5):
def dir_base(f = None, up_dir = 0):
if not f:
f = __file__
b = os.path.dirname(os.path.abspath(f)
for i in range(up_dir):
** b = os.path.joinb, '../')
return b
Synthesized repair in: 11665ms
Tidyparse (valid/total): 459/824
Original error:
def send_message(text):
client = TwilioRestClient(account_sid, auth_token)
message = client.sms.messages.create(
body = text,
to = "REDACTED",
from_ = "REDACTED"
Bad Repair: unexpected indent (<unknown>, line 4):
def send_message(text):
client = TwilioRestClient(account_sid, auth_token)
** message = client.sms.messages.create
body = text,
to = "REDACTED",
from_ = "REDACTED"
Synthesized repair in: 38957ms
Tidyparse (valid/total): 459/825
Original error:
def addAssembly(self, memonic, params):
params = params.replace("FLAT: ", "")
self.sections[self.currentSectionName].content.append({"type": EnumSectionContentType.MEMONIC, "data": {"memonic": memonic, "params": params})
Bad Repair: invalid syntax (<unknown>, line 3):
def addAssembly(self, memonic, params):
params = params.replace("FLAT: ", "")
** self.sections[self.currentSectionName].content.append("type": EnumSectionContentType.MEMONIC, "data": {"memonic": memonic, "params": params})
Synthesized repair in: 48391ms
Tidyparse (valid/total): 459/826
Original error:
def hobj(symb, width):
"""Construct horizontal object of a given width"""
return ''.join(xobj(symb, width)
Good Repair:
def hobj(symb, width):
"""Construct horizontal object of a given width"""
** return ''.joinxobj(symb, width)
Synthesized repair in: 6879ms
Tidyparse (valid/total): 460/827
Original error:
def status(self):
return "Pool size: %d Connections in pool: %d " "Current Overflow: %d Current Checked out " "connections: %d" %(self.size(),
self.checkedin(),
self.overflow(),
self.checkedout()
Bad Repair: unexpected indent (<unknown>, line 4):
def status(self):
return "Pool size: %d Connections in pool: %d " "Current Overflow: %d Current Checked out " "connections: %d" %(self.size(),
** self.checkedin),
self.overflow(),
self.checkedout()
Synthesized repair in: 10255ms
Tidyparse (valid/total): 460/828
Original error:
def sortedLayerViews(self):
"""Cached list of layer views sorted by zValue."""
if not self._sortedLayerViews:
self._sortedLayerViews = sorted(self.layerViews, lambda a, b: cmp(a.layer.zValue, b.layer.zValue)
return self._sortedLayerViews
Good Repair:
def sortedLayerViews(self):
"""Cached list of layer views sorted by zValue."""
if not self._sortedLayerViews:
** self._sortedLayerViews = sortedself.layerViews, lambda a, b: cmp(a.layer.zValue, b.layer.zValue)
return self._sortedLayerViews
Synthesized repair in: 2938ms
Tidyparse (valid/total): 461/829
Original error:
def process_message(self, msg):
try:
ret = self._process_message(msg)
if isinstance(ret, proto.Failure):
self.set_main_state()
return ret
except Exception as exc:
traceback.print_exc()
self.set_main_state()
return proto.Failure(message = str(exc)
Bad Repair: invalid syntax (<unknown>, line 10):
def process_message(self, msg):
try:
ret = self._process_message(msg)
if isinstance(ret, proto.Failure):
self.set_main_state()
return ret
except Exception as exc:
traceback.print_exc()
self.set_main_state()
** return proto.Failuremessage = str(exc)
Synthesized repair in: 416350ms
Tidyparse (valid/total): 461/830
Original error:
def imprimir_matriz(lista):
for elemento in lista:
if elemento.tipo == 'LITERAL_MATRICIAL':
print("{",
imprimir_matriz(elemento.exp))
Bad Repair: expected an indented block (<unknown>, line 4):
def imprimir_matriz(lista):
for elemento in lista:
if elemento.tipo == 'LITERAL_MATRICIAL':
** print("",
imprimir_matriz(elemento.exp))
Synthesized repair in: 28840ms
Tidyparse (valid/total): 461/831
Original error:
import itertools
import numpy as np
from artist import Plot, PolarPlot
from sapphire.analysis.direction_reconstruction import(
DirectAlgorithm, DirectAlgorithmCartesian2D, DirectAlgorithmCartesian3D)
from sapphire.clusters import SingleDiamondStation
FitAlgorithm)
TIME_RESOLUTION = 2.5
C = .3
COLORS = ['black', 'red', 'green', 'blue']
Bad Repair: invalid syntax (<unknown>, line 6):
import itertools
import numpy as np
from artist import Plot, PolarPlot
from sapphire.analysis.direction_reconstruction import(
** DirectAlgorithm, DirectAlgorithmCartesian2D, DirectAlgorithmCartesian3D
from sapphire.clusters import SingleDiamondStation
FitAlgorithm)
TIME_RESOLUTION = 2.5
C = .3
COLORS = ['black', 'red', 'green', 'blue']
Synthesized repair in: 3991ms
Tidyparse (valid/total): 461/832
Original error:
class GMLRangeBase(GMLBase):
TAG = "RangeBase"
def __init__(self, limits, * children, ** attributes):
super(GMLRangeBase, self).__init__(* children, ** attributes)
self.text = (" %s" * len(limits).lstrip(' ')
Good Repair:
class GMLRangeBase(GMLBase):
TAG = "RangeBase"
def __init__(self, limits, * children, ** attributes):
super(GMLRangeBase, self).__init__(* children, ** attributes)
** self.text = (" %s" * lenlimits).lstrip(' ')
Synthesized repair in: 99528ms
Tidyparse (valid/total): 462/833
Original error:
def discard_changes(self, _):
self.datastore.reset()
return Response(etree.Element("ok")
Good Repair:
def discard_changes(self, _):
self.datastore.reset()
** return Responseetree.Element("ok")
Synthesized repair in: 4779ms
Tidyparse (valid/total): 463/834
Original error:
def report_retry(self, count, retries):
"""Report retry in case of HTTP error 5xx"""
self.to_screen('[download]Got server HTTP error.Retrying(attempt %d of %d)...' %(count, retries)
Bad Repair: unexpected EOF while parsing (<unknown>, line 4):
def report_retry(self, count, retries):
"""Report retry in case of HTTP error 5xx"""
** self.to_screen('[download]Got server HTTP error.Retryingattempt %d of %d)...' %(count, retries)
Synthesized repair in: 9023ms
Tidyparse (valid/total): 463/835
Original error:
def retranslateUi(self, HgQueuesListDialog):
_translate = QtCore.QCoreApplication.translate
HgQueuesListDialog.setWindowTitle(_translate("HgQueuesListDialog", "List of Patches"))
HgQueuesListDialog.setWhatsThis(_translate("HgQueuesListDialog", "<b>List of Patches</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, HgQueuesListDialog):
_translate = QtCore.QCoreApplication.translate
HgQueuesListDialog.setWindowTitle(_translate("HgQueuesListDialog", "List of Patches"))
** HgQueuesListDialog.setWhatsThis(_translate)"HgQueuesListDialog", "<b>List of Patches</b>\n"
Synthesized repair in: 268420ms
Tidyparse (valid/total): 463/836
Original error:
def getAbsPath(path):
"""Return None or a normalized absolute path version of the argument string."""
if path is None:
return None
if path.strip() == "":
return None
path = os.path.normcase(os.path.expanduser(path)
if os.path.isabs(path):
return path
else:
return os.path.abspath(path)
Good Repair:
def getAbsPath(path):
"""Return None or a normalized absolute path version of the argument string."""
if path is None:
return None
if path.strip() == "":
return None
** path = os.path.normcaseos.path.expanduser(path)
if os.path.isabs(path):
return path
else:
return os.path.abspath(path)
Synthesized repair in: 17303ms
Tidyparse (valid/total): 464/837
Original error:
def __repr__(self):
"""Generate a represention of the Circle as a string"""
return "(%s, %f)" %(self.getCentre().__repr__(),
self.getRadius()))
Bad Repair: unmatched ')' (<unknown>, line 4):
def __repr__(self):
"""Generate a represention of the Circle as a string"""
** return "(%s, %f" %(self.getCentre().__repr__(),
self.getRadius()))
Synthesized repair in: 11895ms
Tidyparse (valid/total): 464/838
Original error:
def receive_packet_out(self, logical_device_id, egress_port_no, msg):
log.info('packet-out', logical_device_id = logical_device_id,
egress_port_no = egress_port_no, msg_len = len(msg)
Good Repair:
def receive_packet_out(self, logical_device_id, egress_port_no, msg):
log.info('packet-out', logical_device_id = logical_device_id,
** egress_port_no = egress_port_no, msg_len = lenmsg)
Synthesized repair in: 19091ms
Tidyparse (valid/total): 465/839
Original error:
def json_loads(s):
try:
obj = json.loads(s)
except:
obj = json.loads(s.decode()
return obj
Good Repair:
def json_loads(s):
try:
obj = json.loads(s)
except:
** obj = json.loadss.decode()
return obj
Synthesized repair in: 17817ms
Tidyparse (valid/total): 466/840
Original error:
def get_rc(limit, session):
actions = session.recent_changes.query(
type = "edit",
properties = "ids", "sha1", "timestamp"},
direction = "newer",
limit = limit
)
return actions
Bad Repair: positional argument follows keyword argument (<unknown>, line 4):
def get_rc(limit, session):
actions = session.recent_changes.query(
type = "edit",
** properties = "ids", "sha1", "timestamp",
direction = "newer",
limit = limit
)
return actions
Synthesized repair in: 7979ms
Tidyparse (valid/total): 466/841
Original error:
def test_convert_webpage(self):
json_data = {"LoadingDocumentUrl": "http://google.com",
"SaveOptions": {
"Password": None,
"SaveRoutingSlip": True,
"SaveFormat": "doc",
"FileName": "google.doc",
"DmlRenderingMode": None,
"DmlEffectsRenderingMode": None
}
Bad Repair: invalid syntax (<unknown>, line 4):
def test_convert_webpage(self):
json_data = {"LoadingDocumentUrl": "http://google.com",
** "SaveOptions":
"Password": None,
"SaveRoutingSlip": True,
"SaveFormat": "doc",
"FileName": "google.doc",
"DmlRenderingMode": None,
"DmlEffectsRenderingMode": None
}
Synthesized repair in: 3151ms
Tidyparse (valid/total): 466/842
Original error:
def undirected_arcs(bn_structure):
arcs = np.array(bnlearn.undirected_arcs(bn_structure)
ncols = 2
nrows = len(arcs) / 2
arcs = arcs.reshape(nrows, ncols, order = 'F')
return arcs
Bad Repair: invalid syntax (<unknown>, line 3):
def undirected_arcs(bn_structure):
arcs = np.array(bnlearn.undirected_arcs(bn_structure)
ncols = 2
nrows = len(arcs) / 2
** arcs = arcs.reshapenrows, ncols, order = 'F')
return arcs
Synthesized repair in: 28568ms
Tidyparse (valid/total): 466/843
Original error:
Gauss Psudocode
Have the function import two equations from equations.py
Have the user input an initial guess for one of them.
x = Do f2(user_input_guess)
Loop till % error is small:
y = f1(x)
x = f2(y)
If the error keeps getting larger, then switch the functions.
Display the intercection point to the user.
Class Psudocode
input functions
input
input initial guess
While error > desired error:
for i in range(
solve each function
calculate error
(x2 - x1) /(y2 - y1) = % error
check for divergence
Bad Repair: invalid syntax (<unknown>, line 1):
Gauss Psudocode
Have the function import two equations from equations.py
Have the user input an initial guess for one of them.
x = Do f2(user_input_guess)
Loop till % error is small:
y = f1(x)
x = f2(y)
If the error keeps getting larger, then switch the functions.
Display the intercection point to the user.
Class Psudocode
input functions
input
input initial guess
While error > desired error:
for i in range(
solve each function
calculate error
** x2 - x1) /(y2 - y1) = % error
check for divergence
Synthesized repair in: 82680ms
Tidyparse (valid/total): 466/844
Original error:
def infer_shape_numpy_add_sub(node, input_shapes):
ashp, bshp = input_shapes
return[ashp[0]
Good Repair:
def infer_shape_numpy_add_sub(node, input_shapes):
ashp, bshp = input_shapes
** return[ashp0]
Synthesized repair in: 20275ms
Tidyparse (valid/total): 467/845
Original error:
def setText(self, text):
assert(isinstance(text, unicode)
self._text = text
Good Repair:
def setText(self, text):
** assert(isinstancetext, unicode)
self._text = text
Synthesized repair in: 7393ms
Tidyparse (valid/total): 468/846
Original error:
def rastrigin_skew(individual):
"""Skewed Rastrigin test objective function."""
N = len(individual)
return 10 * N + sum((10 * x if x > 0 else x) ** 2
Good Repair:
def rastrigin_skew(individual):
"""Skewed Rastrigin test objective function."""
N = len(individual)
** return 10 * N + sum(10 * x if x > 0 else x) ** 2
Synthesized repair in: 39978ms
Tidyparse (valid/total): 469/847
Original error:
def generate_uuid():
"""Returns a random uuid as a string."""
return str(uuid.uuid4()))
Good Repair:
def generate_uuid():
"""Returns a random uuid as a string."""
** return str(uuid.uuid4())
Synthesized repair in: 8384ms
Tidyparse (valid/total): 470/848
Original error:
def nb(self):
self.write()
display(HTML(self.fname)
Good Repair:
def nb(self):
self.write()
** display(HTMLself.fname)
Synthesized repair in: 18779ms
Tidyparse (valid/total): 471/849
Original error:
def test_lancaster(self):
self.op = StemmerLancaster()
self.test_data = ['strange', 'women', 'lying', 'ponds', 'distributing', 'swords', 'no', 'basis', 'system', 'government']
self.assertEqual(self.op.run(self.test_data),
['starnge', 'wom', 'lying', 'pond', 'distribut', 'sword', 'no', 'bas', 'system', 'govern']
Good Repair:
def test_lancaster(self):
self.op = StemmerLancaster()
self.test_data = ['strange', 'women', 'lying', 'ponds', 'distributing', 'swords', 'no', 'basis', 'system', 'government']
** self.assertEqualself.op.run(self.test_data),
['starnge', 'wom', 'lying', 'pond', 'distribut', 'sword', 'no', 'bas', 'system', 'govern']
Synthesized repair in: 61868ms
Tidyparse (valid/total): 472/850
Original error:
def is_binary_file(file):
return isinstance(file, (io.BufferedReader, io.BufferedWriter,
io.BufferedRandom)
Good Repair:
def is_binary_file(file):
** return isinstance(file, io.BufferedReader, io.BufferedWriter,
io.BufferedRandom)
Synthesized repair in: 13550ms
Tidyparse (valid/total): 473/851
Original error:
def retranslateUi(self, FormFunctions):
FormFunctions.setWindowTitle(_translate("FormFunctions", "Form", None))
self.labelScipyFunc.setText(_translate("FormFunctions", "Scipy\n"
Bad Repair: invalid syntax (<unknown>, line 3):
def retranslateUi(self, FormFunctions):
FormFunctions.setWindowTitle(_translate("FormFunctions", "Form", None))
** self.labelScipyFunc.setText(_translate)"FormFunctions", "Scipy\n"
Synthesized repair in: 78759ms
Tidyparse (valid/total): 473/852
Original error:
def delete(self, name):
try:
cloudstorage.delete(self.path(name)
except cloudstorage.NotFoundError:
pass
Good Repair:
def delete(self, name):
try:
** cloudstorage.deleteself.path(name)
except cloudstorage.NotFoundError:
pass
Synthesized repair in: 4023ms
Tidyparse (valid/total): 474/853
Original error:
def reg(self, identity, password):
salt = os.urandom(64)
x = bin_str_to_big_int(sha256(salt, password)
verifier = mod_exp(self.config.g, x, self.config.N)
self.server.reg(identity, salt, verifier)
Good Repair:
def reg(self, identity, password):
salt = os.urandom(64)
** x = bin_str_to_big_int(sha256salt, password)
verifier = mod_exp(self.config.g, x, self.config.N)
self.server.reg(identity, salt, verifier)
Synthesized repair in: 40699ms
Tidyparse (valid/total): 475/854
Original error:
def test_normalize_summary(self):
self.assertEqual(
'This is a sentence.',
docformatter.normalize_summary('This \n\t is\na sentence')
Bad Repair: invalid syntax (<unknown>, line 4):
def test_normalize_summary(self):
self.assertEqual(
'This is a sentence.',
** docformatter.normalize_summary'This \n\t is\na sentence')
Synthesized repair in: 7310ms
Tidyparse (valid/total): 475/855
Original error:
def validate_schema(self, schema_test):
sql = schema_test.render()
num_rows = self.execute_query(model, sql)
if num_rows == 0:
logger.info(" OK")
yield True
else:
logger.info(" FAILED({})".format(num_rows)
yield False
Good Repair:
def validate_schema(self, schema_test):
sql = schema_test.render()
num_rows = self.execute_query(model, sql)
if num_rows == 0:
logger.info(" OK")
yield True
else:
** logger.info(" FAILED({})".formatnum_rows)
yield False
Synthesized repair in: 94753ms
Tidyparse (valid/total): 476/856
Original error:
def get_sample_installed_config(self):
return{
"id": 1,
"name": {
"en-us": "aa",
},
"current_version": "0.1.1",
"installed_path": "bb",
"shortcut_path": "dd"
Bad Repair: unexpected indent (<unknown>, line 3):
def get_sample_installed_config(self):
** return
"id": 1,
"name": {
"en-us": "aa",
},
"current_version": "0.1.1",
"installed_path": "bb",
"shortcut_path": "dd"
Synthesized repair in: 7371ms
Tidyparse (valid/total): 476/857
Original error:
def depart_citation_reference(self, node):
raise NotImplementedError, node.astext()
self.body.append(']</a>')
Bad Repair: invalid syntax (<unknown>, line 2):
def depart_citation_reference(self, node):
raise NotImplementedError, node.astext()
** self.body.append('</a>')
Synthesized repair in: 41218ms
Tidyparse (valid/total): 476/858
Original error:
def camel_case(text, sep = None):
"""Convert *text* to camel case.Use the *sep* keyword to specify the word"""
return ''.join(text.title().split(sep)
Good Repair:
def camel_case(text, sep = None):
"""Convert *text* to camel case.Use the *sep* keyword to specify the word"""
** return ''.join(text.title().splitsep)
Synthesized repair in: 18572ms
Tidyparse (valid/total): 477/859
Original error:
def show(self, context, image_id):
"""Get data about specified image."""
image = self.images.get(str(image_id)
if image:
return copy.deepcopy(image)
LOG.warn('Unable to find image id %s.Have images: %s',
image_id, self.images)
raise exception.ImageNotFound(image_id = image_id)
Good Repair:
def show(self, context, image_id):
"""Get data about specified image."""
** image = self.images.get(strimage_id)
if image:
return copy.deepcopy(image)
LOG.warn('Unable to find image id %s.Have images: %s',
image_id, self.images)
raise exception.ImageNotFound(image_id = image_id)
Synthesized repair in: 57157ms
Tidyparse (valid/total): 478/860
Original error:
def on_start(self):
self.crawl('http://www.xhplan.com/ghgs.asp?Page=1',
callback = self.index_page, age = 1, save = {'type': self.table_name[8]}})
Good Repair:
def on_start(self):
self.crawl('http://www.xhplan.com/ghgs.asp?Page=1',
** callback = self.index_page, age = 1, save = {'type': self.table_name[8]})
Synthesized repair in: 62744ms
Tidyparse (valid/total): 479/861
Original error:
class AuthorAdmin(DisplayableAdmin):
form = AuthorForm
fieldsets = (None, {
"fields": [
"title", "image", "gen_description",
"description", "email", "twitter_username",
"facebook_username", "website"
Bad Repair: invalid syntax (<unknown>, line 4):
class AuthorAdmin(DisplayableAdmin):
form = AuthorForm
** fieldsets = None, {
** "fields": }
"title", "image", "gen_description",
"description", "email", "twitter_username",
"facebook_username", "website"
Synthesized repair in: 48432ms
Tidyparse (valid/total): 479/862
Original error:
def logout():
""" Utility function used to force browsers to reset cached HTTP Basic Auth"""
return make_response((
"<meta http-equiv='refresh' content='0; url=/''>.",
401,
{'WWW-Authenticate': 'Basic realm="API Access Token Required"'})))
Good Repair:
def logout():
""" Utility function used to force browsers to reset cached HTTP Basic Auth"""
return make_response((
"<meta http-equiv='refresh' content='0; url=/''>.",
401,
** {'WWW-Authenticate': 'Basic realm="API Access Token Required"'}))
Synthesized repair in: 10594ms
Tidyparse (valid/total): 480/863
Original error:
def format_h5_backtrace(self, backtrace = None):
"""Convert the HDF5 trace back represented as a list of tuples."""
if backtrace is None:
backtrace = self.h5backtrace
if backtrace is None:
return 'No HDF5 back trace available'
else:
return ''.join(traceback.format_list(backtrace)
Good Repair:
def format_h5_backtrace(self, backtrace = None):
"""Convert the HDF5 trace back represented as a list of tuples."""
if backtrace is None:
backtrace = self.h5backtrace
if backtrace is None:
return 'No HDF5 back trace available'
else:
** return ''.join(traceback.format_listbacktrace)
Synthesized repair in: 3272ms
Tidyparse (valid/total): 481/864
Original error:
def getTimeDelay(self):
try:
return int(os.getenv("TEXTTEST_FILEWAIT_SLEEP", 1)
except ValueError:
return 1
Bad Repair: invalid syntax (<unknown>, line 3):
def getTimeDelay(self):
try:
** return int(os.getenv"TEXTTEST_FILEWAIT_SLEEP", 1)
except ValueError:
return 1
Synthesized repair in: 3257ms
Tidyparse (valid/total): 481/865
Original error:
def get(self):
""" 查询节点 """
return g.node.GET(node = request.args.get("node", None)
Bad Repair: invalid syntax (<unknown>, line 3):
def get(self):
""" 查询节点 """
** return g.node.GETnode = request.args.get("node", None)
Synthesized repair in: 4120ms
Tidyparse (valid/total): 481/866
Original error:
def printmsg(msg, level = 0):
prefix = "| " * level
prefix2 = prefix + "|"
print(prefix + "+ Message Headers: ")
for header, value in list(msg.items():
print(prefix2, header + ": ", value)
if msg.is_multipart():
for item in msg.get_payload():
printmsg(item, level + 1)
Bad Repair: invalid syntax (<unknown>, line 5):
def printmsg(msg, level = 0):
prefix = "| " * level
prefix2 = prefix + "|"
print(prefix + "+ Message Headers: ")
for header, value in list(msg.items():
print(prefix2, header + ": ", value)
if msg.is_multipart():
for item in msg.get_payload():
** printmsgitem, level + 1)
Synthesized repair in: 163358ms
Tidyparse (valid/total): 481/867
Original error:
def authenticate(self, password):
"""Authenticates against a password-protected MCP2210."""
self.sendCommand(commands.SendPasswordCommand(password)
Good Repair:
def authenticate(self, password):
"""Authenticates against a password-protected MCP2210."""
** self.sendCommandcommands.SendPasswordCommand(password)
Synthesized repair in: 8938ms
Tidyparse (valid/total): 482/868
Original error:
def testReadOnlyDefaultsToOff(self):
p = Gaffer.Plug()
self.failIf(p.getFlags(Gaffer.Plug.Flags.ReadOnly)
Good Repair:
def testReadOnlyDefaultsToOff(self):
p = Gaffer.Plug()
** self.failIf(p.getFlagsGaffer.Plug.Flags.ReadOnly)
Synthesized repair in: 22665ms
Tidyparse (valid/total): 483/869
Original error:
def parse(binary):
"""Turns a PICKLE structure into a frozen sample."""
return dict(frozen = pickle.loads(binary)
Good Repair:
def parse(binary):
"""Turns a PICKLE structure into a frozen sample."""
** return dict(frozen = pickle.loadsbinary)
Synthesized repair in: 6926ms
Tidyparse (valid/total): 484/870
Original error:
def gen_call(member_function_args, free_function_args = None):
if free_function_args is None:
free_function_args = member_function_args + 1
return(header %(member_function_args, free_function_args)
Good Repair:
def gen_call(member_function_args, free_function_args = None):
if free_function_args is None:
free_function_args = member_function_args + 1
** returnheader %(member_function_args, free_function_args)
Synthesized repair in: 7183ms
Tidyparse (valid/total): 485/871
Original error:
from django.conf.urls import patterns, include
from.import admin
urlpatterns = patterns('',
(r'^generic_inline_admin/admin/', include(admin.site.urls),
)
Good Repair:
from django.conf.urls import patterns, include
from.import admin
urlpatterns = patterns('',
** r'^generic_inline_admin/admin/', include(admin.site.urls),
)
Synthesized repair in: 2931ms
Tidyparse (valid/total): 486/872
Original error:
def send(self, name = None):
try:
if name is None:
name = self.EOF
name += os.linesep
bytes = self.socket.send(name)
print("sent: %s(%d bytes of %d)" %(name, bytes, len(name))
return True
except socket.error:
pass
return False
Good Repair:
def send(self, name = None):
try:
if name is None:
name = self.EOF
name += os.linesep
bytes = self.socket.send(name)
** print("sent: %s(%d bytes of %d)" %name, bytes, len(name))
return True
except socket.error:
pass
return False
Synthesized repair in: 111081ms
Tidyparse (valid/total): 487/873
Original error:
def subtree(mrca, treestore, graph, prune = False):
cursor = treestore.get_cursor()
query = '''sparql''' %(graph, ('''?n obo:CDAO_0000179 <%s>''' % mrca) if mrca
Bad Repair: invalid syntax (<unknown>, line 3):
def subtree(mrca, treestore, graph, prune = False):
cursor = treestore.get_cursor()
** query = '''sparql''' %(graph, '''?n obo:CDAO_0000179 <%s>''' % mrca) if mrca
Synthesized repair in: 23518ms
Tidyparse (valid/total): 487/874
Original error:
def start_service(self, name, host = None, ** kwargs):
svc = self.useFixture(ServiceFixture(name, host, ** kwargs)
return svc.service
Good Repair:
def start_service(self, name, host = None, ** kwargs):
** svc = self.useFixture(ServiceFixturename, host, ** kwargs)
return svc.service
Synthesized repair in: 12252ms
Tidyparse (valid/total): 488/875
Original error:
def clientConnectionLost(self, connector, reason):
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
log.clients("%s: :clientConnectionLost(%s: %d)%s" %(self, connector.host, connector.port, reason.getErrorMessage())
self.connectedProtocol = None
self.connectionLost.callback(0)
self.connectionLost = Deferred()
Good Repair:
def clientConnectionLost(self, connector, reason):
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
** log.clients("%s: :clientConnectionLost(%s: %d)%s" %(self, connector.host, connector.port, reason.getErrorMessage))
self.connectedProtocol = None
self.connectionLost.callback(0)
self.connectionLost = Deferred()
Synthesized repair in: 38246ms
Tidyparse (valid/total): 489/876
Original error:
def tag_delete(self, tag):
""" Delete a tag"""
res = self.delete('/tags/%s' %(tag, )
if res.ok:
return True
return False
Good Repair:
def tag_delete(self, tag):
""" Delete a tag"""
** res = self.delete('/tags/%s' %tag, )
if res.ok:
return True
return False
Synthesized repair in: 4117ms
Tidyparse (valid/total): 490/877
Original error:
def usage():
print(""" Bulb is Tor relay monitor that provides a status dashboard site on localhost.""" %{
"progname": sys.argv[0],
"control_port": DEFAULT_CONTROL_PORT,
"port": DEFAULT_PORT
}
Bad Repair: invalid syntax (<unknown>, line 2):
def usage():
** print""" Bulb is Tor relay monitor that provides a status dashboard site on localhost.""" %{
"progname": sys.argv[0],
"control_port": DEFAULT_CONTROL_PORT,
"port": DEFAULT_PORT
}
Synthesized repair in: 5529ms
Tidyparse (valid/total): 490/878
Original error:
def detach(program, * args):
"""Caution: In contrast to most other code of mediatum, """
return subprocess.Popen([program] + list(args)
Good Repair:
def detach(program, * args):
"""Caution: In contrast to most other code of mediatum, """
** return subprocess.Popen([program] + listargs)
Synthesized repair in: 15438ms
Tidyparse (valid/total): 491/879
Original error:
def PrintJsonResults(results):
"""Print results in json format."""
print(json.dumps(results)
Good Repair:
def PrintJsonResults(results):
"""Print results in json format."""
** print(json.dumpsresults)
Synthesized repair in: 21107ms
Tidyparse (valid/total): 492/880
Original error:
"""DataReader from yahoo.jp finance"""
import datetime
import time
import numpy
import jsm
import pandas.compat as compat
import pandas
def DataReader(name, data_source = None, start = None, end = None,
retry_count = 3, pause = 0.001):
"""[This method is compatible with"""
if data_source == "yahoojp":
return get_data_yahoojp(symbols = name, start = start, end = end,
adjust_price = False, chunksize = 25,
retry_count = retry_count, pause = pause)
Bad Repair: expected an indented block (<unknown>, line 12):
"""DataReader from yahoo.jp finance"""
import datetime
import time
import numpy
import jsm
import pandas.compat as compat
import pandas
def DataReader(name, data_source = None, start = None, end = None,
retry_count = 3, pause = 0.001):
** """This method is compatible with"""
if data_source == "yahoojp":
return get_data_yahoojp(symbols = name, start = start, end = end,
adjust_price = False, chunksize = 25,
retry_count = retry_count, pause = pause)
Synthesized repair in: 13205ms
Tidyparse (valid/total): 492/881
Original error:
def getServers(self):
servers = copy.copy(self.get('servers')
def_server = self.get('default_server')
if def_server is not None:
servers[def_server]['default'] = True
return servers
Bad Repair: invalid syntax (<unknown>, line 2):
def getServers(self):
** servers = copy.copy(self.get'servers')
def_server = self.get('default_server')
if def_server is not None:
servers[def_server]['default'] = True
return servers
Synthesized repair in: 49150ms
Tidyparse (valid/total): 492/882
Original error:
from __future__ import print_function
import pika
import sys
import json
import time
import os
from fontprojects import git_repos
local_devel = (os.environ.get("FONTBAKERY_LOCAL_DEVEL" == 1)
local_families_selection = [
"Roboto",
"Roboto Condensed",
"Ubuntu",
"Merriweather",
"Lobster",
"Exo",
"Overpass Mono",
"Sarala"]
Bad Repair: invalid syntax (<unknown>, line 8):
from __future__ import print_function
import pika
import sys
import json
import time
import os
from fontprojects import git_repos
** local_devel = (os.environ.get"FONTBAKERY_LOCAL_DEVEL" == 1)
local_families_selection = [
"Roboto",
"Roboto Condensed",
"Ubuntu",
"Merriweather",
"Lobster",
"Exo",
"Overpass Mono",
"Sarala"]
Synthesized repair in: 7958ms
Tidyparse (valid/total): 492/883
Original error:
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.'''
return timegm(rfc822.parsedate(self.created_at)
Good Repair:
def GetCreatedAtInSeconds(self):
'''Get the time this status message was posted, in seconds since the epoch.'''
** return timegm(rfc822.parsedateself.created_at)
Synthesized repair in: 10739ms
Tidyparse (valid/total): 493/884
Original error:
def wrapmodule(module):
"""wrapmodule(module)"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
raise GeneralProxyError((4, "no proxy specified")
Good Repair:
def wrapmodule(module):
"""wrapmodule(module)"""
if _defaultproxy != None:
module.socket.socket = socksocket
else:
** raise GeneralProxyError(4, "no proxy specified")
Synthesized repair in: 36716ms
Tidyparse (valid/total): 494/885
Original error:
def is_valid(number):
"""Check if the number provided is a valid RNC."""
try:
return bool(validate(number)
except ValidationError:
return False
Good Repair:
def is_valid(number):
"""Check if the number provided is a valid RNC."""
try:
** return bool(validatenumber)
except ValidationError:
return False
Synthesized repair in: 3553ms
Tidyparse (valid/total): 495/886
Original error:
def gettext(self, msgid):
"""Obtain translation of gettext, return a unicode object"""
if len(msgid.strip() == 0:
return msgid
return gettext.GNUTranslations.gettext(self, msgid)
Bad Repair: invalid syntax (<unknown>, line 3):
def gettext(self, msgid):
"""Obtain translation of gettext, return a unicode object"""
if len(msgid.strip() == 0:
return msgid
** return gettext.GNUTranslations.gettextself, msgid)
Synthesized repair in: 5220ms
Tidyparse (valid/total): 495/887
Original error:
def full_path(self):
""" Same as `.path()`, but with the provider storage root prepended."""
return '/'.join([x.value for x in self._prepend_parts + self.parts[1: ]]]) +('/' if self.is_dir else '')
Good Repair:
def full_path(self):
""" Same as `.path()`, but with the provider storage root prepended."""
** return '/'.join([x.value for x in self._prepend_parts + self.parts[1: ]]) +('/' if self.is_dir else '')
Synthesized repair in: 22152ms
Tidyparse (valid/total): 496/888
Original error:
def replace_static_urls(data_dir, block, view, frag, context, course_id = None, static_asset_path = ''):
"""Updates the supplied module with a new get_html function that wraps"""
return wrap_fragment(frag, static_replace.replace_static_urls(
frag.content,
data_dir,
course_id,
static_asset_path = static_asset_path
)
Bad Repair: invalid syntax (<unknown>, line 4):
def replace_static_urls(data_dir, block, view, frag, context, course_id = None, static_asset_path = ''):
"""Updates the supplied module with a new get_html function that wraps"""
** return wrap_fragment(frag, static_replace.replace_static_urls
frag.content,
data_dir,
course_id,
static_asset_path = static_asset_path
)
Synthesized repair in: 6651ms
Tidyparse (valid/total): 496/889
Original error:
def factor(self):
"""Ratio between adjacent steps"""
if self.decade:
n = (np.log10(self.stop) - np.log10(self.start))) * self.decade + 1
else:
n = self.n
return(self.stop / self.start) **(1. /(n - 1))
Good Repair:
def factor(self):
"""Ratio between adjacent steps"""
if self.decade:
** n = (np.log10(self.stop - np.log10(self.start))) * self.decade + 1
else:
n = self.n
return(self.stop / self.start) **(1. /(n - 1))
Synthesized repair in: 64278ms
Tidyparse (valid/total): 497/890
Original error:
def find_similars(face_id, face_list_id):
url = 'findsimilars'
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': KEY,
}
json = {
"faceId": face_id,
"faceListId": face_list_id,
"maxNumOfCandidatesReturned": 100,
"mode": "matchPerson"
Bad Repair: invalid syntax (<unknown>, line 7):
def find_similars(face_id, face_list_id):
url = 'findsimilars'
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': KEY,
}
** json =
"faceId": face_id,
"faceListId": face_list_id,
"maxNumOfCandidatesReturned": 100,
"mode": "matchPerson"
Synthesized repair in: 10142ms
Tidyparse (valid/total): 497/891
Original error:
def get_item_outbound_links(self, item):
links = self.create_link_collection()
links.append(self.get_item_storage_link(item, link_factor = 'LO')
return links
Good Repair:
def get_item_outbound_links(self, item):
links = self.create_link_collection()
** links.append(self.get_item_storage_linkitem, link_factor = 'LO')
return links
Synthesized repair in: 15982ms
Tidyparse (valid/total): 498/892
Original error:
import netsnmp
vars = netsnmp.Varbind(netsnmp.VarList(netsnmp.Varbind(".1.2.6.1.4.1.9.2.10.6.0", "1"),
(netsnmp.Varbind("cisco.example.com.1.3.6.1.4.1.9.2.10.12.172.25.1.1",
"iso-config.bin")
result = netsnmp.snmpset(vars,
Version = 1,
DestHost = 'cisco.example.com',
Community = 'readWrite')
Bad Repair: invalid syntax (<unknown>, line 2):
import netsnmp
** vars = netsnmp.Varbind(netsnmp.VarList(netsnmp.Varbind".1.2.6.1.4.1.9.2.10.6.0", "1"),
(netsnmp.Varbind("cisco.example.com.1.3.6.1.4.1.9.2.10.12.172.25.1.1",
"iso-config.bin")
** result = netsnmp.snmpset)vars,
Version = 1,
DestHost = 'cisco.example.com',
Community = 'readWrite')
Synthesized repair in: 244254ms
Tidyparse (valid/total): 498/893
Original error:
def get_endpoint_location_data_old():
return[{
"input": {
"node-connector-id": "openflow:1:1",
"node-id": "openflow:1",
"faas-port-ref-id": "165b3a20-adc7-11e5-bf7f-feff819cdc9f"
}
Bad Repair: illegal target for annotation (<unknown>, line 3):
def get_endpoint_location_data_old():
** return[]
"input": {
"node-connector-id": "openflow:1:1",
"node-id": "openflow:1",
"faas-port-ref-id": "165b3a20-adc7-11e5-bf7f-feff819cdc9f"
}
Synthesized repair in: 4292ms
Tidyparse (valid/total): 498/894
Original error:
def _reproducir_animacion(self):
self.cuadro += 0.2
if self.cuadro > 1:
self.cuadro = 0
self.definir_cuadro(int(self.posicion * 2 + self.cuadro)
Good Repair:
def _reproducir_animacion(self):
self.cuadro += 0.2
if self.cuadro > 1:
self.cuadro = 0
** self.definir_cuadroint(self.posicion * 2 + self.cuadro)
Synthesized repair in: 3491ms
Tidyparse (valid/total): 499/895
Original error:
def main(request):
""" выводим список всех отчетов """
return render_to_response('analytic/main.html',
context_instance = RequestContext(request)
Bad Repair: invalid syntax (<unknown>, line 3):
def main(request):
""" выводим список всех отчетов """
** return render_to_response'analytic/main.html',
context_instance = RequestContext(request)
Synthesized repair in: 4859ms
Tidyparse (valid/total): 499/896
Original error:
def GetGTestFilter(tests, blacklist):
"""Returns the GTest filter to run or exclude only the given tests."""
if blacklist:
blacklist = '-'
else:
blacklist = ''
return '%s%s' %(blacklist, ': '.join(test for test in tests)
Good Repair:
def GetGTestFilter(tests, blacklist):
"""Returns the GTest filter to run or exclude only the given tests."""
if blacklist:
blacklist = '-'
else:
blacklist = ''
** return '%s%s' %blacklist, ': '.join(test for test in tests)
Synthesized repair in: 3593ms
Tidyparse (valid/total): 500/897
Original error:
def get_charge(self, atom_index_list = None):
if atom_index_list:
for i in atom_index_list:
print("Charge at atom index ", i, " is ", self.data[i][
"charge"]
Bad Repair: invalid syntax (<unknown>, line 4):
def get_charge(self, atom_index_list = None):
if atom_index_list:
for i in atom_index_list:
** print"Charge at atom index ", i, " is ", self.data[i][
"charge"]
Synthesized repair in: 23009ms
Tidyparse (valid/total): 500/898
Original error:
def devpts(self):
if not self._devpts:
self._devpts = NoDevice(fmt = getFormat("devpts", device = "devpts", mountpoint = "/dev/pts")
return self._devpts
Bad Repair: invalid syntax (<unknown>, line 3):
def devpts(self):
if not self._devpts:
** self._devpts = NoDevice(fmt = getFormat"devpts", device = "devpts", mountpoint = "/dev/pts")
return self._devpts
Synthesized repair in: 8793ms
Tidyparse (valid/total): 500/899
Original error:
def change_ocfs2_device(rsc):
print("The current device for ocfs2 depends on evms: %s" % get_param(rsc, "device")
dev = get_input("Please supply the device where %s ocfs2 resource resides: " % rsc.getAttribute("id"))
set_param(rsc, "device", dev)
Bad Repair: invalid syntax (<unknown>, line 2):
def change_ocfs2_device(rsc):
** print"The current device for ocfs2 depends on evms: %s" % get_param(rsc, "device")
dev = get_input("Please supply the device where %s ocfs2 resource resides: " % rsc.getAttribute("id"))
set_param(rsc, "device", dev)
Synthesized repair in: 44993ms
Tidyparse (valid/total): 500/900
Original error:
import os
import subprocess
from collections import namedtuple
__all__ = [
'abspath',
'update_repo',
'Update',
]
def abspath(* p): return os.path.abspath(os.path.join(* p)
Update = namedtuple('Update', 'popen cloned')
Bad Repair: invalid syntax (<unknown>, line 10):
import os
import subprocess
from collections import namedtuple
__all__ = [
'abspath',
'update_repo',
'Update',
]
def abspath(* p): return os.path.abspath(os.path.join(* p)
** Update = namedtuple'Update', 'popen cloned')
Synthesized repair in: 32745ms
Tidyparse (valid/total): 500/901
Original error:
class check_dig(CommandParser):
def processResults(self, cmd, result):
for dp in cmd.points:
result.values.append((dp, 12345)
Bad Repair: expected an indented block (<unknown>, line 3):
class check_dig(CommandParser):
def processResults(self, cmd, result):
for dp in cmd.points:
** result.values.append(dp, 12345)
Synthesized repair in: 13582ms
Tidyparse (valid/total): 500/902
Original error:
def VerifyEditablePaths(cls, paths):
"""Returns true if source already opened for editing."""
for doc in appdata.documents:
for p in doc.paths:
if p in paths:
Notify(cls.msg_cantedit.format(p)
return False
return True
Good Repair:
def VerifyEditablePaths(cls, paths):
"""Returns true if source already opened for editing."""
for doc in appdata.documents:
for p in doc.paths:
if p in paths:
** Notify(cls.msg_cantedit.formatp)
return False
return True
Synthesized repair in: 19943ms
Tidyparse (valid/total): 501/903
Original error:
def topic_overview(self, feature_names, topic):
return[feature_names[i]
for i in topic.argsort()[: - self.n_top_words - 1: - 1]]]
Good Repair:
def topic_overview(self, feature_names, topic):
return[feature_names[i]
** for i in topic.argsort()[: - self.n_top_words - 1: - 1]]
Synthesized repair in: 9311ms
Tidyparse (valid/total): 502/904
Original error:
class ToonClass(Base):
__tablename__ = 'classes'
id = Column(Integer, primary_key = True)
name = Column(String)
attributeeffects = relation(AttributeEffects, backref('classes'), order_by = id))
Bad Repair: invalid syntax (<unknown>, line 4):
class ToonClass(Base):
__tablename__ = 'classes'
** id = Column(Integer, primary_key = True
name = Column(String)
attributeeffects = relation(AttributeEffects, backref('classes'), order_by = id))
Synthesized repair in: 15164ms
Tidyparse (valid/total): 502/905
Original error:
def _notebook_dir_default(self):
if self.file_to_run:
return os.path.dirname(os.path.abspath(self.file_to_run)
else:
return py3compat.getcwd()
Good Repair:
def _notebook_dir_default(self):
if self.file_to_run:
** return os.path.dirnameos.path.abspath(self.file_to_run)
else:
return py3compat.getcwd()
Synthesized repair in: 22798ms
Tidyparse (valid/total): 503/906
Original error:
def loss(self):
model = self.inference
loss = digits.classification_loss(model, self.y)
accuracy = digits.classification_accuracy(model, self.y)
self.summaries.append(tf.summary.scalar(accuracy.op.name, accuracy)
return loss
Good Repair:
def loss(self):
model = self.inference
loss = digits.classification_loss(model, self.y)
accuracy = digits.classification_accuracy(model, self.y)
** self.summaries.appendtf.summary.scalar(accuracy.op.name, accuracy)
return loss
Synthesized repair in: 16183ms
Tidyparse (valid/total): 504/907
Original error:
def test_location_print_pytz():
tus = Location(32.2, - 111, aztz, 700, 'Tucson')
expected_str = '\n'.join([
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Bad Repair: unexpected indent (<unknown>, line 4):
def test_location_print_pytz():
tus = Location(32.2, - 111, aztz, 700, 'Tucson')
** expected_str = '\n'.join()
'Location: ',
' name: Tucson',
' latitude: 32.2',
' longitude: -111',
' altitude: 700',
' tz: US/Arizona'
Synthesized repair in: 24602ms
Tidyparse (valid/total): 504/908
Original error:
"""rlundo"""
from __future__ import unicode_literals
import sys
import os
import argparse
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
import rlundo
from rlundo.rlundoable import modify_env_with_modified_rl
from rlundo.termrewrite import run_with_listeners
from rlundo import interps
Good Repair:
"""rlundo"""
from __future__ import unicode_literals
import sys
import os
import argparse
** sys.path.insert(0, os.path.abspath(os.path.joinos.path.dirname(__file__), '..'))
import rlundo
from rlundo.rlundoable import modify_env_with_modified_rl
from rlundo.termrewrite import run_with_listeners
from rlundo import interps
Synthesized repair in: 9562ms
Tidyparse (valid/total): 505/909
Original error:
import os, sys
if __name__ == '__main__':
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))
sys.path.append(SRC_ROOT)
import time
import re
import json
from settings.base import get_github_auth, REDMINE_ISSUES_DIRECTORY, USER_MAP_FILE, LABEL_MAP_FILE, MILESTONE_MAP_FILE, REDMINE_TO_GITHUB_MAP_FILE
from github_issues.user_map_helper import UserMapHelper
from github_issues.github_issue_maker import GithubIssueMaker
Bad Repair: invalid syntax (<unknown>, line 4):
import os, sys
if __name__ == '__main__':
SRC_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))
** sys.path.appendSRC_ROOT)
import time
import re
import json
from settings.base import get_github_auth, REDMINE_ISSUES_DIRECTORY, USER_MAP_FILE, LABEL_MAP_FILE, MILESTONE_MAP_FILE, REDMINE_TO_GITHUB_MAP_FILE
from github_issues.user_map_helper import UserMapHelper
from github_issues.github_issue_maker import GithubIssueMaker
Synthesized repair in: 3860ms
Tidyparse (valid/total): 505/910
Original error:
def make_sortkey(sortkeys):
def safe_int(x):
try:
return int(x)
except ValueError:
return x
key = lambda x: [k for sk in sortkeys
for k in map(safe_int,
re.split(r'(\d+)', xp.find(x, sk) or '')]
return key
Good Repair:
def make_sortkey(sortkeys):
def safe_int(x):
try:
return int(x)
except ValueError:
return x
key = lambda x: [k for sk in sortkeys
for k in map(safe_int,
** re.split(r'(\d+)', xp.findx, sk) or '')]
return key
Synthesized repair in: 413353ms
Tidyparse (valid/total): 506/911
Original error:
def begin(self, arg):
if isinstance(arg, basestring):
arg = getattr(self.module, 'GL_%s' % arg.upper()
self.module.glBegin(arg)
return self._apply_on_exit(self.module.glEnd)
Good Repair:
def begin(self, arg):
if isinstance(arg, basestring):
** arg = getattr(self.module, 'GL_%s' % arg.upper)
self.module.glBegin(arg)
return self._apply_on_exit(self.module.glEnd)
Synthesized repair in: 35592ms
Tidyparse (valid/total): 507/912
Original error:
def _log_etree_elem(elem, level = logging.DEBUG):
'''Helper function - Log serialisation of an ElementTree Element'''
if log.getEffectiveLevel() <= level:
log.debug(ET.tostring(elem)
Good Repair:
def _log_etree_elem(elem, level = logging.DEBUG):
'''Helper function - Log serialisation of an ElementTree Element'''
if log.getEffectiveLevel() <= level:
** log.debug(ET.tostringelem)
Synthesized repair in: 15455ms
Tidyparse (valid/total): 508/913
Original error:
def sysfs_nf_conntrack_hashsize(self):
""""""
return{
"/sys/module/nf_conntrack/parameters/hashsize": self.vars["nfConntrackMax"] / 4
Bad Repair: unexpected indent (<unknown>, line 4):
def sysfs_nf_conntrack_hashsize(self):
""""""
** return
"/sys/module/nf_conntrack/parameters/hashsize": self.vars["nfConntrackMax"] / 4
Synthesized repair in: 19905ms
Tidyparse (valid/total): 508/914
Original error:
def go_option_enabled(option):
"""Checks if a boolean script option is enabled or not."""
return weechat.config_string_to_boolean(weechat.config_get_plugin(option)
Good Repair:
def go_option_enabled(option):
"""Checks if a boolean script option is enabled or not."""
** return weechat.config_string_to_booleanweechat.config_get_plugin(option)
Synthesized repair in: 2718ms
Tidyparse (valid/total): 509/915
Original error:
def visit_insert_from_select(element, compiler, ** kw):
"""Form the `INSERT INTO table(SELECT...)` statement."""
return "INSERT INTO %s %s" %(
compiler.process(element.table, asfrom = True),
compiler.process(element.select)
Good Repair:
def visit_insert_from_select(element, compiler, ** kw):
"""Form the `INSERT INTO table(SELECT...)` statement."""
return "INSERT INTO %s %s" %(
compiler.process(element.table, asfrom = True),
** compiler.processelement.select)
Synthesized repair in: 36934ms
Tidyparse (valid/total): 510/916
Original error:
def testGlob1(self):
pt = list(Pipeline.tokenize('echo f*', self._context)
self.assertEquals(len(pt), 2)
Bad Repair: invalid syntax (<unknown>, line 2):
def testGlob1(self):
** pt = list(Pipeline.tokenize'echo f*', self._context)
self.assertEquals(len(pt), 2)
Synthesized repair in: 9430ms
Tidyparse (valid/total): 510/917
Original error:
def list(section_path = ''):
'''List the contents of a directory section.'''
if is_valid_section(section_path):
section = WikiSection(section_path)
g.sections = section.sections
return render_template('list.html', section_path = section_path,
sections = section.subsections,
pages = section.pages)
else:
flash('Sorry.That wiki section doesn\'t exist.')
return redirect(url_for('index')
Good Repair:
def list(section_path = ''):
'''List the contents of a directory section.'''
if is_valid_section(section_path):
section = WikiSection(section_path)
g.sections = section.sections
return render_template('list.html', section_path = section_path,
sections = section.subsections,
pages = section.pages)
else:
flash('Sorry.That wiki section doesn\'t exist.')
** return redirecturl_for('index')
Synthesized repair in: 286340ms
Tidyparse (valid/total): 511/918
Original error:
def _IsDuplicate(self, node_to_copy, node):
"""Is element a duplicate?"""
for merger_node in self._merger_dom.getElementsByTagName(node_to_copy):
if(merger_node.getAttribute(self._ANDROID_NAME) ==
node.getAttribute(self._ANDROID_NAME):
return True
return False
Bad Repair: invalid syntax (<unknown>, line 4):
def _IsDuplicate(self, node_to_copy, node):
"""Is element a duplicate?"""
for merger_node in self._merger_dom.getElementsByTagName(node_to_copy):
** ifmerger_node.getAttribute(self._ANDROID_NAME) ==
node.getAttribute(self._ANDROID_NAME):
return True
return False
Synthesized repair in: 10555ms
Tidyparse (valid/total): 511/919
Original error:
def write_missing_macros(path):
""" These macros are missing in std.ddoc. """
path.open("w").write("""WIKI ="""
Bad Repair: invalid syntax (<unknown>, line 3):
def write_missing_macros(path):
""" These macros are missing in std.ddoc. """
** path.open("w").write"""WIKI ="""
Synthesized repair in: 26440ms
Tidyparse (valid/total): 511/920
Original error:
def flip_images(images):
new = []
for i in images:
new.append(pygame.transform.flip(i, 1, 0)
return new
Good Repair:
def flip_images(images):
new = []
for i in images:
** new.append(pygame.transform.flipi, 1, 0)
return new
Synthesized repair in: 30168ms
Tidyparse (valid/total): 512/921
Original error:
def retranslateUi(self, SvnPropListDialog):
_translate = QtCore.QCoreApplication.translate
SvnPropListDialog.setWindowTitle(_translate("SvnPropListDialog", "Subversion List Properties"))
SvnPropListDialog.setWhatsThis(_translate("SvnPropListDialog", "<b>Subversion List Prperties</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, SvnPropListDialog):
_translate = QtCore.QCoreApplication.translate
SvnPropListDialog.setWindowTitle(_translate("SvnPropListDialog", "Subversion List Properties"))
** SvnPropListDialog.setWhatsThis(_translate)"SvnPropListDialog", "<b>Subversion List Prperties</b>\n"
Synthesized repair in: 248542ms
Tidyparse (valid/total): 512/922
Original error:
sort_list = [- 1, - 2, - 3, - 9]
max_num = 0
second_num = 0
for num in sort_list:
if num > max_num:
second_mun = max_num
max_num = num
elif num > second_num and num < max_num:
second_num = num
max_num_index = 0
i = 0
for num in range(len(sort_list):
if num > max_num:
max_num = num
Good Repair:
sort_list = [- 1, - 2, - 3, - 9]
max_num = 0
second_num = 0
for num in sort_list:
if num > max_num:
second_mun = max_num
max_num = num
elif num > second_num and num < max_num:
second_num = num
max_num_index = 0
i = 0
** for num in range(lensort_list):
if num > max_num:
max_num = num
Synthesized repair in: 3593ms
Tidyparse (valid/total): 513/923
Original error:
def next(self):
if self._next_batch_no >= self._num_batches:
raise StopIteration()
else:
self._last = self._rng.random_integers(low = 0,
high = self._dataset_size - 1,
size = (self._batch_size, )
self._next_batch_no += 1
return self._last
Bad Repair: unexpected indent (<unknown>, line 6):
def next(self):
if self._next_batch_no >= self._num_batches:
raise StopIteration()
else:
** self._last = self._rng.random_integerslow = 0,
high = self._dataset_size - 1,
size = (self._batch_size, )
self._next_batch_no += 1
return self._last
Synthesized repair in: 6795ms
Tidyparse (valid/total): 513/924
Original error:
import glob
import os
import shlex
import sys
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib')
import gyp
output_dir = os.path.join(os.path.abspath(root_dir), 'out')
Bad Repair: invalid syntax (<unknown>, line 7):
import glob
import os
import shlex
import sys
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(root_dir, 'tools', 'gyp', 'pylib')
import gyp
** output_dir = os.path.joinos.path.abspath(root_dir), 'out')
Synthesized repair in: 45146ms
Tidyparse (valid/total): 513/925
Original error:
def get_canonical(self, ** kwargs):
return HTTPLocation.from_keywords(
session = self._session,
base = self.base,
path_prefix = self.to_path(** kwargs)
Bad Repair: unexpected indent (<unknown>, line 3):
def get_canonical(self, ** kwargs):
** return HTTPLocation.from_keywords
session = self._session,
base = self.base,
path_prefix = self.to_path(** kwargs)
Synthesized repair in: 7104ms
Tidyparse (valid/total): 513/926
Original error:
def __exit__(self, * args):
if self.summary:
print('%s: %f ms' %(self.context, self.elapsed)
Good Repair:
def __exit__(self, * args):
if self.summary:
** print('%s: %f ms' %self.context, self.elapsed)
Synthesized repair in: 7994ms
Tidyparse (valid/total): 514/927
Original error:
def delete_flavor(self, flavor_id):
"""Deletes the given flavor."""
return self.delete("flavors/%s" % str(flavor_id)
Bad Repair: invalid syntax (<unknown>, line 3):
def delete_flavor(self, flavor_id):
"""Deletes the given flavor."""
** return self.delete"flavors/%s" % str(flavor_id)
Synthesized repair in: 3743ms
Tidyparse (valid/total): 514/928
Original error:
def get_view_name(self):
"""Return the view name, as used in OPTIONS responses and in the"""
func = self.settings.VIEW_NAME_FUNCTION
return func(self.__class__, getattr(self, 'suffix', None)
Good Repair:
def get_view_name(self):
"""Return the view name, as used in OPTIONS responses and in the"""
func = self.settings.VIEW_NAME_FUNCTION
** return funcself.__class__, getattr(self, 'suffix', None)
Synthesized repair in: 6897ms
Tidyparse (valid/total): 515/929
Original error:
def ExpandConstants(lines, constants):
for key, value in constants.items():
lines = lines.replace(key, str(value)
return lines
Good Repair:
def ExpandConstants(lines, constants):
for key, value in constants.items():
** lines = lines.replacekey, str(value)
return lines
Synthesized repair in: 36667ms
Tidyparse (valid/total): 516/930
Original error:
from faker import Faker
locales = ['bg_BG', 'cs_CZ', 'de_DE', 'dk_DK', 'el_GR', 'en_CA', 'en_GB', 'en_US', 'es_ES', 'es_MX', 'fa_IR', 'fi_FI', 'fr_FR', 'hi_IN', 'it_IT', 'ko_KR', 'lt_LT', 'lv_LV',
for i in locales:
fake = Faker(i)
print(i, fake.name(), fake.city())
Good Repair:
from faker import Faker
** locales = 'bg_BG', 'cs_CZ', 'de_DE', 'dk_DK', 'el_GR', 'en_CA', 'en_GB', 'en_US', 'es_ES', 'es_MX', 'fa_IR', 'fi_FI', 'fr_FR', 'hi_IN', 'it_IT', 'ko_KR', 'lt_LT', 'lv_LV',
for i in locales:
fake = Faker(i)
print(i, fake.name(), fake.city())
Synthesized repair in: 45769ms
Tidyparse (valid/total): 517/931
Original error:
def parseEndHandler(self):
self.tmplput(self.gettmpl('top_tail')
self.parse_done = True
Bad Repair: invalid syntax (<unknown>, line 2):
def parseEndHandler(self):
** self.tmplput(self.gettmpl'top_tail')
self.parse_done = True
Synthesized repair in: 21101ms
Tidyparse (valid/total): 517/932
Original error:
def rotatexyz(alpha, beta, gamma):
'''Rotation matrix for rotating across the X, Y, and Z axes, in that order.'''
return rotatez(gamma).dot(rotatey(beta).dot(rotatex(alpha))
Good Repair:
def rotatexyz(alpha, beta, gamma):
'''Rotation matrix for rotating across the X, Y, and Z axes, in that order.'''
** return rotatez(gamma).dot(rotatey(beta).dot(rotatexalpha))
Synthesized repair in: 42437ms
Tidyparse (valid/total): 518/933
Original error:
def render_markdown(content):
output = Markup(markdown.markdown(content)
return output
Good Repair:
def render_markdown(content):
** output = Markupmarkdown.markdown(content)
return output
Synthesized repair in: 3648ms
Tidyparse (valid/total): 519/934
Original error:
import web
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo = True)
Kakikomi = TAble(
urls = (
'/', 'index'
)
Good Repair:
import web
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo = True)
** Kakikomi = TAble
urls = (
'/', 'index'
)
Synthesized repair in: 9302ms
Tidyparse (valid/total): 520/935
Original error:
def get_alphabetical_topics(course_module):
"""Return a list of team topics sorted alphabetically."""
return sorted(course_module.teams_topics, key = lambda t: t['name'].lower()
Bad Repair: invalid syntax (<unknown>, line 3):
def get_alphabetical_topics(course_module):
"""Return a list of team topics sorted alphabetically."""
** return sortedcourse_module.teams_topics, key = lambda t: t['name'].lower()
Synthesized repair in: 25463ms
Tidyparse (valid/total): 520/936
Original error:
def article_index(request):
articles = Article.objects.all().order_by("-last_update_timestamp")
return render_to_response("article_list.html",
{"articles": articles},
context_instance = RequestContext(request)
Good Repair:
def article_index(request):
articles = Article.objects.all().order_by("-last_update_timestamp")
return render_to_response("article_list.html",
{"articles": articles},
** context_instance = RequestContextrequest)
Synthesized repair in: 25932ms
Tidyparse (valid/total): 521/937
Original error:
def curry(_curried_func, * args, ** kwargs):
def _curried(* moreargs, ** morekwargs):
return _curried_func(*(args + moreargs), ** dict(kwargs, ** morekwargs)
return _curried
Good Repair:
def curry(_curried_func, * args, ** kwargs):
def _curried(* moreargs, ** morekwargs):
** return _curried_func(*(args + moreargs), ** dictkwargs, ** morekwargs)
return _curried
Synthesized repair in: 82915ms
Tidyparse (valid/total): 522/938
Original error:
def __createName(self, alreadyGivenName, num_char = 5):
if not(isinstance(num_char, int) and num_char > 1): raise AttributeError("The number of characters given is not a valid integer > 1."
while True:
name = '_' + ''.join(random.choice(string.ascii_letters) for x in range(num_char))
if not(name in alreadyGivenName):
return name
Bad Repair: invalid syntax (<unknown>, line 3):
def __createName(self, alreadyGivenName, num_char = 5):
if not(isinstance(num_char, int) and num_char > 1): raise AttributeError("The number of characters given is not a valid integer > 1."
while True:
** name = '_' + ''.join(random.choice(string.ascii_letters) for x in rangenum_char))
if not(name in alreadyGivenName):
return name
Synthesized repair in: 119372ms
Tidyparse (valid/total): 522/939
Original error:
def anno1(s, x):
return Annotation(
text = s,
showarrow = False,
x = x,
xref = 'x',
xanchor = 'center',
yref = 'paper',
yanchor = 'top',
y = - 0.05,
font = Font(
color = '#000',
size = 11
),
bgcolor = '#F5F3F2',
borderpad = 10
Bad Repair: unexpected indent (<unknown>, line 3):
def anno1(s, x):
** return Annotation
text = s,
showarrow = False,
x = x,
xref = 'x',
xanchor = 'center',
yref = 'paper',
yanchor = 'top',
y = - 0.05,
font = Font(
color = '#000',
size = 11
),
bgcolor = '#F5F3F2',
borderpad = 10
Synthesized repair in: 25931ms
Tidyparse (valid/total): 522/940
Original error:
def test_validate_integer_less_than_min_int_limit(self):
value = - 12
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.validate_integer,
value, 'limit', min_value = - 1, max_value = (2 ** 31)
Bad Repair: unexpected indent (<unknown>, line 4):
def test_validate_integer_less_than_min_int_limit(self):
value = - 12
** self.assertRaiseswebob.exc.HTTPBadRequest,
self.controller.validate_integer,
value, 'limit', min_value = - 1, max_value = (2 ** 31)
Synthesized repair in: 3984ms
Tidyparse (valid/total): 522/941
Original error:
def clear_cache(self):
for c in list(self.chroms.keys():
del self.chrroms[k]
Good Repair:
def clear_cache(self):
** for c in listself.chroms.keys():
del self.chrroms[k]
Synthesized repair in: 25122ms
Tidyparse (valid/total): 523/942
Original error:
def suite_teardown_failed(self, message):
"""Internal usage only."""
self.visit(SuiteTeardownFailed(message)
Good Repair:
def suite_teardown_failed(self, message):
"""Internal usage only."""
** self.visitSuiteTeardownFailed(message)
Synthesized repair in: 3475ms
Tidyparse (valid/total): 524/943
Original error:
from collections import defaultdict
lexical_order = lambda x: ''.join(sorted(str(x))
d = defaultdict(list)
Bad Repair: invalid syntax (<unknown>, line 3):
from collections import defaultdict
lexical_order = lambda x: ''.join(sorted(str(x))
** d = defaultdictlist)
Synthesized repair in: 4454ms
Tidyparse (valid/total): 524/944
Original error:
def parseLaunchpadDate(datestr, tz_sign, tz_hours, tz_minutes):
time_no_tz = calendar.timegm(time.strptime(datestr, "%Y-%m-%d %H: %M: %S")
tz_delta = 60 * 60 * int(tz_sign + tz_hours) + 60 * int(tz_minutes)
return time_no_tz - tz_delta
Good Repair:
def parseLaunchpadDate(datestr, tz_sign, tz_hours, tz_minutes):
** time_no_tz = calendar.timegm(time.strptimedatestr, "%Y-%m-%d %H: %M: %S")
tz_delta = 60 * 60 * int(tz_sign + tz_hours) + 60 * int(tz_minutes)
return time_no_tz - tz_delta
Synthesized repair in: 31694ms
Tidyparse (valid/total): 525/945
Original error:
def _decode_json(self, response):
body = response.read()
LOG.debug(_("Decoding JSON: %s") %(body)
if body:
return jsonutils.loads(body)
else:
return ""
Bad Repair: invalid syntax (<unknown>, line 3):
def _decode_json(self, response):
body = response.read()
** LOG.debug(_"Decoding JSON: %s") %(body)
if body:
return jsonutils.loads(body)
else:
return ""
Synthesized repair in: 38791ms
Tidyparse (valid/total): 525/946
Original error:
def isLoggedIn(_s, user, ip):
if('_logInTS' in _s
if user:
if ip == _s['_sessIP']:
return True
return False
Bad Repair: invalid syntax (<unknown>, line 2):
def isLoggedIn(_s, user, ip):
** if'_logInTS' in _s
if user:
if ip == _s['_sessIP']:
return True
return False
Synthesized repair in: 23508ms
Tidyparse (valid/total): 525/947
Original error:
def main():
input = raw_input('Input:')
print(operate(input)
Good Repair:
def main():
input = raw_input('Input:')
** print(operateinput)
Synthesized repair in: 24690ms
Tidyparse (valid/total): 526/948
Original error:
def log_api_result(self, entity, ckan):
if ckan.last_status != 200:
message = " %s" % ckan.last_message
else:
message = ""
log.info("PUT %s: %s%s" %(entity, ckan.last_status, message)
Bad Repair: invalid syntax (<unknown>, line 6):
def log_api_result(self, entity, ckan):
if ckan.last_status != 200:
message = " %s" % ckan.last_message
else:
message = ""
** log.info"PUT %s: %s%s" %(entity, ckan.last_status, message)
Synthesized repair in: 7161ms
Tidyparse (valid/total): 526/949
Original error:
def write_date(self, date):
"""Write the date header: :"""
self.write_fr_header('DTE', self.format_date(date)
Good Repair:
def write_date(self, date):
"""Write the date header: :"""
** self.write_fr_header('DTE', self.format_datedate)
Synthesized repair in: 6442ms
Tidyparse (valid/total): 527/950
Original error:
def test_firerole_literal_group(self):
"""firerole - firerole core testing literal group matching"""
self.failUnless(acc_firerole_check_user(self.user_info,
compile_role_definition("allow groups 'patata'\ndeny any"))
Good Repair:
def test_firerole_literal_group(self):
"""firerole - firerole core testing literal group matching"""
** self.failUnlessacc_firerole_check_user(self.user_info,
compile_role_definition("allow groups 'patata'\ndeny any"))
Synthesized repair in: 13742ms
Tidyparse (valid/total): 528/951
Original error:
def clear(self):
try:
os.remove(self._filename)
log.info("Removed cookie %s" % self._filename)
except OSError as e:
log.info("Could not remove file %s: %r" %(self._filename, e)
Good Repair:
def clear(self):
try:
os.remove(self._filename)
log.info("Removed cookie %s" % self._filename)
except OSError as e:
** log.info("Could not remove file %s: %r" %self._filename, e)
Synthesized repair in: 34241ms
Tidyparse (valid/total): 529/952
Original error:
class WorkgroupReviewSerializer(serializers.HyperlinkedModelSerializer):
""" Serializer for model interactions """
workgroup = serializers.PrimaryKeyRelatedField(queryset = Workgroup.objects.all()
class Meta:
""" Meta class for defining additional serializer characteristics """
model = WorkgroupReview
fields = (
'id', 'url', 'created', 'modified', 'question', 'answer',
'workgroup', 'reviewer', 'content_id'
)
Bad Repair: invalid syntax (<unknown>, line 4):
class WorkgroupReviewSerializer(serializers.HyperlinkedModelSerializer):
""" Serializer for model interactions """
workgroup = serializers.PrimaryKeyRelatedField(queryset = Workgroup.objects.all()
class Meta:
""" Meta class for defining additional serializer characteristics """
model = WorkgroupReview
** fields =
'id', 'url', 'created', 'modified', 'question', 'answer',
'workgroup', 'reviewer', 'content_id'
)
Synthesized repair in: 14866ms
Tidyparse (valid/total): 529/953
Original error:
def _calculate_objective(self, function_value):
"""Calculate fraction of change for obj value and standard"""
return(self.objective_function(function_value)
Good Repair:
def _calculate_objective(self, function_value):
"""Calculate fraction of change for obj value and standard"""
** returnself.objective_function(function_value)
Synthesized repair in: 19808ms
Tidyparse (valid/total): 530/954
Original error:
def retranslateUi(self, LandMod):
LandMod.setWindowTitle(_translate("LandMod", "Landscape Modifier", None))
self.label.setText(_translate("LandMod", "Class:", None))
self.helpText.setHtml(_translate("LandMod", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, LandMod):
LandMod.setWindowTitle(_translate("LandMod", "Landscape Modifier", None))
self.label.setText(_translate("LandMod", "Class:", None))
** self.helpText.setHtml(_translate)"LandMod", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 403473ms
Tidyparse (valid/total): 530/955
Original error:
def test_equality(self):
""" Manifest object should be equal to itself """
tools.eq_(self.old_manifest, load_manifest(StringIO(old_manifest))
Good Repair:
def test_equality(self):
""" Manifest object should be equal to itself """
** tools.eq_self.old_manifest, load_manifest(StringIO(old_manifest))
Synthesized repair in: 13301ms
Tidyparse (valid/total): 531/956
Original error:
def test_get_word_at_caret_returns_view_substr(self):
self.view.substr_return_value = 'a substring of a region'
self.assertEqual('a substring of a region', self.sublime_facade.get_word_at_caret(self.view)
Good Repair:
def test_get_word_at_caret_returns_view_substr(self):
self.view.substr_return_value = 'a substring of a region'
** self.assertEqual('a substring of a region', self.sublime_facade.get_word_at_caretself.view)
Synthesized repair in: 20086ms
Tidyparse (valid/total): 532/957
Original error:
def setup():
GPIO.setmode(GPIO.BOARD
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
Bad Repair: invalid syntax (<unknown>, line 3):
def setup():
GPIO.setmode(GPIO.BOARD
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
** GPIO.outputpin, GPIO.LOW)
Synthesized repair in: 13743ms
Tidyparse (valid/total): 532/958
Original error:
def __setitem__(self, key, val):
if isinstance(val, (bytes, str):
val = plistlib.Data(val)
dict.__setitem__(self, key, val)
self.commit()
Bad Repair: invalid syntax (<unknown>, line 2):
def __setitem__(self, key, val):
if isinstance(val, (bytes, str):
** val = plistlib.Dataval)
dict.__setitem__(self, key, val)
self.commit()
Synthesized repair in: 62157ms
Tidyparse (valid/total): 532/959
Original error:
def relellarc(self, rx, ry, xrot, laf, sf, x, y):
self.path.append('a%s, %s %s %s %s %s %s' %
(rx, ry, xrot, laf, sf, x, y)
Bad Repair: invalid syntax (<unknown>, line 2):
def relellarc(self, rx, ry, xrot, laf, sf, x, y):
** self.path.append'a%s, %s %s %s %s %s %s' %
(rx, ry, xrot, laf, sf, x, y)
Synthesized repair in: 7257ms
Tidyparse (valid/total): 532/960
Original error:
def select_page(self, url):
""" Selects page via page url """
self.__select_page(url.split('/')
Bad Repair: invalid syntax (<unknown>, line 3):
def select_page(self, url):
""" Selects page via page url """
** self.__select_page(url.split'/')
Synthesized repair in: 4703ms
Tidyparse (valid/total): 532/961
Original error:
def index():
projectdb = app.config['projectdb']
return render_template("index.html", projects = projectdb.get_all(fields = index_fields)
Bad Repair: invalid syntax (<unknown>, line 3):
def index():
projectdb = app.config['projectdb']
** return render_template"index.html", projects = projectdb.get_all(fields = index_fields)
Synthesized repair in: 7813ms
Tidyparse (valid/total): 532/962
Original error:
def TestFindSubset():
a = [
'BR WH PACT A2'
, 'BR WH PACT A3'
, 'BR WH PACT NURSE'
, 'BR WH PACT A5 EH'
, 'BR PACT A1'
, 'BR PACT A2 WH'
, 'BR PACT B1'
, 'BR PACT C1'
, 'BR PACT C2'
, 'BR PACT CRC C3'
Bad Repair: invalid syntax (<unknown>, line 2):
def TestFindSubset():
** a =
'BR WH PACT A2'
, 'BR WH PACT A3'
, 'BR WH PACT NURSE'
, 'BR WH PACT A5 EH'
, 'BR PACT A1'
, 'BR PACT A2 WH'
, 'BR PACT B1'
, 'BR PACT C1'
, 'BR PACT C2'
, 'BR PACT CRC C3'
Synthesized repair in: 2860ms
Tidyparse (valid/total): 532/963
Original error:
def __init__(self, bite_rate, transmission_rate_v_to_h, transmission_rate_h_to_v)):
"Metapopulation variables"
self.neighbors = None
self.infectious_neighbors_lice = None
self.N_neighbors = None
self.bite_rate = bite_rate
self.transmission_rate_v_to_h = transmission_rate_v_to_h
self.transmission_rate_h_to_v = transmission_rate_h_to_v
Good Repair:
** def __init__(self, bite_rate, transmission_rate_v_to_h, transmission_rate_h_to_v):
"Metapopulation variables"
self.neighbors = None
self.infectious_neighbors_lice = None
self.N_neighbors = None
self.bite_rate = bite_rate
self.transmission_rate_v_to_h = transmission_rate_v_to_h
self.transmission_rate_h_to_v = transmission_rate_h_to_v
Synthesized repair in: 1422ms
Tidyparse (valid/total): 533/964
Original error:
def _loadIndexHistory(self, startDate, endDate = datetime.datetime.now():
self.startDate = startDate
self.endDate = endDate
Good Repair:
** def _loadIndexHistory(self, startDate, endDate = datetime.datetime.now):
self.startDate = startDate
self.endDate = endDate
Synthesized repair in: 2891ms
Tidyparse (valid/total): 534/965
Original error:
import logging
import os
import sys
import argparse
import tempfile
< % if(package.flask.pyres){% >
from pyres import ResQ
from < %= package.pythonName % >.app import create_app
Bad Repair: invalid syntax (<unknown>, line 6):
import logging
import os
import sys
import argparse
import tempfile
** < % if(package.flask.pyres)% >
from pyres import ResQ
from < %= package.pythonName % >.app import create_app
Synthesized repair in: 4231ms
Tidyparse (valid/total): 534/966
Original error:
from prodsyspa.components.collector.run import get_args, proceed
if __name__ == '__main__':
proceed(args = get_args()
Good Repair:
from prodsyspa.components.collector.run import get_args, proceed
if __name__ == '__main__':
** proceed(args = get_args)
Synthesized repair in: 621ms
Tidyparse (valid/total): 535/967
Original error:
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** /
package edu.princeton.cs.algs4
public class GREP:
private GREP(): }
Bad Repair: unexpected indent (<unknown>, line 1):
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** /
package edu.princeton.cs.algs4
public class GREP:
** private GREP():
Synthesized repair in: 1021ms
Tidyparse (valid/total): 535/968
Original error:
import numpy as np
import caffe
caffe.set_mode_cpu()
net = caffe.Net('classify_xor.prototxt', caffe.TEST
Bad Repair: invalid syntax (<unknown>, line 4):
import numpy as np
import caffe
caffe.set_mode_cpu()
** net = caffe.Net'classify_xor.prototxt', caffe.TEST
Synthesized repair in: 1960ms
Tidyparse (valid/total): 535/969
Original error:
import pyaf.tests.periodicities.period_test as per
per.buildModel((120, 'H', 50);
Good Repair:
import pyaf.tests.periodicities.period_test as per
** per.buildModel(120, 'H', 50);
Synthesized repair in: 3011ms
Tidyparse (valid/total): 536/970
Original error:
def _init_readers(self):
for iterator in self.iterators:
t = Thread(target = _enqueue_output, args = (iterator, self.queue)
t.daemon = True
t.start()
Bad Repair: invalid syntax (<unknown>, line 4):
def _init_readers(self):
for iterator in self.iterators:
t = Thread(target = _enqueue_output, args = (iterator, self.queue)
t.daemon = True
** t.start)
Synthesized repair in: 22186ms
Tidyparse (valid/total): 536/971
Original error:
def openbrace():
asdf = 3
asdf
asdf(
asdf
return 1
Bad Repair: unexpected indent (<unknown>, line 3):
def openbrace():
asdf = 3
asdf
** asdf
asdf
return 1
Synthesized repair in: 6229ms
Tidyparse (valid/total): 536/972
Original error:
def test_date_utc(self):
d = datetime.date.today()
d_utc = datetime.datetime(* d.timetuple()[: 3]) + self.local_utcoffset
self.assertEqual(rfc3339(d,
utc = True),
d_utc.strftime('%Y-%m-%dT%H: %M: %SZ')
Bad Repair: unexpected indent (<unknown>, line 6):
def test_date_utc(self):
d = datetime.date.today()
d_utc = datetime.datetime(* d.timetuple()[: 3]) + self.local_utcoffset
** self.assertEqual(rfc3339d,
utc = True),
d_utc.strftime('%Y-%m-%dT%H: %M: %SZ')
Synthesized repair in: 220134ms
Tidyparse (valid/total): 536/973
Original error:
import fix_paths
import common
from models.commit import Commit
session = common.Session()
for commit in session.query(Commitj
Bad Repair: invalid syntax (<unknown>, line 5):
import fix_paths
import common
from models.commit import Commit
session = common.Session()
** for commit in session.queryCommitj
Synthesized repair in: 2911ms
Tidyparse (valid/total): 536/974
Original error:
def Header():
return Util.BuildHeader(_fmt,
"region"
Bad Repair: unexpected indent (<unknown>, line 3):
def Header():
** return Util.BuildHeader_fmt,
"region"
Synthesized repair in: 1180ms
Tidyparse (valid/total): 536/975
Original error:
def RawAudioMixer():
return _RawAudioMixer(sample_rate = 8000,
readThreshold = 0.5,
bufferingLimit = 2.0,
readInterval = 0.1
Bad Repair: invalid syntax (<unknown>, line 2):
def RawAudioMixer():
** return _RawAudioMixersample_rate = 8000,
readThreshold = 0.5,
bufferingLimit = 2.0,
readInterval = 0.1
Synthesized repair in: 1867ms
Tidyparse (valid/total): 536/976
Original error:
import pyaf.tests.periodicities.period_test as per
per.buildModel((12, 'W', 1600);
Good Repair:
import pyaf.tests.periodicities.period_test as per
** per.buildModel(12, 'W', 1600);
Synthesized repair in: 2919ms
Tidyparse (valid/total): 537/977
Original error:
"""DEFINES: """
__version__ = "$Revision: 1 $"
__iversion__ = int(filter(str.isdigit, __version__)
import calc_rho
import isaac
import copy as copier
import numpy as np
import cPickle as pickle
import scipy.interpolate as interp
from multiprocessing import Pool, cpu_count
import pynbody
SimArray = pynbody.array.SimArray
Good Repair:
"""DEFINES: """
__version__ = "$Revision: 1 $"
** __iversion__ = int(filterstr.isdigit, __version__)
import calc_rho
import isaac
import copy as copier
import numpy as np
import cPickle as pickle
import scipy.interpolate as interp
from multiprocessing import Pool, cpu_count
import pynbody
SimArray = pynbody.array.SimArray
Synthesized repair in: 1695ms
Tidyparse (valid/total): 538/978
Original error:
def get_brain_input_dict(self):
return{
'theta': 50,
'alpha': 25
Bad Repair: unexpected indent (<unknown>, line 3):
def get_brain_input_dict(self):
** return
'theta': 50,
'alpha': 25
Synthesized repair in: 1669ms
Tidyparse (valid/total): 538/979
Original error:
class Test(ob
def method(self):
pass
Bad Repair: invalid syntax (<unknown>, line 2):
class Test(ob
** def methodself):
pass
Synthesized repair in: 4047ms
Tidyparse (valid/total): 538/980
Original error:
import psycopg2
conn = psycopg2.connect("dbname=beeva_test user=beeva password=beeva2014")
cur = conn.cursor()
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
conn.commit()
cur.close()
conn.close()
Bad Repair: invalid syntax (<unknown>, line 6):
import psycopg2
conn = psycopg2.connect("dbname=beeva_test user=beeva password=beeva2014")
cur = conn.cursor()
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)",
conn.commit()
cur.close()
** conn.close)
Synthesized repair in: 23492ms
Tidyparse (valid/total): 538/981
Original error:
def test_with_correct_value_model_validates(self):
mtv = ModelToValidate(number = 10, name = 'Some Name')
self.assertEqual(None, mtv.full_clean()
Good Repair:
def test_with_correct_value_model_validates(self):
mtv = ModelToValidate(number = 10, name = 'Some Name')
** self.assertEqual(None, mtv.full_clean)
Synthesized repair in: 24578ms
Tidyparse (valid/total): 539/982
Original error:
def get_trailing_number(s):
m = re.search(r'\d+$', s)
return int(m.group() if m else None
Good Repair:
def get_trailing_number(s):
m = re.search(r'\d+$', s)
** return intm.group() if m else None
Synthesized repair in: 7052ms
Tidyparse (valid/total): 540/983
Original error:
def register():
"Inform main catalyst program of the contents of this plugin."
return({
"arm": arch_arm,
"armv4l": arch_armv4l,
"armv4tl": arch_armv4tl,
"armv5tl": arch_armv5tl,
"armv5tel": arch_armv5tel,
"armv5tejl": arch_armv5tejl,
"armv6j": arch_armv6j,
"armv6z": arch_armv6z,
"armv6zk": arch_armv6zk,
"armv7a": arch_armv7a,
"armv6j_hardfp": arch_armv6j_hardfp,
"armv7a_hardfp": arch_armv7a_hardfp,
"armeb": arch_armeb,
"armv5teb": arch_armv5teb
Bad Repair: unexpected indent (<unknown>, line 4):
def register():
"Inform main catalyst program of the contents of this plugin."
** return()
"arm": arch_arm,
"armv4l": arch_armv4l,
"armv4tl": arch_armv4tl,
"armv5tl": arch_armv5tl,
"armv5tel": arch_armv5tel,
"armv5tejl": arch_armv5tejl,
"armv6j": arch_armv6j,
"armv6z": arch_armv6z,
"armv6zk": arch_armv6zk,
"armv7a": arch_armv7a,
"armv6j_hardfp": arch_armv6j_hardfp,
"armv7a_hardfp": arch_armv7a_hardfp,
"armeb": arch_armeb,
"armv5teb": arch_armv5teb
Synthesized repair in: 15905ms
Tidyparse (valid/total): 540/984
Original error:
def cython_preamble(use_openmp = False):
"""Returns list of code segments for Cython preamble."""
if use_openmp:
openmp_string = 'from qutip.cy.openmp.parfuncs cimport spmvpy_openmp'
else:
openmp_string = ''
return[""" # This file is generated automatically by QuTiP."""
Good Repair:
def cython_preamble(use_openmp = False):
"""Returns list of code segments for Cython preamble."""
if use_openmp:
openmp_string = 'from qutip.cy.openmp.parfuncs cimport spmvpy_openmp'
else:
openmp_string = ''
** return""" # This file is generated automatically by QuTiP."""
Synthesized repair in: 6365ms
Tidyparse (valid/total): 541/985
Original error:
def createNote(self, title, noteString, notebookGuid):
"""Posts a note to evernote using ``title`` as the title and"""
noteStore = self.getNoteStore()
note = Types.Note()
note.title = title
note.content = self.wrapNoteString(noteString)
if notebookGuid:
note.notebookGuid = notebookGuid
note = noteStore.createNote(note)
if self._testing:
print(str(note)))
return note
Good Repair:
def createNote(self, title, noteString, notebookGuid):
"""Posts a note to evernote using ``title`` as the title and"""
noteStore = self.getNoteStore()
note = Types.Note()
note.title = title
note.content = self.wrapNoteString(noteString)
if notebookGuid:
note.notebookGuid = notebookGuid
note = noteStore.createNote(note)
if self._testing:
** print(str(note))
return note
Synthesized repair in: 15808ms
Tidyparse (valid/total): 542/986
Original error:
def _jupyter_server_extension_paths():
return[{
"module": "nteract_on_jupyter"
Bad Repair: unexpected indent (<unknown>, line 3):
def _jupyter_server_extension_paths():
** return[]
"module": "nteract_on_jupyter"
Synthesized repair in: 11214ms
Tidyparse (valid/total): 542/987
Original error:
def get_identity(self):
"""Returns the UID, the UID where the Bricklet is connected to, """
return GetIdentity(* self.ipcon.send_request(self, BrickletIndustrialAnalogOut.FUNCTION_GET_IDENTITY, (), '', '8s 8s c 3B 3B H')
Good Repair:
def get_identity(self):
"""Returns the UID, the UID where the Bricklet is connected to, """
** return GetIdentity(* self.ipcon.send_request(self, BrickletIndustrialAnalogOut.FUNCTION_GET_IDENTITY, ), '', '8s 8s c 3B 3B H')
Synthesized repair in: 20152ms
Tidyparse (valid/total): 543/988
Original error:
from oslo.config import cfg
from cinder import flags
from cinder import test
FLAGS = flags.FLAGS
FLAGS.register_opt(cfg.StrOpt('flags_unittest',
default = 'foo',
help = 'for testing purposes only')
Bad Repair: invalid syntax (<unknown>, line 5):
from oslo.config import cfg
from cinder import flags
from cinder import test
FLAGS = flags.FLAGS
** FLAGS.register_opt(cfg.StrOpt'flags_unittest',
default = 'foo',
help = 'for testing purposes only')
Synthesized repair in: 2502ms
Tidyparse (valid/total): 543/989
Original error:
def process(self, pyfile):
self.pyfile = pyfile
if not self.file_exists():
self.offline()
self.pyfile.name = self.get_file_name()
self.download(self.get_file_url()
Good Repair:
def process(self, pyfile):
self.pyfile = pyfile
if not self.file_exists():
self.offline()
self.pyfile.name = self.get_file_name()
** self.download(self.get_file_url)
Synthesized repair in: 117345ms
Tidyparse (valid/total): 544/990
Original error:
def __len__(self):
"""Return the number of trajectories in the ensemble."""
return sum(len(trajs) for trajs in self.bins.values()
Good Repair:
def __len__(self):
"""Return the number of trajectories in the ensemble."""
** return sum(len(trajs) for trajs in self.bins.values)
Synthesized repair in: 11716ms
Tidyparse (valid/total): 545/991
Original error:
def resource_adapter(obj, request = None):
return{
'id': obj.id,
'naam': obj.naam,
'voornaam': obj.voornaam
Bad Repair: unexpected indent (<unknown>, line 3):
def resource_adapter(obj, request = None):
** return
'id': obj.id,
'naam': obj.naam,
'voornaam': obj.voornaam
Synthesized repair in: 11094ms
Tidyparse (valid/total): 545/992
Original error:
def test_i18n_name_with_content(self):
self._run_check('<div i18n:translate="">This is text for '
'<span i18n:translate="" tal:content="bar" i18n:name="bar_name"/>.'
Bad Repair: invalid syntax (<unknown>, line 2):
def test_i18n_name_with_content(self):
** self._run_check'<div i18n:translate="">This is text for '
'<span i18n:translate="" tal:content="bar" i18n:name="bar_name"/>.'
Synthesized repair in: 1221ms
Tidyparse (valid/total): 545/993
Original error:
class Solution2object):
def hammingWeight(self, n):
""":type n: int"""
count = 0
while n != 0:
if n % 2 == 1:
count += 1
n /= 2
return count
Good Repair:
** class Solution2object:
def hammingWeight(self, n):
""":type n: int"""
count = 0
while n != 0:
if n % 2 == 1:
count += 1
n /= 2
return count
Synthesized repair in: 4217ms
Tidyparse (valid/total): 546/994
Original error:
def add_arguments(self, parser):
parser.add_argument(
'--dry-run',
action = 'store_true',
dest = 'dry_run',
default = False,
help = 'Don\'t change anything, output what needs '
Bad Repair: unexpected indent (<unknown>, line 3):
def add_arguments(self, parser):
** parser.add_argument
'--dry-run',
action = 'store_true',
dest = 'dry_run',
default = False,
help = 'Don\'t change anything, output what needs '
Synthesized repair in: 1458ms
Tidyparse (valid/total): 546/995
Original error:
def handler500(request):
response = render_to_response('500.html', {},
context_instance = RequestContext(request)
response.status_code = 500
return response
Bad Repair: invalid syntax (<unknown>, line 2):
def handler500(request):
** response = render_to_response'500.html', {},
context_instance = RequestContext(request)
response.status_code = 500
return response
Synthesized repair in: 7452ms
Tidyparse (valid/total): 546/996
Original error:
def pointgraph_from_rect(rect):
r"""Convert an opencv detection to a menpo.shape.PointDirectedGraph."""
x, y, w, h = rect
return bounding_box((y, x), (y + h, x + w)
Good Repair:
def pointgraph_from_rect(rect):
r"""Convert an opencv detection to a menpo.shape.PointDirectedGraph."""
x, y, w, h = rect
** return bounding_box((y, x), y + h, x + w)
Synthesized repair in: 5634ms
Tidyparse (valid/total): 547/997
Original error:
def parse_message(msg):
if len(msg) >= 1:
msg = msg.split(' ')
options = {'!commands': command_com,
'!example': command_mod,
if msg[0] in options:
options[msg[0]]()
Bad Repair: invalid syntax (<unknown>, line 4):
def parse_message(msg):
if len(msg) >= 1:
msg = msg.split(' ')
** options = '!commands': command_com,
'!example': command_mod,
if msg[0] in options:
options[msg[0]]()
Synthesized repair in: 415312ms
Tidyparse (valid/total): 547/998
Original error:
def getPinUri(self):
return self.PREFIX + 'auth/authorize?grant_type=authorization_pin&client_id=%s&response_type=pin&redirect_uri=%s' %(
self.id, self.REDIRECTURI
Bad Repair: invalid syntax (<unknown>, line 2):
def getPinUri(self):
** return self.PREFIX + 'auth/authorize?grant_type=authorization_pin&client_id=%s&response_type=pin&redirect_uri=%s' %
self.id, self.REDIRECTURI
Synthesized repair in: 10851ms
Tidyparse (valid/total): 547/999
Original error:
def describe_user(self, _context, name, ** _kwargs):
"""Returns user data, including access and secret keys."""
return user_dict(users.UserManager.instance().get_user(name)
Good Repair:
def describe_user(self, _context, name, ** _kwargs):
"""Returns user data, including access and secret keys."""
** return user_dict(users.UserManager.instance).get_user(name)
Synthesized repair in: 5466ms
Tidyparse (valid/total): 548/1000
Original error:
import os
import platform
repo_root = os.path.dirname(os.path.abspath(__file__)
Good Repair:
import os
import platform
** repo_root = os.path.dirnameos.path.abspath(__file__)
Synthesized repair in: 2479ms
Tidyparse (valid/total): 549/1001
Original error:
def _dist_wrapper():
"""Add temporary distribution build files(and then clean up)."""
try:
for rst_file, txt_file in zip(SDIST_RST_FILES, SDIST_TXT_FILES):
local("cp %s %s" %(rst_file, txt_file)
yield
finally:
for rst_file in SDIST_TXT_FILES:
local("rm -f %s" % rst_file, capture = False)
Bad Repair: invalid syntax (<unknown>, line 5):
def _dist_wrapper():
"""Add temporary distribution build files(and then clean up)."""
try:
for rst_file, txt_file in zip(SDIST_RST_FILES, SDIST_TXT_FILES):
** local"cp %s %s" %(rst_file, txt_file)
yield
finally:
for rst_file in SDIST_TXT_FILES:
local("rm -f %s" % rst_file, capture = False)
Synthesized repair in: 121852ms
Tidyparse (valid/total): 549/1002
Original error:
import weechat
weechat.register("random_topic", "KurzGedanke", "1.0", "GNU v3", "returns a random topic", "", "")
weechat.prnt("", "Hello, from python script!"
Bad Repair: invalid syntax (<unknown>, line 3):
import weechat
weechat.register("random_topic", "KurzGedanke", "1.0", "GNU v3", "returns a random topic", "", "")
** weechat.prnt"", "Hello, from python script!"
Synthesized repair in: 8654ms
Tidyparse (valid/total): 549/1003
Original error:
def build_response(session_attributes, speechlet_response):
return{
"version": "1.0",
"sessionAttributes": session_attributes,
"response": speechlet_response
Bad Repair: unexpected indent (<unknown>, line 3):
def build_response(session_attributes, speechlet_response):
** return
"version": "1.0",
"sessionAttributes": session_attributes,
"response": speechlet_response
Synthesized repair in: 6042ms
Tidyparse (valid/total): 549/1004
Original error:
class styleState(enumeration):
error = InvalidStyleState
valuelist = [
"normal", "highlight"
Bad Repair: invalid syntax (<unknown>, line 3):
class styleState(enumeration):
error = InvalidStyleState
** valuelist =
"normal", "highlight"
Synthesized repair in: 11464ms
Tidyparse (valid/total): 549/1005
Original error:
def utree_search(input_compressed_tree, input_fasta_to_search, output, shell = False):
cmd = [
'utree-search',
input_compressed_tree,
input_fasta_to_search,
output
Bad Repair: invalid syntax (<unknown>, line 2):
def utree_search(input_compressed_tree, input_fasta_to_search, output, shell = False):
** cmd =
'utree-search',
input_compressed_tree,
input_fasta_to_search,
output
Synthesized repair in: 1383ms
Tidyparse (valid/total): 549/1006
Original error:
def http_date_to_time(datestr, want_gmt = True):
"""http_date_to_time(datestr)"""
t = time.mktime(eut.parsedate(datestr)
if want_gmt: return time.gmtime(t)
else: return t
Bad Repair: invalid syntax (<unknown>, line 4):
def http_date_to_time(datestr, want_gmt = True):
"""http_date_to_time(datestr)"""
t = time.mktime(eut.parsedate(datestr)
** if want_gmt: return time.gmtimet)
else: return t
Synthesized repair in: 55782ms
Tidyparse (valid/total): 549/1007
Original error:
class refreshMode(enumeration):
error = InvalidRefreshMode
valuelist = [
"onChange", "onInterval", "onExpire"
Bad Repair: invalid syntax (<unknown>, line 3):
class refreshMode(enumeration):
error = InvalidRefreshMode
** valuelist =
"onChange", "onInterval", "onExpire"
Synthesized repair in: 1400ms
Tidyparse (valid/total): 549/1008
Original error:
def base_endpoint(self):
return{
"adminURL": "http://localhost:9292",
"internalURL": "http://localhost:9292",
"publicURL": "http://localhost:9292"
Bad Repair: unexpected indent (<unknown>, line 3):
def base_endpoint(self):
** return
"adminURL": "http://localhost:9292",
"internalURL": "http://localhost:9292",
"publicURL": "http://localhost:9292"
Synthesized repair in: 9047ms
Tidyparse (valid/total): 549/1009
Original error:
import helper
import new
if __name__ == "__main__":
helper.greeting(new.const("hello", 3)
Bad Repair: invalid syntax (<unknown>, line 4):
import helper
import new
if __name__ == "__main__":
** helper.greeting(new.const"hello", 3)
Synthesized repair in: 1472ms
Tidyparse (valid/total): 549/1010
Original error:
import a
import c, d
from e import f
from g import h, i
from j import *
from k import l as m
import n as o
import a1, a2 as a3, a4, a5
from p import b1, b2 as b3, b4, b5
from x import(y as z1, z2,
z3, z4)
import X as
import Y,
from Z import(A
Bad Repair: invalid syntax (<unknown>, line 12):
import a
import c, d
from e import f
from g import h, i
from j import *
from k import l as m
import n as o
import a1, a2 as a3, a4, a5
from p import b1, b2 as b3, b4, b5
from x import(y as z1, z2,
z3, z4)
import X as
import Y,
** from Z importA
Synthesized repair in: 6313ms
Tidyparse (valid/total): 549/1011
Original error:
from mock import patch
from nailgun.test import base
from nailgun.extensions.network_manager.serializers import neutron_serializers
CREDS = {'tenant': {'value': 'NONDEFAULT'}
Bad Repair: invalid syntax (<unknown>, line 4):
from mock import patch
from nailgun.test import base
from nailgun.extensions.network_manager.serializers import neutron_serializers
** CREDS = 'tenant': {'value': 'NONDEFAULT'}
Synthesized repair in: 1004ms
Tidyparse (valid/total): 549/1012
Original error:
from string import join, upper
import sys
import os
dir = os.path.dirname(os.path.abspath(__file__)
Good Repair:
from string import join, upper
import sys
import os
** dir = os.path.dirname(os.path.abspath__file__)
Synthesized repair in: 2477ms
Tidyparse (valid/total): 550/1013
Original error:
def setup(topdir):
srcdir = os.path.join(topdir, 'src')
os.chdir(srcdir)
utils.configure('--with-elfutils=elfutils --prefix=%s/systemtap' % topdir)
utils.make('-j %d' % utils.count_cpus()
utils.make('install')
os.chdir(topdir)
Bad Repair: invalid syntax (<unknown>, line 6):
def setup(topdir):
srcdir = os.path.join(topdir, 'src')
os.chdir(srcdir)
utils.configure('--with-elfutils=elfutils --prefix=%s/systemtap' % topdir)
utils.make('-j %d' % utils.count_cpus()
utils.make('install')
** os.chdirtopdir)
Synthesized repair in: 264045ms
Tidyparse (valid/total): 550/1014
Original error:
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0] = row[idx]
return d
Bad Repair: invalid syntax (<unknown>, line 4):
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
** d[col[0] = rowidx]
return d
Synthesized repair in: 47397ms
Tidyparse (valid/total): 550/1015
Original error:
class Test_GUI(TestCase):
def basic_run_test(self:
pass
Bad Repair: invalid syntax (<unknown>, line 2):
class Test_GUI(TestCase):
** def basic_run_testself:
pass
Synthesized repair in: 8469ms
Tidyparse (valid/total): 550/1016
Original error:
def decrypt(encKey, message):
oldMsg = ""
for i in range(
newMsg +=
return oldMsg
Bad Repair: invalid syntax (<unknown>, line 3):
def decrypt(encKey, message):
oldMsg = ""
** for i in range
newMsg +=
return oldMsg
Synthesized repair in: 1393ms
Tidyparse (valid/total): 550/1017
Original error:
class listItemType(enumeration):
error = InvalidListItemType
valuelist = [
"radioFolder", "check", "checkHideChildren", "checkOffOnly"
Bad Repair: invalid syntax (<unknown>, line 3):
class listItemType(enumeration):
error = InvalidListItemType
** valuelist =
"radioFolder", "check", "checkHideChildren", "checkOffOnly"
Synthesized repair in: 1422ms
Tidyparse (valid/total): 550/1018
Original error:
import sys
import mock
import unittest
from pkg_resources import resource_filename
sys.path.append(resource_filename(__name__, '../hooks')
import actions
Good Repair:
import sys
import mock
import unittest
from pkg_resources import resource_filename
** sys.path.append(resource_filename__name__, '../hooks')
import actions
Synthesized repair in: 1591ms
Tidyparse (valid/total): 551/1019
Original error:
class SchemaFieldType(enumeration):
error = InvalidSchemaFieldType
valuelist = [
"string", "int", "uint", "short", "ushort", "float", "double", "bool"
Bad Repair: invalid syntax (<unknown>, line 3):
class SchemaFieldType(enumeration):
error = InvalidSchemaFieldType
** valuelist =
"string", "int", "uint", "short", "ushort", "float", "double", "bool"
Synthesized repair in: 1501ms
Tidyparse (valid/total): 551/1020
Original error:
def getMobID(name):
log("Finding the ID for %s" % name, "debug"
pass
Bad Repair: invalid syntax (<unknown>, line 2):
def getMobID(name):
** log"Finding the ID for %s" % name, "debug"
pass
Synthesized repair in: 5504ms
Tidyparse (valid/total): 551/1021
Original error:
def retranslateUi(self, TabnannyDialog):
_translate = QtCore.QCoreApplication.translate
TabnannyDialog.setWindowTitle(_translate("TabnannyDialog", "Tabnanny Result"))
TabnannyDialog.setWhatsThis(_translate("TabnannyDialog", "<b>Tabnanny Results</b>\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, TabnannyDialog):
_translate = QtCore.QCoreApplication.translate
TabnannyDialog.setWindowTitle(_translate("TabnannyDialog", "Tabnanny Result"))
** TabnannyDialog.setWhatsThis(_translate)"TabnannyDialog", "<b>Tabnanny Results</b>\n"
Synthesized repair in: 315683ms
Tidyparse (valid/total): 551/1022
Original error:
class altitudeMode(enumeration):
error = InvalidAltitudeMode
valuelist = [
"clampToGround", "relativeToGround", "absolute"
Bad Repair: invalid syntax (<unknown>, line 3):
class altitudeMode(enumeration):
error = InvalidAltitudeMode
** valuelist =
"clampToGround", "relativeToGround", "absolute"
Synthesized repair in: 4477ms
Tidyparse (valid/total): 551/1023
Original error:
def pocket_list(self, * args):
if not self.token:
if self.pocket_last_update:
pocketclient.get_items(self.
else:
pass
pass
Bad Repair: invalid syntax (<unknown>, line 4):
def pocket_list(self, * args):
if not self.token:
if self.pocket_last_update:
** pocketclient.get_itemsself.
else:
pass
pass
Synthesized repair in: 2791ms
Tidyparse (valid/total): 551/1024
Original error:
def retranslateUi(self, FileEditorDialog):
_translate = QtCore.QCoreApplication.translate
FileEditorDialog.setWindowTitle(_translate("FileEditorDialog", "File editor"))
self.uiFileTextEdit.setHtml(_translate("FileEditorDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Bad Repair: invalid syntax (<unknown>, line 4):
def retranslateUi(self, FileEditorDialog):
_translate = QtCore.QCoreApplication.translate
FileEditorDialog.setWindowTitle(_translate("FileEditorDialog", "File editor"))
** self.uiFileTextEdit.setHtml(_translate)"FileEditorDialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
Synthesized repair in: 8420ms
Tidyparse (valid/total): 551/1025
Original error:
class A:
def foo(self):
self.a = < caret >{"1": 1, "2": 2
Bad Repair: invalid syntax (<unknown>, line 3):
class A:
def foo(self):
** self.a = < caret >"1": 1, "2": 2
Synthesized repair in: 3575ms
Tidyparse (valid/total): 551/1026
Original error:
def addResidue(self, resNum, resName):
found = False
for r in self.residues:
if r.num == resNum:
found = True
if not found:
self.residues.append(Residue(resNum, resName)
self.weight += residueWeight(resName)
self.protons += residueProtons(resName)
Bad Repair: invalid syntax (<unknown>, line 8):
def addResidue(self, resNum, resName):
found = False
for r in self.residues:
if r.num == resNum:
found = True
if not found:
self.residues.append(Residue(resNum, resName)
** self.weight += residueWeightresName)
self.protons += residueProtons(resName)
Synthesized repair in: 52600ms
Tidyparse (valid/total): 551/1027
Original error:
def __init__(self, width, case_width = 10):
self.cases = []
self.width = width
self.case_width = case_width
self.screen_width = self.case_width * self.width
self.screen = pygame.display.set_mode((self.screen_width, self.screen_width)
self._initialize_grill()
Good Repair:
def __init__(self, width, case_width = 10):
self.cases = []
self.width = width
self.case_width = case_width
self.screen_width = self.case_width * self.width
** self.screen = pygame.display.set_mode(self.screen_width, self.screen_width)
self._initialize_grill()
Synthesized repair in: 8684ms
Tidyparse (valid/total): 552/1028
Original error:
from eulerlib import *
p = numtheory.Divisors(1000000)
n = 1
m = 0
l = 0.0
while n <= 1000000:
k = float(p.phi(n)
s = float(n)
t = s / k
if t > l:
l = t
m = n
n = n + 1
else:
n = n + 1
print(m)
Bad Repair: invalid syntax (<unknown>, line 8):
from eulerlib import *
p = numtheory.Divisors(1000000)
n = 1
m = 0
l = 0.0
while n <= 1000000:
k = float(p.phi(n)
s = float(n)
t = s / k
if t > l:
l = t
m = n
n = n + 1
else:
n = n + 1
** printm)
Synthesized repair in: 7860ms
Tidyparse (valid/total): 552/1029
Original error:
def __str__(self):
return '%s.%s%s' %(
self.klass, self.name, self.jni
Bad Repair: invalid syntax (<unknown>, line 2):
def __str__(self):
** return '%s.%s%s' %
self.klass, self.name, self.jni
Synthesized repair in: 9885ms
Tidyparse (valid/total): 552/1030
Original error:
def catchDone(state, action, state2):
if state2 not in rewardMap:
rewardMap[state2)] = - 10
print("punished")
Good Repair:
def catchDone(state, action, state2):
if state2 not in rewardMap:
** rewardMap[state2] = - 10
print("punished")
Synthesized repair in: 92815ms
Tidyparse (valid/total): 553/1031
Original error:
"""Tasks:"""
def CreateUser(os,
"""class sitePermissions:"""
"""sessionId = None"""
"""if (self.persistent):"""
"""self.userName = userName #From cookie"""
"""Permissions must be explicitly set for user or group, with a default to invisible"""
"""sitePermissionLevel = sitePermissions.Guest"""
Bad Repair: invalid syntax (<unknown>, line 3):
"""Tasks:"""
def CreateUser(os,
"""class sitePermissions:"""
"""sessionId = None"""
** """if self.persistent):"""
"""self.userName = userName #From cookie"""
"""Permissions must be explicitly set for user or group, with a default to invisible"""
"""sitePermissionLevel = sitePermissions.Guest"""
Synthesized repair in: 3890ms
Tidyparse (valid/total): 553/1032
Original error:
from setuptools import setup, Command
import codecs
import re
import os
here = os.path.abspath(os.path.dirname(__file__)
Good Repair:
from setuptools import setup, Command
import codecs
import re
import os
** here = os.path.abspath(os.path.dirname__file__)
Synthesized repair in: 1536ms
Tidyparse (valid/total): 554/1033
Original error:
import os
import sys
import unittest
from Tribler.Core.CacheDB.sqlitecachedb import SQLiteCacheDB, str2bin, CURRENT_MAIN_DB_VERSION
from Tribler.Core.CacheDB.SqliteCacheDBHandler import PreferenceDBHandler, MyPreferenceDBHandler
from Tribler.Core.BuddyCast.TorrentCollecting import SimpleTorrentCollecting
from bak_tribler_sdb import *
CREATE_SQL_FILE = os.path.join('..', "schema_sdb_v" + str(CURRENT_MAIN_DB_VERSION) + ".sql"))
assert os.path.isfile(CREATE_SQL_FILE)
Good Repair:
import os
import sys
import unittest
from Tribler.Core.CacheDB.sqlitecachedb import SQLiteCacheDB, str2bin, CURRENT_MAIN_DB_VERSION
from Tribler.Core.CacheDB.SqliteCacheDBHandler import PreferenceDBHandler, MyPreferenceDBHandler
from Tribler.Core.BuddyCast.TorrentCollecting import SimpleTorrentCollecting
from bak_tribler_sdb import *
** CREATE_SQL_FILE = os.path.join('..', "schema_sdb_v" + str(CURRENT_MAIN_DB_VERSION + ".sql"))
assert os.path.isfile(CREATE_SQL_FILE)
Synthesized repair in: 4367ms
Tidyparse (valid/total): 555/1034
Original error:
"""An abstraction around the source and classfiles for a Java application."""
import os
import os.path
import google
_SDKROOT = os.path.dirname(os.path.dirname(google.__file__)
Good Repair:
"""An abstraction around the source and classfiles for a Java application."""
import os
import os.path
import google
** _SDKROOT = os.path.dirname(os.path.dirnamegoogle.__file__)
Synthesized repair in: 768ms
Tidyparse (valid/total): 556/1035
Original error:
def test_get_my_ipv4_address_with_multi_ipv4_on_single_interface(self):
response_route = """172.18.56.0/24 dev customer proto kernel scope link src 172.18.56.22"""
response_addr = (""
Good Repair:
def test_get_my_ipv4_address_with_multi_ipv4_on_single_interface(self):
response_route = """172.18.56.0/24 dev customer proto kernel scope link src 172.18.56.22"""
** response_addr = ""
Synthesized repair in: 2710ms
Tidyparse (valid/total): 557/1036
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment