{"sample_uid": "defects4j_function_repair::Compress-35", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean verifyCheckSum(byte[] header) {\n long storedSum = 0;\n long unsignedSum = 0;\n long signedSum = 0;\n int digits = 0;\n for (int i = 0; i < header.length; i++) {\n byte b = header[i];\n if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {\n if ('0' <= b && b <= '7' && digits++ < 6) {\n storedSum = storedSum * 8 + b - '0';\n } else if (digits > 0) {\n digits = 6;\n }\n b = ' ';\n }\n unsignedSum += 0xff & b;\n signedSum += b;\n }\n return storedSum == unsignedSum || storedSum == signedSum;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean verifyCheckSum(byte[] header) {\n long storedSum = 0;\n long unsignedSum = 0;\n long signedSum = 0;\n int digits = 0;\n for (int i = 0; i < header.length; i++) {\n byte b = header[i];\n if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {\n if ('0' <= b && b <= '7' && digits++ < 6) {\n storedSum = storedSum * 8 + b - '0';\n } else if (digits > 0) {\n digits = 6;\n }\n b = ' ';\n }\n unsignedSum += 0xff & b;\n signedSum += b;\n }\n return storedSum == unsignedSum || storedSum == signedSum;\n }\n"}, "reference": " public static boolean verifyCheckSum(byte[] header) {\n long storedSum = parseOctal(header, CHKSUM_OFFSET, CHKSUMLEN);\n long unsignedSum = 0;\n long signedSum = 0;\n int digits = 0;\n for (int i = 0; i < header.length; i++) {\n byte b = header[i];\n if (CHKSUM_OFFSET <= i && i < CHKSUM_OFFSET + CHKSUMLEN) {\n b = ' ';\n }\n unsignedSum += 0xff & b;\n signedSum += b;\n }\n return storedSum == unsignedSum || storedSum == signedSum;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-35"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-35"}} {"sample_uid": "defects4j_function_repair::JacksonCore-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonToken nextToken() throws IOException\n {\n if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {\n if (_currToken.isStructEnd()) {\n if (_headContext.isStartHandled()) {\n return (_currToken = null);\n }\n } else if (_currToken.isScalarValue()) {\n if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {\n return (_currToken = null);\n }\n }\n }\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n _currToken = t;\n return t;\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonToken nextToken() throws IOException\n {\n if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {\n if (_currToken.isStructEnd()) {\n if (_headContext.isStartHandled()) {\n return (_currToken = null);\n }\n } else if (_currToken.isScalarValue()) {\n if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {\n return (_currToken = null);\n }\n }\n }\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n _currToken = t;\n return t;\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n"}, "reference": " public JsonToken nextToken() throws IOException\n {\n if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {\n if (!_includePath) {\n if (_currToken.isStructEnd()) {\n if (_headContext.isStartHandled()) {\n return (_currToken = null);\n }\n } else if (_currToken.isScalarValue()) {\n if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {\n return (_currToken = null);\n }\n }\n }\n }\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n _currToken = t;\n return t;\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-21"}} {"sample_uid": "defects4j_function_repair::Lang-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Locale toLocale(final String str) {\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len < 2) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch0 = str.charAt(0);\n final char ch1 = str.charAt(1);\n if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str);\n }\n if (len < 5) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch3 = str.charAt(3);\n if (ch3 == '_') {\n return new Locale(str.substring(0, 2), \"\", str.substring(4));\n }\n final char ch4 = str.charAt(4);\n if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n }\n if (len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Locale toLocale(final String str) {\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len < 2) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch0 = str.charAt(0);\n final char ch1 = str.charAt(1);\n if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str);\n }\n if (len < 5) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch3 = str.charAt(3);\n if (ch3 == '_') {\n return new Locale(str.substring(0, 2), \"\", str.substring(4));\n }\n final char ch4 = str.charAt(4);\n if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n }\n if (len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n"}, "reference": " public static Locale toLocale(final String str) {\n if (str == null) {\n return null;\n }\n final int len = str.length();\n if (len < 2) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch0 = str.charAt(0);\n if (ch0 == '_') {\n if (len < 3) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch1 = str.charAt(1);\n final char ch2 = str.charAt(2);\n if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 3) {\n return new Locale(\"\", str.substring(1, 3));\n }\n if (len < 5) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(3) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(\"\", str.substring(1, 3), str.substring(4));\n } else {\n final char ch1 = str.charAt(1);\n if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str);\n }\n if (len < 5) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n final char ch3 = str.charAt(3);\n if (ch3 == '_') {\n return new Locale(str.substring(0, 2), \"\", str.substring(4));\n }\n final char ch4 = str.charAt(4);\n if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n }\n if (len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-5"}} {"sample_uid": "defects4j_function_repair::Codec-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String newStringIso8859_1(final byte[] bytes) {\n return new String(bytes, Charsets.ISO_8859_1);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String newStringIso8859_1(final byte[] bytes) {\n return new String(bytes, Charsets.ISO_8859_1);\n }\n"}, "reference": " public static String newStringIso8859_1(final byte[] bytes) {\n return newString(bytes, Charsets.ISO_8859_1);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-17"}} {"sample_uid": "defects4j_function_repair::Compress-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public TarArchiveEntry getNextTarEntry() throws IOException {\n if (hasHitEOF) {\n return null;\n }\n if (currEntry != null) {\n long numToSkip = entrySize - entryOffset;\n while (numToSkip > 0) {\n long skipped = skip(numToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip current tar entry\");\n }\n numToSkip -= skipped;\n }\n readBuf = null;\n }\n byte[] headerBuf = getRecord();\n if (hasHitEOF) {\n currEntry = null;\n return null;\n }\n currEntry = new TarArchiveEntry(headerBuf);\n entryOffset = 0;\n entrySize = currEntry.getSize();\n if (currEntry.isGNULongNameEntry()) {\n StringBuffer longName = new StringBuffer();\n byte[] buf = new byte[SMALL_BUFFER_SIZE];\n int length = 0;\n while ((length = read(buf)) >= 0) {\n longName.append(new String(buf, 0, length));\n }\n getNextEntry();\n if (currEntry == null) {\n return null;\n }\n if (longName.length() > 0\n && longName.charAt(longName.length() - 1) == 0) {\n longName.deleteCharAt(longName.length() - 1);\n }\n currEntry.setName(longName.toString());\n }\n if (currEntry.isPaxHeader()){ \n paxHeaders();\n }\n if (currEntry.isGNUSparse()){ \n readGNUSparse();\n }\n entrySize = currEntry.getSize();\n return currEntry;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public TarArchiveEntry getNextTarEntry() throws IOException {\n if (hasHitEOF) {\n return null;\n }\n if (currEntry != null) {\n long numToSkip = entrySize - entryOffset;\n while (numToSkip > 0) {\n long skipped = skip(numToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip current tar entry\");\n }\n numToSkip -= skipped;\n }\n readBuf = null;\n }\n byte[] headerBuf = getRecord();\n if (hasHitEOF) {\n currEntry = null;\n return null;\n }\n currEntry = new TarArchiveEntry(headerBuf);\n entryOffset = 0;\n entrySize = currEntry.getSize();\n if (currEntry.isGNULongNameEntry()) {\n StringBuffer longName = new StringBuffer();\n byte[] buf = new byte[SMALL_BUFFER_SIZE];\n int length = 0;\n while ((length = read(buf)) >= 0) {\n longName.append(new String(buf, 0, length));\n }\n getNextEntry();\n if (currEntry == null) {\n return null;\n }\n if (longName.length() > 0\n && longName.charAt(longName.length() - 1) == 0) {\n longName.deleteCharAt(longName.length() - 1);\n }\n currEntry.setName(longName.toString());\n }\n if (currEntry.isPaxHeader()){ \n paxHeaders();\n }\n if (currEntry.isGNUSparse()){ \n readGNUSparse();\n }\n entrySize = currEntry.getSize();\n return currEntry;\n }\n"}, "reference": " public TarArchiveEntry getNextTarEntry() throws IOException {\n if (hasHitEOF) {\n return null;\n }\n if (currEntry != null) {\n long numToSkip = entrySize - entryOffset;\n while (numToSkip > 0) {\n long skipped = skip(numToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip current tar entry\");\n }\n numToSkip -= skipped;\n }\n readBuf = null;\n }\n byte[] headerBuf = getRecord();\n if (hasHitEOF) {\n currEntry = null;\n return null;\n }\n try {\n currEntry = new TarArchiveEntry(headerBuf);\n } catch (IllegalArgumentException e) {\n IOException ioe = new IOException(\"Error detected parsing the header\");\n ioe.initCause(e);\n throw ioe;\n }\n entryOffset = 0;\n entrySize = currEntry.getSize();\n if (currEntry.isGNULongNameEntry()) {\n StringBuffer longName = new StringBuffer();\n byte[] buf = new byte[SMALL_BUFFER_SIZE];\n int length = 0;\n while ((length = read(buf)) >= 0) {\n longName.append(new String(buf, 0, length));\n }\n getNextEntry();\n if (currEntry == null) {\n return null;\n }\n if (longName.length() > 0\n && longName.charAt(longName.length() - 1) == 0) {\n longName.deleteCharAt(longName.length() - 1);\n }\n currEntry.setName(longName.toString());\n }\n if (currEntry.isPaxHeader()){ \n paxHeaders();\n }\n if (currEntry.isGNUSparse()){ \n readGNUSparse();\n }\n entrySize = currEntry.getSize();\n return currEntry;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-12"}} {"sample_uid": "defects4j_function_repair::Lang-31", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n\tpublic static boolean containsAny(CharSequence cs, char[] searchChars) {\n\t\tif (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {\n\t\t\treturn false;\n\t\t}\n\t\tint csLength = cs.length();\n\t\tint searchLength = searchChars.length;\n\t\tfor (int i = 0; i < csLength; i++) {\n\t\t\tchar ch = cs.charAt(i);\n\t\t\tfor (int j = 0; j < searchLength; j++) {\n\t\t\t\tif (searchChars[j] == ch) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": "\tpublic static boolean containsAny(CharSequence cs, char[] searchChars) {\n\t\tif (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {\n\t\t\treturn false;\n\t\t}\n\t\tint csLength = cs.length();\n\t\tint searchLength = searchChars.length;\n\t\tfor (int i = 0; i < csLength; i++) {\n\t\t\tchar ch = cs.charAt(i);\n\t\t\tfor (int j = 0; j < searchLength; j++) {\n\t\t\t\tif (searchChars[j] == ch) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n"}, "reference": "\tpublic static boolean containsAny(CharSequence cs, char[] searchChars) {\n\t\tif (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {\n\t\t\treturn false;\n\t\t}\n\t\tint csLength = cs.length();\n\t\tint searchLength = searchChars.length;\n\t\tint csLastIndex = csLength - 1;\n\t\tint searchLastIndex = searchLength - 1;\n\t\tfor (int i = 0; i < csLength; i++) {\n\t\t\tchar ch = cs.charAt(i);\n\t\t\tfor (int j = 0; j < searchLength; j++) {\n\t\t\t\tif (searchChars[j] == ch) {\n\t\t\t\t\tif (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) {\n\t\t\t\t\t\tif (searchChars[j + 1] == cs.charAt(i + 1)) {\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n", "tests": {}, "repo_meta": {"bug_id": "Lang-31"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-31"}} {"sample_uid": "defects4j_function_repair::Closure-116", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n"}, "reference": " private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n boolean hasSideEffects = false; \n if (block.hasChildren()) {\n Preconditions.checkState(block.hasOneChild());\n Node stmt = block.getFirstChild();\n if (stmt.isReturn()) {\n hasSideEffects = NodeUtil.mayHaveSideEffects(\n stmt.getFirstChild(), compiler);\n }\n }\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) {\n return CanInlineResult.NO;\n }\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-116"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-116"}} {"sample_uid": "defects4j_function_repair::Mockito-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Object returnValueFor(Class type) {\n if (Primitives.isPrimitiveOrWrapper(type)) {\n return Primitives.defaultValueForPrimitiveOrWrapper(type);\n } else if (type == Collection.class) {\n return new LinkedList();\n } else if (type == Set.class) {\n return new HashSet();\n } else if (type == HashSet.class) {\n return new HashSet();\n } else if (type == SortedSet.class) {\n return new TreeSet();\n } else if (type == TreeSet.class) {\n return new TreeSet();\n } else if (type == LinkedHashSet.class) {\n return new LinkedHashSet();\n } else if (type == List.class) {\n return new LinkedList();\n } else if (type == LinkedList.class) {\n return new LinkedList();\n } else if (type == ArrayList.class) {\n return new ArrayList();\n } else if (type == Map.class) {\n return new HashMap();\n } else if (type == HashMap.class) {\n return new HashMap();\n } else if (type == SortedMap.class) {\n return new TreeMap();\n } else if (type == TreeMap.class) {\n return new TreeMap();\n } else if (type == LinkedHashMap.class) {\n return new LinkedHashMap();\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Object returnValueFor(Class type) {\n if (Primitives.isPrimitiveOrWrapper(type)) {\n return Primitives.defaultValueForPrimitiveOrWrapper(type);\n } else if (type == Collection.class) {\n return new LinkedList();\n } else if (type == Set.class) {\n return new HashSet();\n } else if (type == HashSet.class) {\n return new HashSet();\n } else if (type == SortedSet.class) {\n return new TreeSet();\n } else if (type == TreeSet.class) {\n return new TreeSet();\n } else if (type == LinkedHashSet.class) {\n return new LinkedHashSet();\n } else if (type == List.class) {\n return new LinkedList();\n } else if (type == LinkedList.class) {\n return new LinkedList();\n } else if (type == ArrayList.class) {\n return new ArrayList();\n } else if (type == Map.class) {\n return new HashMap();\n } else if (type == HashMap.class) {\n return new HashMap();\n } else if (type == SortedMap.class) {\n return new TreeMap();\n } else if (type == TreeMap.class) {\n return new TreeMap();\n } else if (type == LinkedHashMap.class) {\n return new LinkedHashMap();\n }\n return null;\n }\n"}, "reference": " Object returnValueFor(Class type) {\n if (Primitives.isPrimitiveOrWrapper(type)) {\n return Primitives.defaultValueForPrimitiveOrWrapper(type);\n } else if (type == Iterable.class) {\n return new ArrayList(0);\n } else if (type == Collection.class) {\n return new LinkedList();\n } else if (type == Set.class) {\n return new HashSet();\n } else if (type == HashSet.class) {\n return new HashSet();\n } else if (type == SortedSet.class) {\n return new TreeSet();\n } else if (type == TreeSet.class) {\n return new TreeSet();\n } else if (type == LinkedHashSet.class) {\n return new LinkedHashSet();\n } else if (type == List.class) {\n return new LinkedList();\n } else if (type == LinkedList.class) {\n return new LinkedList();\n } else if (type == ArrayList.class) {\n return new ArrayList();\n } else if (type == Map.class) {\n return new HashMap();\n } else if (type == HashMap.class) {\n return new HashMap();\n } else if (type == SortedMap.class) {\n return new TreeMap();\n } else if (type == TreeMap.class) {\n return new TreeMap();\n } else if (type == LinkedHashMap.class) {\n return new LinkedHashMap();\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-18"}} {"sample_uid": "defects4j_function_repair::Time-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n int defaultYear = chrono.year().get(instantLocal);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, defaultYear);\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n int defaultYear = chrono.year().get(instantLocal);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, defaultYear);\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n"}, "reference": " public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis);\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, defaultYear);\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-7"}} {"sample_uid": "defects4j_function_repair::Closure-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n hoistExterns(externsRoot);\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement() && options.closurePass) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n hoistNoCompileFiles();\n if (staleInputs) {\n repartitionInputs();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n hoistExterns(externsRoot);\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement() && options.closurePass) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n hoistNoCompileFiles();\n if (staleInputs) {\n repartitionInputs();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n"}, "reference": " Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n hoistExterns(externsRoot);\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement()) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n hoistNoCompileFiles();\n if (staleInputs) {\n repartitionInputs();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-18"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean useForType(JavaType t)\n {\n switch (_appliesFor) {\n case NON_CONCRETE_AND_ARRAYS:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n case OBJECT_AND_NON_CONCRETE:\n return (t.getRawClass() == Object.class)\n || (!t.isConcrete()\n || TreeNode.class.isAssignableFrom(t.getRawClass()));\n case NON_FINAL:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());\n default:\n return (t.getRawClass() == Object.class);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean useForType(JavaType t)\n {\n switch (_appliesFor) {\n case NON_CONCRETE_AND_ARRAYS:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n case OBJECT_AND_NON_CONCRETE:\n return (t.getRawClass() == Object.class)\n || (!t.isConcrete()\n || TreeNode.class.isAssignableFrom(t.getRawClass()));\n case NON_FINAL:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());\n default:\n return (t.getRawClass() == Object.class);\n }\n }\n"}, "reference": " public boolean useForType(JavaType t)\n {\n switch (_appliesFor) {\n case NON_CONCRETE_AND_ARRAYS:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n case OBJECT_AND_NON_CONCRETE:\n return (t.getRawClass() == Object.class)\n || (!t.isConcrete()\n && !TreeNode.class.isAssignableFrom(t.getRawClass()));\n case NON_FINAL:\n while (t.isArrayType()) {\n t = t.getContentType();\n }\n return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());\n default:\n return (t.getRawClass() == Object.class);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-17"}} {"sample_uid": "defects4j_function_repair::Math-52", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {\n double u1u1 = u1.getNormSq();\n double u2u2 = u2.getNormSq();\n double v1v1 = v1.getNormSq();\n double v2v2 = v2.getNormSq();\n if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {\n throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);\n }\n v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1);\n double u1u2 = u1.dotProduct(u2);\n double v1v2 = v1.dotProduct(v2);\n double coeffU = u1u2 / u1u1;\n double coeffV = v1v2 / u1u1;\n double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV));\n double alpha = coeffU - beta * coeffV;\n v2 = new Vector3D(alpha, v1, beta, v2);\n Vector3D uRef = u1;\n Vector3D vRef = v1;\n Vector3D v1Su1 = v1.subtract(u1);\n Vector3D v2Su2 = v2.subtract(u2);\n Vector3D k = v1Su1.crossProduct(v2Su2);\n Vector3D u3 = u1.crossProduct(u2);\n double c = k.dotProduct(u3);\n if (c == 0) {\n Vector3D v3 = Vector3D.crossProduct(v1, v2);\n Vector3D v3Su3 = v3.subtract(u3);\n k = v1Su1.crossProduct(v3Su3);\n Vector3D u2Prime = u1.crossProduct(u3);\n c = k.dotProduct(u2Prime);\n if (c == 0) {\n k = v2Su2.crossProduct(v3Su3);;\n c = k.dotProduct(u2.crossProduct(u3));;\n if (c == 0) {\n q0 = 1.0;\n q1 = 0.0;\n q2 = 0.0;\n q3 = 0.0;\n return;\n }\n uRef = u2;\n vRef = v2;\n }\n }\n c = FastMath.sqrt(c);\n double inv = 1.0 / (c + c);\n q1 = inv * k.getX();\n q2 = inv * k.getY();\n q3 = inv * k.getZ();\n k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2,\n uRef.getZ() * q1 - uRef.getX() * q3,\n uRef.getX() * q2 - uRef.getY() * q1);\n q0 = vRef.dotProduct(k) / (2 * k.getNormSq());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {\n double u1u1 = u1.getNormSq();\n double u2u2 = u2.getNormSq();\n double v1v1 = v1.getNormSq();\n double v2v2 = v2.getNormSq();\n if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {\n throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);\n }\n v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1);\n double u1u2 = u1.dotProduct(u2);\n double v1v2 = v1.dotProduct(v2);\n double coeffU = u1u2 / u1u1;\n double coeffV = v1v2 / u1u1;\n double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV));\n double alpha = coeffU - beta * coeffV;\n v2 = new Vector3D(alpha, v1, beta, v2);\n Vector3D uRef = u1;\n Vector3D vRef = v1;\n Vector3D v1Su1 = v1.subtract(u1);\n Vector3D v2Su2 = v2.subtract(u2);\n Vector3D k = v1Su1.crossProduct(v2Su2);\n Vector3D u3 = u1.crossProduct(u2);\n double c = k.dotProduct(u3);\n if (c == 0) {\n Vector3D v3 = Vector3D.crossProduct(v1, v2);\n Vector3D v3Su3 = v3.subtract(u3);\n k = v1Su1.crossProduct(v3Su3);\n Vector3D u2Prime = u1.crossProduct(u3);\n c = k.dotProduct(u2Prime);\n if (c == 0) {\n k = v2Su2.crossProduct(v3Su3);;\n c = k.dotProduct(u2.crossProduct(u3));;\n if (c == 0) {\n q0 = 1.0;\n q1 = 0.0;\n q2 = 0.0;\n q3 = 0.0;\n return;\n }\n uRef = u2;\n vRef = v2;\n }\n }\n c = FastMath.sqrt(c);\n double inv = 1.0 / (c + c);\n q1 = inv * k.getX();\n q2 = inv * k.getY();\n q3 = inv * k.getZ();\n k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2,\n uRef.getZ() * q1 - uRef.getX() * q3,\n uRef.getX() * q2 - uRef.getY() * q1);\n q0 = vRef.dotProduct(k) / (2 * k.getNormSq());\n }\n"}, "reference": " public Rotation(Vector3D u1, Vector3D u2, Vector3D v1, Vector3D v2) {\n double u1u1 = u1.getNormSq();\n double u2u2 = u2.getNormSq();\n double v1v1 = v1.getNormSq();\n double v2v2 = v2.getNormSq();\n if ((u1u1 == 0) || (u2u2 == 0) || (v1v1 == 0) || (v2v2 == 0)) {\n throw MathRuntimeException.createIllegalArgumentException(LocalizedFormats.ZERO_NORM_FOR_ROTATION_DEFINING_VECTOR);\n }\n v1 = new Vector3D(FastMath.sqrt(u1u1 / v1v1), v1);\n double u1u2 = u1.dotProduct(u2);\n double v1v2 = v1.dotProduct(v2);\n double coeffU = u1u2 / u1u1;\n double coeffV = v1v2 / u1u1;\n double beta = FastMath.sqrt((u2u2 - u1u2 * coeffU) / (v2v2 - v1v2 * coeffV));\n double alpha = coeffU - beta * coeffV;\n v2 = new Vector3D(alpha, v1, beta, v2);\n Vector3D uRef = u1;\n Vector3D vRef = v1;\n Vector3D v1Su1 = v1.subtract(u1);\n Vector3D v2Su2 = v2.subtract(u2);\n Vector3D k = v1Su1.crossProduct(v2Su2);\n Vector3D u3 = u1.crossProduct(u2);\n double c = k.dotProduct(u3);\n final double inPlaneThreshold = 0.001;\n if (c <= inPlaneThreshold * k.getNorm() * u3.getNorm()) {\n Vector3D v3 = Vector3D.crossProduct(v1, v2);\n Vector3D v3Su3 = v3.subtract(u3);\n k = v1Su1.crossProduct(v3Su3);\n Vector3D u2Prime = u1.crossProduct(u3);\n c = k.dotProduct(u2Prime);\n if (c <= inPlaneThreshold * k.getNorm() * u2Prime.getNorm()) {\n k = v2Su2.crossProduct(v3Su3);;\n c = k.dotProduct(u2.crossProduct(u3));;\n if (c <= 0) {\n q0 = 1.0;\n q1 = 0.0;\n q2 = 0.0;\n q3 = 0.0;\n return;\n }\n uRef = u2;\n vRef = v2;\n }\n }\n c = FastMath.sqrt(c);\n double inv = 1.0 / (c + c);\n q1 = inv * k.getX();\n q2 = inv * k.getY();\n q3 = inv * k.getZ();\n k = new Vector3D(uRef.getY() * q3 - uRef.getZ() * q2,\n uRef.getZ() * q1 - uRef.getX() * q3,\n uRef.getX() * q2 - uRef.getY() * q1);\n q0 = vRef.dotProduct(k) / (2 * k.getNormSq());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-52"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-52"}} {"sample_uid": "defects4j_function_repair::Chart-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Week(Date time, TimeZone zone) {\n this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Week(Date time, TimeZone zone) {\n this(time, RegularTimePeriod.DEFAULT_TIME_ZONE, Locale.getDefault());\n }\n"}, "reference": " public Week(Date time, TimeZone zone) {\n this(time, zone, Locale.getDefault());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-8"}} {"sample_uid": "defects4j_function_repair::Chart-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean equal(GeneralPath p1, GeneralPath p2) {\n if (p1 == null) {\n return (p2 == null);\n }\n if (p2 == null) {\n return false;\n }\n if (p1.getWindingRule() != p2.getWindingRule()) {\n return false;\n }\n PathIterator iterator1 = p1.getPathIterator(null);\n PathIterator iterator2 = p1.getPathIterator(null);\n double[] d1 = new double[6];\n double[] d2 = new double[6];\n boolean done = iterator1.isDone() && iterator2.isDone();\n while (!done) {\n if (iterator1.isDone() != iterator2.isDone()) {\n return false;\n }\n int seg1 = iterator1.currentSegment(d1);\n int seg2 = iterator2.currentSegment(d2);\n if (seg1 != seg2) {\n return false;\n }\n if (!Arrays.equals(d1, d2)) {\n return false;\n }\n iterator1.next();\n iterator2.next();\n done = iterator1.isDone() && iterator2.isDone();\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean equal(GeneralPath p1, GeneralPath p2) {\n if (p1 == null) {\n return (p2 == null);\n }\n if (p2 == null) {\n return false;\n }\n if (p1.getWindingRule() != p2.getWindingRule()) {\n return false;\n }\n PathIterator iterator1 = p1.getPathIterator(null);\n PathIterator iterator2 = p1.getPathIterator(null);\n double[] d1 = new double[6];\n double[] d2 = new double[6];\n boolean done = iterator1.isDone() && iterator2.isDone();\n while (!done) {\n if (iterator1.isDone() != iterator2.isDone()) {\n return false;\n }\n int seg1 = iterator1.currentSegment(d1);\n int seg2 = iterator2.currentSegment(d2);\n if (seg1 != seg2) {\n return false;\n }\n if (!Arrays.equals(d1, d2)) {\n return false;\n }\n iterator1.next();\n iterator2.next();\n done = iterator1.isDone() && iterator2.isDone();\n }\n return true;\n }\n"}, "reference": " public static boolean equal(GeneralPath p1, GeneralPath p2) {\n if (p1 == null) {\n return (p2 == null);\n }\n if (p2 == null) {\n return false;\n }\n if (p1.getWindingRule() != p2.getWindingRule()) {\n return false;\n }\n PathIterator iterator1 = p1.getPathIterator(null);\n PathIterator iterator2 = p2.getPathIterator(null);\n double[] d1 = new double[6];\n double[] d2 = new double[6];\n boolean done = iterator1.isDone() && iterator2.isDone();\n while (!done) {\n if (iterator1.isDone() != iterator2.isDone()) {\n return false;\n }\n int seg1 = iterator1.currentSegment(d1);\n int seg2 = iterator2.currentSegment(d2);\n if (seg1 != seg2) {\n return false;\n }\n if (!Arrays.equals(d1, d2)) {\n return false;\n }\n iterator1.next();\n iterator2.next();\n done = iterator1.isDone() && iterator2.isDone();\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-11"}} {"sample_uid": "defects4j_function_repair::Closure-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean mayBeString(Node n, boolean recurse) {\n if (recurse) {\n return allResultsMatch(n, MAY_BE_STRING_PREDICATE);\n } else {\n return mayBeStringHelper(n);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean mayBeString(Node n, boolean recurse) {\n if (recurse) {\n return allResultsMatch(n, MAY_BE_STRING_PREDICATE);\n } else {\n return mayBeStringHelper(n);\n }\n }\n"}, "reference": " static boolean mayBeString(Node n, boolean recurse) {\n if (recurse) {\n return anyResultsMatch(n, MAY_BE_STRING_PREDICATE);\n } else {\n return mayBeStringHelper(n);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-10"}} {"sample_uid": "defects4j_function_repair::Jsoup-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public DocumentType(String name, String publicId, String systemId, String baseUri) {\n super(baseUri);\n Validate.notEmpty(name);\n attr(\"name\", name);\n attr(\"publicId\", publicId);\n attr(\"systemId\", systemId);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public DocumentType(String name, String publicId, String systemId, String baseUri) {\n super(baseUri);\n Validate.notEmpty(name);\n attr(\"name\", name);\n attr(\"publicId\", publicId);\n attr(\"systemId\", systemId);\n }\n"}, "reference": " public DocumentType(String name, String publicId, String systemId, String baseUri) {\n super(baseUri);\n attr(\"name\", name);\n attr(\"publicId\", publicId);\n attr(\"systemId\", systemId);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-40"}} {"sample_uid": "defects4j_function_repair::Time-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public long computeMillis(boolean resetFields, String text) {\n SavedField[] savedFields = iSavedFields;\n int count = iSavedFieldsCount;\n if (iSavedFieldsShared) {\n iSavedFields = savedFields = (SavedField[])iSavedFields.clone();\n iSavedFieldsShared = false;\n }\n sort(savedFields, count);\n if (count > 0) {\n DurationField months = DurationFieldType.months().getField(iChrono);\n DurationField days = DurationFieldType.days().getField(iChrono);\n DurationField first = savedFields[0].iField.getDurationField();\n if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {\n saveField(DateTimeFieldType.year(), iDefaultYear);\n return computeMillis(resetFields, text);\n }\n }\n long millis = iMillis;\n try {\n for (int i = 0; i < count; i++) {\n millis = savedFields[i].set(millis, resetFields);\n }\n } catch (IllegalFieldValueException e) {\n if (text != null) {\n e.prependMessage(\"Cannot parse \\\"\" + text + '\"');\n }\n throw e;\n }\n if (iZone == null) {\n millis -= iOffset;\n } else {\n int offset = iZone.getOffsetFromLocal(millis);\n millis -= offset;\n if (offset != iZone.getOffset(millis)) {\n String message =\n \"Illegal instant due to time zone offset transition (\" + iZone + ')';\n if (text != null) {\n message = \"Cannot parse \\\"\" + text + \"\\\": \" + message;\n }\n throw new IllegalArgumentException(message);\n }\n }\n return millis;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public long computeMillis(boolean resetFields, String text) {\n SavedField[] savedFields = iSavedFields;\n int count = iSavedFieldsCount;\n if (iSavedFieldsShared) {\n iSavedFields = savedFields = (SavedField[])iSavedFields.clone();\n iSavedFieldsShared = false;\n }\n sort(savedFields, count);\n if (count > 0) {\n DurationField months = DurationFieldType.months().getField(iChrono);\n DurationField days = DurationFieldType.days().getField(iChrono);\n DurationField first = savedFields[0].iField.getDurationField();\n if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {\n saveField(DateTimeFieldType.year(), iDefaultYear);\n return computeMillis(resetFields, text);\n }\n }\n long millis = iMillis;\n try {\n for (int i = 0; i < count; i++) {\n millis = savedFields[i].set(millis, resetFields);\n }\n } catch (IllegalFieldValueException e) {\n if (text != null) {\n e.prependMessage(\"Cannot parse \\\"\" + text + '\"');\n }\n throw e;\n }\n if (iZone == null) {\n millis -= iOffset;\n } else {\n int offset = iZone.getOffsetFromLocal(millis);\n millis -= offset;\n if (offset != iZone.getOffset(millis)) {\n String message =\n \"Illegal instant due to time zone offset transition (\" + iZone + ')';\n if (text != null) {\n message = \"Cannot parse \\\"\" + text + \"\\\": \" + message;\n }\n throw new IllegalArgumentException(message);\n }\n }\n return millis;\n }\n"}, "reference": " public long computeMillis(boolean resetFields, String text) {\n SavedField[] savedFields = iSavedFields;\n int count = iSavedFieldsCount;\n if (iSavedFieldsShared) {\n iSavedFields = savedFields = (SavedField[])iSavedFields.clone();\n iSavedFieldsShared = false;\n }\n sort(savedFields, count);\n if (count > 0) {\n DurationField months = DurationFieldType.months().getField(iChrono);\n DurationField days = DurationFieldType.days().getField(iChrono);\n DurationField first = savedFields[0].iField.getDurationField();\n if (compareReverse(first, months) >= 0 && compareReverse(first, days) <= 0) {\n saveField(DateTimeFieldType.year(), iDefaultYear);\n return computeMillis(resetFields, text);\n }\n }\n long millis = iMillis;\n try {\n for (int i = 0; i < count; i++) {\n millis = savedFields[i].set(millis, resetFields);\n }\n if (resetFields) {\n for (int i = 0; i < count; i++) {\n millis = savedFields[i].set(millis, i == (count - 1));\n }\n }\n } catch (IllegalFieldValueException e) {\n if (text != null) {\n e.prependMessage(\"Cannot parse \\\"\" + text + '\"');\n }\n throw e;\n }\n if (iZone == null) {\n millis -= iOffset;\n } else {\n int offset = iZone.getOffsetFromLocal(millis);\n millis -= offset;\n if (offset != iZone.getOffset(millis)) {\n String message =\n \"Illegal instant due to time zone offset transition (\" + iZone + ')';\n if (text != null) {\n message = \"Cannot parse \\\"\" + text + \"\\\": \" + message;\n }\n throw new IllegalArgumentException(message);\n }\n }\n return millis;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-24"}} {"sample_uid": "defects4j_function_repair::Cli-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Option create(String opt) throws IllegalArgumentException\n {\n Option option = new Option(opt, description);\n option.setLongOpt(longopt);\n option.setRequired(required);\n option.setOptionalArg(optionalArg);\n option.setArgs(numberOfArgs);\n option.setType(type);\n option.setValueSeparator(valuesep);\n option.setArgName(argName);\n OptionBuilder.reset();\n return option;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Option create(String opt) throws IllegalArgumentException\n {\n Option option = new Option(opt, description);\n option.setLongOpt(longopt);\n option.setRequired(required);\n option.setOptionalArg(optionalArg);\n option.setArgs(numberOfArgs);\n option.setType(type);\n option.setValueSeparator(valuesep);\n option.setArgName(argName);\n OptionBuilder.reset();\n return option;\n }\n"}, "reference": " public static Option create(String opt) throws IllegalArgumentException\n {\n Option option = null;\n try {\n option = new Option(opt, description);\n option.setLongOpt(longopt);\n option.setRequired(required);\n option.setOptionalArg(optionalArg);\n option.setArgs(numberOfArgs);\n option.setType(type);\n option.setValueSeparator(valuesep);\n option.setArgName(argName);\n } finally {\n OptionBuilder.reset();\n }\n return option;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-26"}} {"sample_uid": "defects4j_function_repair::Math-82", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Integer getPivotRow(final int col, final SimplexTableau tableau) {\n double minRatio = Double.MAX_VALUE;\n Integer minRatioPos = null;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {\n final double ratio = rhs / entry;\n if (ratio < minRatio) {\n minRatio = ratio;\n minRatioPos = i; \n }\n }\n }\n return minRatioPos;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Integer getPivotRow(final int col, final SimplexTableau tableau) {\n double minRatio = Double.MAX_VALUE;\n Integer minRatioPos = null;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (MathUtils.compareTo(entry, 0, epsilon) >= 0) {\n final double ratio = rhs / entry;\n if (ratio < minRatio) {\n minRatio = ratio;\n minRatioPos = i; \n }\n }\n }\n return minRatioPos;\n }\n"}, "reference": " private Integer getPivotRow(final int col, final SimplexTableau tableau) {\n double minRatio = Double.MAX_VALUE;\n Integer minRatioPos = null;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (MathUtils.compareTo(entry, 0, epsilon) > 0) {\n final double ratio = rhs / entry;\n if (ratio < minRatio) {\n minRatio = ratio;\n minRatioPos = i; \n }\n }\n }\n return minRatioPos;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-82"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-82"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-82", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void addBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n final boolean isConcrete = !beanDesc.getType().isAbstract();\n final SettableBeanProperty[] creatorProps = isConcrete\n ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())\n : null;\n final boolean hasCreatorProps = (creatorProps != null);\n JsonIgnoreProperties.Value ignorals = ctxt.getConfig()\n .getDefaultPropertyIgnorals(beanDesc.getBeanClass(),\n beanDesc.getClassInfo());\n Set ignored;\n if (ignorals != null) {\n boolean ignoreAny = ignorals.getIgnoreUnknown();\n builder.setIgnoreUnknownProperties(ignoreAny);\n ignored = ignorals.getIgnored();\n for (String propName : ignored) {\n builder.addIgnorable(propName);\n }\n } else {\n ignored = Collections.emptySet();\n }\n AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();\n AnnotatedMember anySetterField = null;\n if (anySetterMethod != null) {\n builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));\n }\n else {\n \tanySetterField = beanDesc.findAnySetterField();\n \tif(anySetterField != null) {\n \t\tbuilder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));\n \t}\n }\n if (anySetterMethod == null && anySetterField == null) {\n Collection ignored2 = beanDesc.getIgnoredPropertyNames();\n if (ignored2 != null) {\n for (String propName : ignored2) {\n builder.addIgnorable(propName);\n }\n }\n }\n final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)\n && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);\n List propDefs = filterBeanProps(ctxt,\n beanDesc, builder, beanDesc.findProperties(), ignored);\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);\n }\n }\n for (BeanPropertyDefinition propDef : propDefs) {\n SettableBeanProperty prop = null;\n if (propDef.hasSetter()) {\n JavaType propertyType = propDef.getSetter().getParameterType(0);\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (propDef.hasField()) {\n JavaType propertyType = propDef.getField().getType();\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (useGettersAsSetters && propDef.hasGetter()) {\n AnnotatedMethod getter = propDef.getGetter();\n Class rawPropertyType = getter.getRawType();\n if (Collection.class.isAssignableFrom(rawPropertyType)\n || Map.class.isAssignableFrom(rawPropertyType)) {\n prop = constructSetterlessProperty(ctxt, beanDesc, propDef);\n }\n }\n if (hasCreatorProps && propDef.hasConstructorParameter()) {\n final String name = propDef.getName();\n CreatorProperty cprop = null;\n if (creatorProps != null) {\n for (SettableBeanProperty cp : creatorProps) {\n if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {\n cprop = (CreatorProperty) cp;\n break;\n }\n }\n }\n if (cprop == null) {\n List n = new ArrayList<>();\n for (SettableBeanProperty cp : creatorProps) {\n n.add(cp.getName());\n }\n ctxt.reportBadPropertyDefinition(beanDesc, propDef,\n \"Could not find creator property with name '%s' (known Creator properties: %s)\",\n name, n);\n continue;\n }\n if (prop != null) {\n cprop.setFallbackSetter(prop);\n }\n prop = cprop;\n builder.addCreatorProperty(cprop);\n continue;\n }\n if (prop != null) {\n Class[] views = propDef.findViews();\n if (views == null) {\n if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {\n views = NO_VIEWS;\n }\n }\n prop.setViews(views);\n builder.addProperty(prop);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void addBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n final boolean isConcrete = !beanDesc.getType().isAbstract();\n final SettableBeanProperty[] creatorProps = isConcrete\n ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())\n : null;\n final boolean hasCreatorProps = (creatorProps != null);\n JsonIgnoreProperties.Value ignorals = ctxt.getConfig()\n .getDefaultPropertyIgnorals(beanDesc.getBeanClass(),\n beanDesc.getClassInfo());\n Set ignored;\n if (ignorals != null) {\n boolean ignoreAny = ignorals.getIgnoreUnknown();\n builder.setIgnoreUnknownProperties(ignoreAny);\n ignored = ignorals.getIgnored();\n for (String propName : ignored) {\n builder.addIgnorable(propName);\n }\n } else {\n ignored = Collections.emptySet();\n }\n AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();\n AnnotatedMember anySetterField = null;\n if (anySetterMethod != null) {\n builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));\n }\n else {\n \tanySetterField = beanDesc.findAnySetterField();\n \tif(anySetterField != null) {\n \t\tbuilder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));\n \t}\n }\n if (anySetterMethod == null && anySetterField == null) {\n Collection ignored2 = beanDesc.getIgnoredPropertyNames();\n if (ignored2 != null) {\n for (String propName : ignored2) {\n builder.addIgnorable(propName);\n }\n }\n }\n final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)\n && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);\n List propDefs = filterBeanProps(ctxt,\n beanDesc, builder, beanDesc.findProperties(), ignored);\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);\n }\n }\n for (BeanPropertyDefinition propDef : propDefs) {\n SettableBeanProperty prop = null;\n if (propDef.hasSetter()) {\n JavaType propertyType = propDef.getSetter().getParameterType(0);\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (propDef.hasField()) {\n JavaType propertyType = propDef.getField().getType();\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (useGettersAsSetters && propDef.hasGetter()) {\n AnnotatedMethod getter = propDef.getGetter();\n Class rawPropertyType = getter.getRawType();\n if (Collection.class.isAssignableFrom(rawPropertyType)\n || Map.class.isAssignableFrom(rawPropertyType)) {\n prop = constructSetterlessProperty(ctxt, beanDesc, propDef);\n }\n }\n if (hasCreatorProps && propDef.hasConstructorParameter()) {\n final String name = propDef.getName();\n CreatorProperty cprop = null;\n if (creatorProps != null) {\n for (SettableBeanProperty cp : creatorProps) {\n if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {\n cprop = (CreatorProperty) cp;\n break;\n }\n }\n }\n if (cprop == null) {\n List n = new ArrayList<>();\n for (SettableBeanProperty cp : creatorProps) {\n n.add(cp.getName());\n }\n ctxt.reportBadPropertyDefinition(beanDesc, propDef,\n \"Could not find creator property with name '%s' (known Creator properties: %s)\",\n name, n);\n continue;\n }\n if (prop != null) {\n cprop.setFallbackSetter(prop);\n }\n prop = cprop;\n builder.addCreatorProperty(cprop);\n continue;\n }\n if (prop != null) {\n Class[] views = propDef.findViews();\n if (views == null) {\n if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {\n views = NO_VIEWS;\n }\n }\n prop.setViews(views);\n builder.addProperty(prop);\n }\n }\n }\n"}, "reference": " protected void addBeanProps(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanDeserializerBuilder builder)\n throws JsonMappingException\n {\n final boolean isConcrete = !beanDesc.getType().isAbstract();\n final SettableBeanProperty[] creatorProps = isConcrete\n ? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())\n : null;\n final boolean hasCreatorProps = (creatorProps != null);\n JsonIgnoreProperties.Value ignorals = ctxt.getConfig()\n .getDefaultPropertyIgnorals(beanDesc.getBeanClass(),\n beanDesc.getClassInfo());\n Set ignored;\n if (ignorals != null) {\n boolean ignoreAny = ignorals.getIgnoreUnknown();\n builder.setIgnoreUnknownProperties(ignoreAny);\n ignored = ignorals.findIgnoredForDeserialization();\n for (String propName : ignored) {\n builder.addIgnorable(propName);\n }\n } else {\n ignored = Collections.emptySet();\n }\n AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();\n AnnotatedMember anySetterField = null;\n if (anySetterMethod != null) {\n builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));\n }\n else {\n \tanySetterField = beanDesc.findAnySetterField();\n \tif(anySetterField != null) {\n \t\tbuilder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));\n \t}\n }\n if (anySetterMethod == null && anySetterField == null) {\n Collection ignored2 = beanDesc.getIgnoredPropertyNames();\n if (ignored2 != null) {\n for (String propName : ignored2) {\n builder.addIgnorable(propName);\n }\n }\n }\n final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)\n && ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);\n List propDefs = filterBeanProps(ctxt,\n beanDesc, builder, beanDesc.findProperties(), ignored);\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);\n }\n }\n for (BeanPropertyDefinition propDef : propDefs) {\n SettableBeanProperty prop = null;\n if (propDef.hasSetter()) {\n JavaType propertyType = propDef.getSetter().getParameterType(0);\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (propDef.hasField()) {\n JavaType propertyType = propDef.getField().getType();\n prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);\n } else if (useGettersAsSetters && propDef.hasGetter()) {\n AnnotatedMethod getter = propDef.getGetter();\n Class rawPropertyType = getter.getRawType();\n if (Collection.class.isAssignableFrom(rawPropertyType)\n || Map.class.isAssignableFrom(rawPropertyType)) {\n prop = constructSetterlessProperty(ctxt, beanDesc, propDef);\n }\n }\n if (hasCreatorProps && propDef.hasConstructorParameter()) {\n final String name = propDef.getName();\n CreatorProperty cprop = null;\n if (creatorProps != null) {\n for (SettableBeanProperty cp : creatorProps) {\n if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {\n cprop = (CreatorProperty) cp;\n break;\n }\n }\n }\n if (cprop == null) {\n List n = new ArrayList<>();\n for (SettableBeanProperty cp : creatorProps) {\n n.add(cp.getName());\n }\n ctxt.reportBadPropertyDefinition(beanDesc, propDef,\n \"Could not find creator property with name '%s' (known Creator properties: %s)\",\n name, n);\n continue;\n }\n if (prop != null) {\n cprop.setFallbackSetter(prop);\n }\n prop = cprop;\n builder.addCreatorProperty(cprop);\n continue;\n }\n if (prop != null) {\n Class[] views = propDef.findViews();\n if (views == null) {\n if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {\n views = NO_VIEWS;\n }\n }\n prop.setViews(views);\n builder.addProperty(prop);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-82"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-82"}} {"sample_uid": "defects4j_function_repair::Jsoup-35", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"script\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size() && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"script\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size() && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n"}, "reference": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"script\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size() && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-35"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-35"}} {"sample_uid": "defects4j_function_repair::Lang-48", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public EqualsBuilder append(Object lhs, Object rhs) {\n if (isEquals == false) {\n return this;\n }\n if (lhs == rhs) {\n return this;\n }\n if (lhs == null || rhs == null) {\n this.setEquals(false);\n return this;\n }\n Class lhsClass = lhs.getClass();\n if (!lhsClass.isArray()) {\n isEquals = lhs.equals(rhs);\n } else if (lhs.getClass() != rhs.getClass()) {\n this.setEquals(false);\n }\n else if (lhs instanceof long[]) {\n append((long[]) lhs, (long[]) rhs);\n } else if (lhs instanceof int[]) {\n append((int[]) lhs, (int[]) rhs);\n } else if (lhs instanceof short[]) {\n append((short[]) lhs, (short[]) rhs);\n } else if (lhs instanceof char[]) {\n append((char[]) lhs, (char[]) rhs);\n } else if (lhs instanceof byte[]) {\n append((byte[]) lhs, (byte[]) rhs);\n } else if (lhs instanceof double[]) {\n append((double[]) lhs, (double[]) rhs);\n } else if (lhs instanceof float[]) {\n append((float[]) lhs, (float[]) rhs);\n } else if (lhs instanceof boolean[]) {\n append((boolean[]) lhs, (boolean[]) rhs);\n } else {\n append((Object[]) lhs, (Object[]) rhs);\n }\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public EqualsBuilder append(Object lhs, Object rhs) {\n if (isEquals == false) {\n return this;\n }\n if (lhs == rhs) {\n return this;\n }\n if (lhs == null || rhs == null) {\n this.setEquals(false);\n return this;\n }\n Class lhsClass = lhs.getClass();\n if (!lhsClass.isArray()) {\n isEquals = lhs.equals(rhs);\n } else if (lhs.getClass() != rhs.getClass()) {\n this.setEquals(false);\n }\n else if (lhs instanceof long[]) {\n append((long[]) lhs, (long[]) rhs);\n } else if (lhs instanceof int[]) {\n append((int[]) lhs, (int[]) rhs);\n } else if (lhs instanceof short[]) {\n append((short[]) lhs, (short[]) rhs);\n } else if (lhs instanceof char[]) {\n append((char[]) lhs, (char[]) rhs);\n } else if (lhs instanceof byte[]) {\n append((byte[]) lhs, (byte[]) rhs);\n } else if (lhs instanceof double[]) {\n append((double[]) lhs, (double[]) rhs);\n } else if (lhs instanceof float[]) {\n append((float[]) lhs, (float[]) rhs);\n } else if (lhs instanceof boolean[]) {\n append((boolean[]) lhs, (boolean[]) rhs);\n } else {\n append((Object[]) lhs, (Object[]) rhs);\n }\n return this;\n }\n"}, "reference": " public EqualsBuilder append(Object lhs, Object rhs) {\n if (isEquals == false) {\n return this;\n }\n if (lhs == rhs) {\n return this;\n }\n if (lhs == null || rhs == null) {\n this.setEquals(false);\n return this;\n }\n Class lhsClass = lhs.getClass();\n if (!lhsClass.isArray()) {\n if (lhs instanceof java.math.BigDecimal) {\n isEquals = (((java.math.BigDecimal)lhs).compareTo(rhs) == 0);\n } else {\n isEquals = lhs.equals(rhs);\n }\n } else if (lhs.getClass() != rhs.getClass()) {\n this.setEquals(false);\n }\n else if (lhs instanceof long[]) {\n append((long[]) lhs, (long[]) rhs);\n } else if (lhs instanceof int[]) {\n append((int[]) lhs, (int[]) rhs);\n } else if (lhs instanceof short[]) {\n append((short[]) lhs, (short[]) rhs);\n } else if (lhs instanceof char[]) {\n append((char[]) lhs, (char[]) rhs);\n } else if (lhs instanceof byte[]) {\n append((byte[]) lhs, (byte[]) rhs);\n } else if (lhs instanceof double[]) {\n append((double[]) lhs, (double[]) rhs);\n } else if (lhs instanceof float[]) {\n append((float[]) lhs, (float[]) rhs);\n } else if (lhs instanceof boolean[]) {\n append((boolean[]) lhs, (boolean[]) rhs);\n } else {\n append((Object[]) lhs, (Object[]) rhs);\n }\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-48"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-48"}} {"sample_uid": "defects4j_function_repair::Chart-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ValueMarker(double value, Paint paint, Stroke stroke, \n Paint outlinePaint, Stroke outlineStroke, float alpha) {\n super(paint, stroke, paint, stroke, alpha);\n this.value = value;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ValueMarker(double value, Paint paint, Stroke stroke, \n Paint outlinePaint, Stroke outlineStroke, float alpha) {\n super(paint, stroke, paint, stroke, alpha);\n this.value = value;\n }\n"}, "reference": " public ValueMarker(double value, Paint paint, Stroke stroke, \n Paint outlinePaint, Stroke outlineStroke, float alpha) {\n super(paint, stroke, outlinePaint, outlineStroke, alpha);\n this.value = value;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-20"}} {"sample_uid": "defects4j_function_repair::Lang-45", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String abbreviate(String str, int lower, int upper, String appendToEnd) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return StringUtils.EMPTY;\n }\n if (upper == -1 || upper > str.length()) {\n upper = str.length();\n }\n if (upper < lower) {\n upper = lower;\n }\n StringBuffer result = new StringBuffer();\n int index = StringUtils.indexOf(str, \" \", lower);\n if (index == -1) {\n result.append(str.substring(0, upper));\n if (upper != str.length()) {\n result.append(StringUtils.defaultString(appendToEnd));\n }\n } else if (index > upper) {\n result.append(str.substring(0, upper));\n result.append(StringUtils.defaultString(appendToEnd));\n } else {\n result.append(str.substring(0, index));\n result.append(StringUtils.defaultString(appendToEnd));\n }\n return result.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String abbreviate(String str, int lower, int upper, String appendToEnd) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return StringUtils.EMPTY;\n }\n if (upper == -1 || upper > str.length()) {\n upper = str.length();\n }\n if (upper < lower) {\n upper = lower;\n }\n StringBuffer result = new StringBuffer();\n int index = StringUtils.indexOf(str, \" \", lower);\n if (index == -1) {\n result.append(str.substring(0, upper));\n if (upper != str.length()) {\n result.append(StringUtils.defaultString(appendToEnd));\n }\n } else if (index > upper) {\n result.append(str.substring(0, upper));\n result.append(StringUtils.defaultString(appendToEnd));\n } else {\n result.append(str.substring(0, index));\n result.append(StringUtils.defaultString(appendToEnd));\n }\n return result.toString();\n }\n"}, "reference": " public static String abbreviate(String str, int lower, int upper, String appendToEnd) {\n if (str == null) {\n return null;\n }\n if (str.length() == 0) {\n return StringUtils.EMPTY;\n }\n if (lower > str.length()) {\n lower = str.length(); \n }\n if (upper == -1 || upper > str.length()) {\n upper = str.length();\n }\n if (upper < lower) {\n upper = lower;\n }\n StringBuffer result = new StringBuffer();\n int index = StringUtils.indexOf(str, \" \", lower);\n if (index == -1) {\n result.append(str.substring(0, upper));\n if (upper != str.length()) {\n result.append(StringUtils.defaultString(appendToEnd));\n }\n } else if (index > upper) {\n result.append(str.substring(0, upper));\n result.append(StringUtils.defaultString(appendToEnd));\n } else {\n result.append(str.substring(0, index));\n result.append(StringUtils.defaultString(appendToEnd));\n }\n return result.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-45"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-45"}} {"sample_uid": "defects4j_function_repair::Codec-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String encodeBase64String(byte[] binaryData) {\n return StringUtils.newStringUtf8(encodeBase64(binaryData, true));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String encodeBase64String(byte[] binaryData) {\n return StringUtils.newStringUtf8(encodeBase64(binaryData, true));\n }\n"}, "reference": " public static String encodeBase64String(byte[] binaryData) {\n return StringUtils.newStringUtf8(encodeBase64(binaryData, false));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-7"}} {"sample_uid": "defects4j_function_repair::Gson-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static TypeAdapterFactory newTypeHierarchyFactory(\n final Class clazz, final TypeAdapter typeAdapter) {\n return new TypeAdapterFactory() {\n @SuppressWarnings(\"unchecked\")\n public TypeAdapter create(Gson gson, TypeToken typeToken) {\n final Class requestedType = typeToken.getRawType();\n if (!clazz.isAssignableFrom(requestedType)) {\n return null;\n }\n return (TypeAdapter) typeAdapter;\n }\n @Override public String toString() {\n return \"Factory[typeHierarchy=\" + clazz.getName() + \",adapter=\" + typeAdapter + \"]\";\n }\n };\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static TypeAdapterFactory newTypeHierarchyFactory(\n final Class clazz, final TypeAdapter typeAdapter) {\n return new TypeAdapterFactory() {\n @SuppressWarnings(\"unchecked\")\n public TypeAdapter create(Gson gson, TypeToken typeToken) {\n final Class requestedType = typeToken.getRawType();\n if (!clazz.isAssignableFrom(requestedType)) {\n return null;\n }\n return (TypeAdapter) typeAdapter;\n }\n @Override public String toString() {\n return \"Factory[typeHierarchy=\" + clazz.getName() + \",adapter=\" + typeAdapter + \"]\";\n }\n };\n }\n"}, "reference": " public static TypeAdapterFactory newTypeHierarchyFactory(\n final Class clazz, final TypeAdapter typeAdapter) {\n return new TypeAdapterFactory() {\n @SuppressWarnings(\"unchecked\")\n public TypeAdapter create(Gson gson, TypeToken typeToken) {\n final Class requestedType = typeToken.getRawType();\n if (!clazz.isAssignableFrom(requestedType)) {\n return null;\n }\n return (TypeAdapter) new TypeAdapter() {\n @Override public void write(JsonWriter out, T1 value) throws IOException {\n typeAdapter.write(out, value);\n }\n @Override public T1 read(JsonReader in) throws IOException {\n T1 result = typeAdapter.read(in);\n if (result != null && !requestedType.isInstance(result)) {\n throw new JsonSyntaxException(\"Expected a \" + requestedType.getName()\n + \" but was \" + result.getClass().getName());\n }\n return result;\n }\n };\n }\n @Override public String toString() {\n return \"Factory[typeHierarchy=\" + clazz.getName() + \",adapter=\" + typeAdapter + \"]\";\n }\n };\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-2"}} {"sample_uid": "defects4j_function_repair::Chart-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public XYDataItem addOrUpdate(Number x, Number y) {\n if (x == null) {\n throw new IllegalArgumentException(\"Null 'x' argument.\");\n }\n XYDataItem overwritten = null;\n int index = indexOf(x);\n if (index >= 0 && !this.allowDuplicateXValues) {\n XYDataItem existing = (XYDataItem) this.data.get(index);\n try {\n overwritten = (XYDataItem) existing.clone();\n }\n catch (CloneNotSupportedException e) {\n throw new SeriesException(\"Couldn't clone XYDataItem!\");\n }\n existing.setY(y);\n }\n else {\n if (this.autoSort) {\n this.data.add(-index - 1, new XYDataItem(x, y));\n }\n else {\n this.data.add(new XYDataItem(x, y));\n }\n if (getItemCount() > this.maximumItemCount) {\n this.data.remove(0);\n }\n }\n fireSeriesChanged();\n return overwritten;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public XYDataItem addOrUpdate(Number x, Number y) {\n if (x == null) {\n throw new IllegalArgumentException(\"Null 'x' argument.\");\n }\n XYDataItem overwritten = null;\n int index = indexOf(x);\n if (index >= 0 && !this.allowDuplicateXValues) {\n XYDataItem existing = (XYDataItem) this.data.get(index);\n try {\n overwritten = (XYDataItem) existing.clone();\n }\n catch (CloneNotSupportedException e) {\n throw new SeriesException(\"Couldn't clone XYDataItem!\");\n }\n existing.setY(y);\n }\n else {\n if (this.autoSort) {\n this.data.add(-index - 1, new XYDataItem(x, y));\n }\n else {\n this.data.add(new XYDataItem(x, y));\n }\n if (getItemCount() > this.maximumItemCount) {\n this.data.remove(0);\n }\n }\n fireSeriesChanged();\n return overwritten;\n }\n"}, "reference": " public XYDataItem addOrUpdate(Number x, Number y) {\n if (x == null) {\n throw new IllegalArgumentException(\"Null 'x' argument.\");\n }\n if (this.allowDuplicateXValues) {\n add(x, y);\n return null;\n }\n XYDataItem overwritten = null;\n int index = indexOf(x);\n if (index >= 0) {\n XYDataItem existing = (XYDataItem) this.data.get(index);\n try {\n overwritten = (XYDataItem) existing.clone();\n }\n catch (CloneNotSupportedException e) {\n throw new SeriesException(\"Couldn't clone XYDataItem!\");\n }\n existing.setY(y);\n }\n else {\n if (this.autoSort) {\n this.data.add(-index - 1, new XYDataItem(x, y));\n }\n else {\n this.data.add(new XYDataItem(x, y));\n }\n if (getItemCount() > this.maximumItemCount) {\n this.data.remove(0);\n }\n }\n fireSeriesChanged();\n return overwritten;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-5"}} {"sample_uid": "defects4j_function_repair::Closure-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isInlinableObject(List refs) {\n boolean ret = false;\n Set validProperties = Sets.newHashSet();\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n String propName = parent.getLastChild().getString();\n if (!validProperties.contains(propName)) {\n if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {\n validProperties.add(propName);\n } else {\n return false;\n }\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n validProperties.add(child.getString());\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isInlinableObject(List refs) {\n boolean ret = false;\n Set validProperties = Sets.newHashSet();\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n String propName = parent.getLastChild().getString();\n if (!validProperties.contains(propName)) {\n if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {\n validProperties.add(propName);\n } else {\n return false;\n }\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n validProperties.add(child.getString());\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n"}, "reference": " private boolean isInlinableObject(List refs) {\n boolean ret = false;\n Set validProperties = Sets.newHashSet();\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n if (gramps.isDelProp()) {\n return false;\n }\n String propName = parent.getLastChild().getString();\n if (!validProperties.contains(propName)) {\n if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {\n validProperties.add(propName);\n } else {\n return false;\n }\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n validProperties.add(child.getString());\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-5"}} {"sample_uid": "defects4j_function_repair::Math-64", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected VectorialPointValuePair doOptimize()\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n solvedCols = Math.min(rows, cols);\n diagR = new double[cols];\n jacNorm = new double[cols];\n beta = new double[cols];\n permutation = new int[cols];\n lmDir = new double[cols];\n double delta = 0;\n double xNorm = 0;\n double[] diag = new double[cols];\n double[] oldX = new double[cols];\n double[] oldRes = new double[rows];\n double[] work1 = new double[cols];\n double[] work2 = new double[cols];\n double[] work3 = new double[cols];\n updateResidualsAndCost();\n lmPar = 0;\n boolean firstIteration = true;\n VectorialPointValuePair current = new VectorialPointValuePair(point, objective);\n while (true) {\n incrementIterationsCounter();\n VectorialPointValuePair previous = current;\n updateJacobian();\n qrDecomposition();\n qTy(residuals);\n for (int k = 0; k < solvedCols; ++k) {\n int pk = permutation[k];\n jacobian[k][pk] = diagR[pk];\n }\n if (firstIteration) {\n xNorm = 0;\n for (int k = 0; k < cols; ++k) {\n double dk = jacNorm[k];\n if (dk == 0) {\n dk = 1.0;\n }\n double xk = dk * point[k];\n xNorm += xk * xk;\n diag[k] = dk;\n }\n xNorm = Math.sqrt(xNorm);\n delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);\n }\n double maxCosine = 0;\n if (cost != 0) {\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n double s = jacNorm[pj];\n if (s != 0) {\n double sum = 0;\n for (int i = 0; i <= j; ++i) {\n sum += jacobian[i][pj] * residuals[i];\n }\n maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost));\n }\n }\n }\n if (maxCosine <= orthoTolerance) {\n return current;\n }\n for (int j = 0; j < cols; ++j) {\n diag[j] = Math.max(diag[j], jacNorm[j]);\n }\n for (double ratio = 0; ratio < 1.0e-4;) {\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n oldX[pj] = point[pj];\n }\n double previousCost = cost;\n double[] tmpVec = residuals;\n residuals = oldRes;\n oldRes = tmpVec;\n determineLMParameter(oldRes, delta, diag, work1, work2, work3);\n double lmNorm = 0;\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n lmDir[pj] = -lmDir[pj];\n point[pj] = oldX[pj] + lmDir[pj];\n double s = diag[pj] * lmDir[pj];\n lmNorm += s * s;\n }\n lmNorm = Math.sqrt(lmNorm);\n if (firstIteration) {\n delta = Math.min(delta, lmNorm);\n }\n updateResidualsAndCost();\n current = new VectorialPointValuePair(point, objective);\n double actRed = -1.0;\n if (0.1 * cost < previousCost) {\n double r = cost / previousCost;\n actRed = 1.0 - r * r;\n }\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n double dirJ = lmDir[pj];\n work1[j] = 0;\n for (int i = 0; i <= j; ++i) {\n work1[i] += jacobian[i][pj] * dirJ;\n }\n }\n double coeff1 = 0;\n for (int j = 0; j < solvedCols; ++j) {\n coeff1 += work1[j] * work1[j];\n }\n double pc2 = previousCost * previousCost;\n coeff1 = coeff1 / pc2;\n double coeff2 = lmPar * lmNorm * lmNorm / pc2;\n double preRed = coeff1 + 2 * coeff2;\n double dirDer = -(coeff1 + coeff2);\n ratio = (preRed == 0) ? 0 : (actRed / preRed);\n if (ratio <= 0.25) {\n double tmp =\n (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;\n if ((0.1 * cost >= previousCost) || (tmp < 0.1)) {\n tmp = 0.1;\n }\n delta = tmp * Math.min(delta, 10.0 * lmNorm);\n lmPar /= tmp;\n } else if ((lmPar == 0) || (ratio >= 0.75)) {\n delta = 2 * lmNorm;\n lmPar *= 0.5;\n }\n if (ratio >= 1.0e-4) {\n firstIteration = false;\n xNorm = 0;\n for (int k = 0; k < cols; ++k) {\n double xK = diag[k] * point[k];\n xNorm += xK * xK;\n }\n xNorm = Math.sqrt(xNorm);\n } else {\n cost = previousCost;\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n point[pj] = oldX[pj];\n }\n tmpVec = residuals;\n residuals = oldRes;\n oldRes = tmpVec;\n }\n if (checker==null) {\n \tif (((Math.abs(actRed) <= costRelativeTolerance) &&\n (preRed <= costRelativeTolerance) &&\n (ratio <= 2.0)) ||\n (delta <= parRelativeTolerance * xNorm)) {\n return current;\n }\n } else {\n if (checker.converged(getIterations(), previous, current)) {\n return current;\n }\n }\n if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,\n costRelativeTolerance);\n } else if (delta <= 2.2204e-16 * xNorm) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,\n parRelativeTolerance);\n } else if (maxCosine <= 2.2204e-16) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,\n orthoTolerance);\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected VectorialPointValuePair doOptimize()\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n solvedCols = Math.min(rows, cols);\n diagR = new double[cols];\n jacNorm = new double[cols];\n beta = new double[cols];\n permutation = new int[cols];\n lmDir = new double[cols];\n double delta = 0;\n double xNorm = 0;\n double[] diag = new double[cols];\n double[] oldX = new double[cols];\n double[] oldRes = new double[rows];\n double[] work1 = new double[cols];\n double[] work2 = new double[cols];\n double[] work3 = new double[cols];\n updateResidualsAndCost();\n lmPar = 0;\n boolean firstIteration = true;\n VectorialPointValuePair current = new VectorialPointValuePair(point, objective);\n while (true) {\n incrementIterationsCounter();\n VectorialPointValuePair previous = current;\n updateJacobian();\n qrDecomposition();\n qTy(residuals);\n for (int k = 0; k < solvedCols; ++k) {\n int pk = permutation[k];\n jacobian[k][pk] = diagR[pk];\n }\n if (firstIteration) {\n xNorm = 0;\n for (int k = 0; k < cols; ++k) {\n double dk = jacNorm[k];\n if (dk == 0) {\n dk = 1.0;\n }\n double xk = dk * point[k];\n xNorm += xk * xk;\n diag[k] = dk;\n }\n xNorm = Math.sqrt(xNorm);\n delta = (xNorm == 0) ? initialStepBoundFactor : (initialStepBoundFactor * xNorm);\n }\n double maxCosine = 0;\n if (cost != 0) {\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n double s = jacNorm[pj];\n if (s != 0) {\n double sum = 0;\n for (int i = 0; i <= j; ++i) {\n sum += jacobian[i][pj] * residuals[i];\n }\n maxCosine = Math.max(maxCosine, Math.abs(sum) / (s * cost));\n }\n }\n }\n if (maxCosine <= orthoTolerance) {\n return current;\n }\n for (int j = 0; j < cols; ++j) {\n diag[j] = Math.max(diag[j], jacNorm[j]);\n }\n for (double ratio = 0; ratio < 1.0e-4;) {\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n oldX[pj] = point[pj];\n }\n double previousCost = cost;\n double[] tmpVec = residuals;\n residuals = oldRes;\n oldRes = tmpVec;\n determineLMParameter(oldRes, delta, diag, work1, work2, work3);\n double lmNorm = 0;\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n lmDir[pj] = -lmDir[pj];\n point[pj] = oldX[pj] + lmDir[pj];\n double s = diag[pj] * lmDir[pj];\n lmNorm += s * s;\n }\n lmNorm = Math.sqrt(lmNorm);\n if (firstIteration) {\n delta = Math.min(delta, lmNorm);\n }\n updateResidualsAndCost();\n current = new VectorialPointValuePair(point, objective);\n double actRed = -1.0;\n if (0.1 * cost < previousCost) {\n double r = cost / previousCost;\n actRed = 1.0 - r * r;\n }\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n double dirJ = lmDir[pj];\n work1[j] = 0;\n for (int i = 0; i <= j; ++i) {\n work1[i] += jacobian[i][pj] * dirJ;\n }\n }\n double coeff1 = 0;\n for (int j = 0; j < solvedCols; ++j) {\n coeff1 += work1[j] * work1[j];\n }\n double pc2 = previousCost * previousCost;\n coeff1 = coeff1 / pc2;\n double coeff2 = lmPar * lmNorm * lmNorm / pc2;\n double preRed = coeff1 + 2 * coeff2;\n double dirDer = -(coeff1 + coeff2);\n ratio = (preRed == 0) ? 0 : (actRed / preRed);\n if (ratio <= 0.25) {\n double tmp =\n (actRed < 0) ? (0.5 * dirDer / (dirDer + 0.5 * actRed)) : 0.5;\n if ((0.1 * cost >= previousCost) || (tmp < 0.1)) {\n tmp = 0.1;\n }\n delta = tmp * Math.min(delta, 10.0 * lmNorm);\n lmPar /= tmp;\n } else if ((lmPar == 0) || (ratio >= 0.75)) {\n delta = 2 * lmNorm;\n lmPar *= 0.5;\n }\n if (ratio >= 1.0e-4) {\n firstIteration = false;\n xNorm = 0;\n for (int k = 0; k < cols; ++k) {\n double xK = diag[k] * point[k];\n xNorm += xK * xK;\n }\n xNorm = Math.sqrt(xNorm);\n } else {\n cost = previousCost;\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n point[pj] = oldX[pj];\n }\n tmpVec = residuals;\n residuals = oldRes;\n oldRes = tmpVec;\n }\n if (checker==null) {\n \tif (((Math.abs(actRed) <= costRelativeTolerance) &&\n (preRed <= costRelativeTolerance) &&\n (ratio <= 2.0)) ||\n (delta <= parRelativeTolerance * xNorm)) {\n return current;\n }\n } else {\n if (checker.converged(getIterations(), previous, current)) {\n return current;\n }\n }\n if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,\n costRelativeTolerance);\n } else if (delta <= 2.2204e-16 * xNorm) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,\n parRelativeTolerance);\n } else if (maxCosine <= 2.2204e-16) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,\n orthoTolerance);\n }\n }\n }\n }\n"}, "reference": " protected VectorialPointValuePair doOptimize()\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n solvedCols = Math.min(rows, cols);\n diagR = new double[cols];\n jacNorm = new double[cols];\n beta = new double[cols];\n permutation = new int[cols];\n lmDir = new double[cols];\n double delta = 0;\n double xNorm = 0;\n double[] diag = new double[cols];\n double[] oldX = new double[cols];\n double[] oldRes = new double[rows];\n double[] oldObj = new double[rows];\n double[] qtf = new double[rows];\n double[] work1 = new double[cols];\n double[] work2 = new double[cols];\n double[] work3 = new double[cols];\n updateResidualsAndCost();\n lmPar = 0;\n boolean firstIteration = true;\n VectorialPointValuePair current = new VectorialPointValuePair(point, objective);\n while (true) {\n for (int i=0;i= previousCost) || (tmp < 0.1)) {\n tmp = 0.1;\n }\n delta = tmp * Math.min(delta, 10.0 * lmNorm);\n lmPar /= tmp;\n } else if ((lmPar == 0) || (ratio >= 0.75)) {\n delta = 2 * lmNorm;\n lmPar *= 0.5;\n }\n if (ratio >= 1.0e-4) {\n firstIteration = false;\n xNorm = 0;\n for (int k = 0; k < cols; ++k) {\n double xK = diag[k] * point[k];\n xNorm += xK * xK;\n }\n xNorm = Math.sqrt(xNorm);\n current = new VectorialPointValuePair(point, objective);\n if (checker != null) {\n \tif (checker.converged(getIterations(), previous, current)) {\n \t\treturn current;\n \t}\n }\n } else {\n cost = previousCost;\n for (int j = 0; j < solvedCols; ++j) {\n int pj = permutation[j];\n point[pj] = oldX[pj];\n }\n tmpVec = residuals;\n residuals = oldRes;\n oldRes = tmpVec;\n tmpVec = objective;\n objective = oldObj;\n oldObj = tmpVec;\n }\n if (checker==null) {\n \tif (((Math.abs(actRed) <= costRelativeTolerance) &&\n (preRed <= costRelativeTolerance) &&\n (ratio <= 2.0)) ||\n (delta <= parRelativeTolerance * xNorm)) {\n return current;\n }\n }\n if ((Math.abs(actRed) <= 2.2204e-16) && (preRed <= 2.2204e-16) && (ratio <= 2.0)) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_COST_RELATIVE_TOLERANCE,\n costRelativeTolerance);\n } else if (delta <= 2.2204e-16 * xNorm) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_PARAMETERS_RELATIVE_TOLERANCE,\n parRelativeTolerance);\n } else if (maxCosine <= 2.2204e-16) {\n throw new OptimizationException(LocalizedFormats.TOO_SMALL_ORTHOGONALITY_TOLERANCE,\n orthoTolerance);\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-64"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-64"}} {"sample_uid": "defects4j_function_repair::Mockito-22", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean areEqual(Object o1, Object o2) {\n if (o1 == null || o2 == null) {\n return o1 == null && o2 == null;\n } else if (isArray(o1)) {\n return isArray(o2) && areArraysEqual(o1, o2);\n } else {\n return o1.equals(o2);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean areEqual(Object o1, Object o2) {\n if (o1 == null || o2 == null) {\n return o1 == null && o2 == null;\n } else if (isArray(o1)) {\n return isArray(o2) && areArraysEqual(o1, o2);\n } else {\n return o1.equals(o2);\n }\n }\n"}, "reference": " public static boolean areEqual(Object o1, Object o2) {\n if (o1 == o2 ) {\n return true;\n\t} else if (o1 == null || o2 == null) {\n return o1 == null && o2 == null;\n } else if (isArray(o1)) {\n return isArray(o2) && areArraysEqual(o1, o2);\n } else {\n return o1.equals(o2);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-22"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-22"}} {"sample_uid": "defects4j_function_repair::JacksonXml-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonToken nextToken() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n switch (t) {\n case START_OBJECT:\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n break;\n case START_ARRAY:\n _parsingContext = _parsingContext.createChildArrayContext(-1, -1);\n break;\n case END_OBJECT:\n case END_ARRAY:\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case FIELD_NAME:\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n break;\n default: \n }\n return t;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n return (_currToken = JsonToken.FIELD_NAME);\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n return (_currToken = JsonToken.VALUE_NULL);\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currText = _xmlTokens.getText();\n return (_currToken = JsonToken.VALUE_STRING);\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n if (_parsingContext.inArray()) {\n if (_isEmpty(_currText)) {\n _currToken = JsonToken.END_ARRAY;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n }\n }\n return (_currToken = JsonToken.VALUE_STRING);\n } else {\n if (_parsingContext.inObject()\n && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {\n _currToken = JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n }\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_END:\n return (_currToken = null);\n }\n _throwInternal();\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonToken nextToken() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n switch (t) {\n case START_OBJECT:\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n break;\n case START_ARRAY:\n _parsingContext = _parsingContext.createChildArrayContext(-1, -1);\n break;\n case END_OBJECT:\n case END_ARRAY:\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case FIELD_NAME:\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n break;\n default: \n }\n return t;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n return (_currToken = JsonToken.FIELD_NAME);\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n return (_currToken = JsonToken.VALUE_NULL);\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currText = _xmlTokens.getText();\n return (_currToken = JsonToken.VALUE_STRING);\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n if (_parsingContext.inArray()) {\n if (_isEmpty(_currText)) {\n _currToken = JsonToken.END_ARRAY;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n }\n }\n return (_currToken = JsonToken.VALUE_STRING);\n } else {\n if (_parsingContext.inObject()\n && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {\n _currToken = JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n }\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_END:\n return (_currToken = null);\n }\n _throwInternal();\n return null;\n }\n"}, "reference": " public JsonToken nextToken() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n switch (t) {\n case START_OBJECT:\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n break;\n case START_ARRAY:\n _parsingContext = _parsingContext.createChildArrayContext(-1, -1);\n break;\n case END_OBJECT:\n case END_ARRAY:\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case FIELD_NAME:\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n break;\n default: \n }\n return t;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n return (_currToken = JsonToken.FIELD_NAME);\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n if (_parsingContext.inArray()) {\n _nextToken = JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n return (_currToken = JsonToken.VALUE_NULL);\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currText = _xmlTokens.getText();\n return (_currToken = JsonToken.VALUE_STRING);\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n if (_parsingContext.inArray()) {\n if (_isEmpty(_currText)) {\n _nextToken = JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n return (_currToken = JsonToken.START_OBJECT);\n }\n }\n return (_currToken = JsonToken.VALUE_STRING);\n } else {\n if (_parsingContext.inObject()\n && (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {\n _currToken = JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n return _currToken;\n }\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n return (_currToken = JsonToken.FIELD_NAME);\n case XmlTokenStream.XML_END:\n return (_currToken = null);\n }\n _throwInternal();\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonXml-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonXml-1"}} {"sample_uid": "defects4j_function_repair::Gson-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonWriter value(double value) throws IOException {\n writeDeferredName();\n if (Double.isNaN(value) || Double.isInfinite(value)) {\n throw new IllegalArgumentException(\"Numeric values must be finite, but was \" + value);\n }\n beforeValue();\n out.append(Double.toString(value));\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonWriter value(double value) throws IOException {\n writeDeferredName();\n if (Double.isNaN(value) || Double.isInfinite(value)) {\n throw new IllegalArgumentException(\"Numeric values must be finite, but was \" + value);\n }\n beforeValue();\n out.append(Double.toString(value));\n return this;\n }\n"}, "reference": " public JsonWriter value(double value) throws IOException {\n writeDeferredName();\n if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {\n throw new IllegalArgumentException(\"Numeric values must be finite, but was \" + value);\n }\n beforeValue();\n out.append(Double.toString(value));\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-15"}} {"sample_uid": "defects4j_function_repair::Math-74", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double integrate(final FirstOrderDifferentialEquations equations,\n final double t0, final double[] y0,\n final double t, final double[] y)\n throws DerivativeException, IntegratorException {\n sanityChecks(equations, t0, y0, t, y);\n setEquations(equations);\n resetEvaluations();\n final boolean forward = t > t0;\n final int stages = c.length + 1;\n if (y != y0) {\n System.arraycopy(y0, 0, y, 0, y0.length);\n }\n final double[][] yDotK = new double[stages][y0.length];\n final double[] yTmp = new double[y0.length];\n AbstractStepInterpolator interpolator;\n if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) {\n final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy();\n rki.reinitialize(this, yTmp, yDotK, forward);\n interpolator = rki;\n } else {\n interpolator = new DummyStepInterpolator(yTmp, forward);\n }\n interpolator.storeTime(t0);\n stepStart = t0;\n double hNew = 0;\n boolean firstTime = true;\n for (StepHandler handler : stepHandlers) {\n handler.reset();\n }\n CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager);\n boolean lastStep = false;\n while (!lastStep) {\n interpolator.shift();\n double error = 0;\n for (boolean loop = true; loop;) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale;\n if (vecAbsoluteTolerance == null) {\n scale = new double[y0.length];\n java.util.Arrays.fill(scale, scalAbsoluteTolerance);\n } else {\n scale = vecAbsoluteTolerance;\n }\n hNew = initializeStep(equations, forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error <= 1.0) {\n interpolator.storeTime(stepStart + stepSize);\n if (manager.evaluateStep(interpolator)) {\n final double dt = manager.getEventTime() - stepStart;\n if (Math.abs(dt) <= Math.ulp(stepStart)) {\n loop = false;\n } else {\n hNew = dt;\n }\n } else {\n loop = false;\n }\n } else {\n final double factor =\n Math.min(maxGrowth,\n Math.max(minReduction, safety * Math.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n final double nextStep = stepStart + stepSize;\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n manager.stepAccepted(nextStep, y);\n lastStep = manager.stop();\n interpolator.storeTime(nextStep);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, lastStep);\n }\n stepStart = nextStep;\n if (fsal) {\n System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length);\n }\n if (manager.reset(stepStart, y) && ! lastStep) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (! lastStep) {\n stepSize = filterStep(stepSize, forward, true);\n final double factor = Math.min(maxGrowth,\n Math.max(minReduction,\n safety * Math.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n }\n }\n final double stopTime = stepStart;\n resetInternalState();\n return stopTime;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double integrate(final FirstOrderDifferentialEquations equations,\n final double t0, final double[] y0,\n final double t, final double[] y)\n throws DerivativeException, IntegratorException {\n sanityChecks(equations, t0, y0, t, y);\n setEquations(equations);\n resetEvaluations();\n final boolean forward = t > t0;\n final int stages = c.length + 1;\n if (y != y0) {\n System.arraycopy(y0, 0, y, 0, y0.length);\n }\n final double[][] yDotK = new double[stages][y0.length];\n final double[] yTmp = new double[y0.length];\n AbstractStepInterpolator interpolator;\n if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) {\n final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy();\n rki.reinitialize(this, yTmp, yDotK, forward);\n interpolator = rki;\n } else {\n interpolator = new DummyStepInterpolator(yTmp, forward);\n }\n interpolator.storeTime(t0);\n stepStart = t0;\n double hNew = 0;\n boolean firstTime = true;\n for (StepHandler handler : stepHandlers) {\n handler.reset();\n }\n CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager);\n boolean lastStep = false;\n while (!lastStep) {\n interpolator.shift();\n double error = 0;\n for (boolean loop = true; loop;) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale;\n if (vecAbsoluteTolerance == null) {\n scale = new double[y0.length];\n java.util.Arrays.fill(scale, scalAbsoluteTolerance);\n } else {\n scale = vecAbsoluteTolerance;\n }\n hNew = initializeStep(equations, forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error <= 1.0) {\n interpolator.storeTime(stepStart + stepSize);\n if (manager.evaluateStep(interpolator)) {\n final double dt = manager.getEventTime() - stepStart;\n if (Math.abs(dt) <= Math.ulp(stepStart)) {\n loop = false;\n } else {\n hNew = dt;\n }\n } else {\n loop = false;\n }\n } else {\n final double factor =\n Math.min(maxGrowth,\n Math.max(minReduction, safety * Math.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n final double nextStep = stepStart + stepSize;\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n manager.stepAccepted(nextStep, y);\n lastStep = manager.stop();\n interpolator.storeTime(nextStep);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, lastStep);\n }\n stepStart = nextStep;\n if (fsal) {\n System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length);\n }\n if (manager.reset(stepStart, y) && ! lastStep) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (! lastStep) {\n stepSize = filterStep(stepSize, forward, true);\n final double factor = Math.min(maxGrowth,\n Math.max(minReduction,\n safety * Math.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n }\n }\n final double stopTime = stepStart;\n resetInternalState();\n return stopTime;\n }\n"}, "reference": " public double integrate(final FirstOrderDifferentialEquations equations,\n final double t0, final double[] y0,\n final double t, final double[] y)\n throws DerivativeException, IntegratorException {\n sanityChecks(equations, t0, y0, t, y);\n setEquations(equations);\n resetEvaluations();\n final boolean forward = t > t0;\n final int stages = c.length + 1;\n if (y != y0) {\n System.arraycopy(y0, 0, y, 0, y0.length);\n }\n final double[][] yDotK = new double[stages][y0.length];\n final double[] yTmp = new double[y0.length];\n AbstractStepInterpolator interpolator;\n if (requiresDenseOutput() || (! eventsHandlersManager.isEmpty())) {\n final RungeKuttaStepInterpolator rki = (RungeKuttaStepInterpolator) prototype.copy();\n rki.reinitialize(this, yTmp, yDotK, forward);\n interpolator = rki;\n } else {\n interpolator = new DummyStepInterpolator(yTmp, forward);\n }\n interpolator.storeTime(t0);\n stepStart = t0;\n double hNew = 0;\n boolean firstTime = true;\n for (StepHandler handler : stepHandlers) {\n handler.reset();\n }\n CombinedEventsManager manager = addEndTimeChecker(t0, t, eventsHandlersManager);\n boolean lastStep = false;\n while (!lastStep) {\n interpolator.shift();\n double error = 0;\n for (boolean loop = true; loop;) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale = new double[y0.length];\n if (vecAbsoluteTolerance == null) {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * Math.abs(y[i]);\n }\n } else {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * Math.abs(y[i]);\n }\n }\n hNew = initializeStep(equations, forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error <= 1.0) {\n interpolator.storeTime(stepStart + stepSize);\n if (manager.evaluateStep(interpolator)) {\n final double dt = manager.getEventTime() - stepStart;\n if (Math.abs(dt) <= Math.ulp(stepStart)) {\n loop = false;\n } else {\n hNew = dt;\n }\n } else {\n loop = false;\n }\n } else {\n final double factor =\n Math.min(maxGrowth,\n Math.max(minReduction, safety * Math.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n final double nextStep = stepStart + stepSize;\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n manager.stepAccepted(nextStep, y);\n lastStep = manager.stop();\n interpolator.storeTime(nextStep);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, lastStep);\n }\n stepStart = nextStep;\n if (fsal) {\n System.arraycopy(yDotK[stages - 1], 0, yDotK[0], 0, y0.length);\n }\n if (manager.reset(stepStart, y) && ! lastStep) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (! lastStep) {\n stepSize = filterStep(stepSize, forward, true);\n final double factor = Math.min(maxGrowth,\n Math.max(minReduction,\n safety * Math.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n }\n }\n final double stopTime = stepStart;\n resetInternalState();\n return stopTime;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-74"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-74"}} {"sample_uid": "defects4j_function_repair::Gson-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Number read(JsonReader in) throws IOException {\n JsonToken jsonToken = in.peek();\n switch (jsonToken) {\n case NULL:\n in.nextNull();\n return null;\n case NUMBER:\n return new LazilyParsedNumber(in.nextString());\n default:\n throw new JsonSyntaxException(\"Expecting number, got: \" + jsonToken);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Number read(JsonReader in) throws IOException {\n JsonToken jsonToken = in.peek();\n switch (jsonToken) {\n case NULL:\n in.nextNull();\n return null;\n case NUMBER:\n return new LazilyParsedNumber(in.nextString());\n default:\n throw new JsonSyntaxException(\"Expecting number, got: \" + jsonToken);\n }\n }\n"}, "reference": " public Number read(JsonReader in) throws IOException {\n JsonToken jsonToken = in.peek();\n switch (jsonToken) {\n case NULL:\n in.nextNull();\n return null;\n case NUMBER:\n case STRING:\n return new LazilyParsedNumber(in.nextString());\n default:\n throw new JsonSyntaxException(\"Expecting number, got: \" + jsonToken);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-11"}} {"sample_uid": "defects4j_function_repair::Jsoup-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean process(Token t, TreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n Element form = tb.insert(startTag);\n tb.setFormElement(form);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n TreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size(); si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean process(Token t, TreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n Element form = tb.insert(startTag);\n tb.setFormElement(form);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n TreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size(); si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n"}, "reference": " boolean process(Token t, TreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, \"base\", \"basefont\", \"bgsound\", \"command\", \"link\", \"meta\", \"noframes\", \"script\", \"style\", \"title\")) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"center\", \"details\", \"dir\", \"div\", \"dl\",\n \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"menu\", \"nav\", \"ol\",\n \"p\", \"section\", \"summary\", \"ul\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"pre\", \"listing\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n Element form = tb.insert(startTag);\n tb.setFormElement(form);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), \"dd\", \"dt\")) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), \"address\", \"div\", \"p\"))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name,\n \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, \"area\", \"br\", \"embed\", \"img\", \"keygen\", \"wbr\")) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, \"param\", \"source\", \"track\")) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n startTag.name(\"img\");\n return tb.process(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), \"name\", \"action\", \"prompt\"))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n TreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(\"optgroup\", \"option\")) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(\"rp\", \"rt\")) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name,\n \"caption\", \"col\", \"colgroup\", \"frame\", \"head\", \"tbody\", \"td\", \"tfoot\", \"th\", \"thead\", \"tr\")) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name,\n \"address\", \"article\", \"aside\", \"blockquote\", \"button\", \"center\", \"details\", \"dir\", \"div\",\n \"dl\", \"fieldset\", \"figcaption\", \"figure\", \"footer\", \"header\", \"hgroup\", \"listing\", \"menu\",\n \"nav\", \"ol\", \"pre\", \"section\", \"summary\", \"ul\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"dd\", \"dt\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\")) {\n if (!tb.inScope(new String[]{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"})) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\");\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name,\n \"a\", \"b\", \"big\", \"code\", \"em\", \"font\", \"i\", \"nobr\", \"s\", \"small\", \"strike\", \"strong\", \"tt\", \"u\")) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n for (int si = 0; si < stack.size(); si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), \"table\", \"tbody\", \"tfoot\", \"thead\", \"tr\")) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, \"applet\", \"marquee\", \"object\")) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-15"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-98", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Object complete(JsonParser p, DeserializationContext ctxt,\n PropertyValueBuffer buffer, PropertyBasedCreator creator)\n throws IOException\n {\n final int len = _properties.length;\n Object[] values = new Object[len];\n for (int i = 0; i < len; ++i) {\n String typeId = _typeIds[i];\n final ExtTypedProperty extProp = _properties[i];\n if (typeId == null) {\n if (_tokens[i] == null) {\n continue;\n }\n if (!extProp.hasDefaultType()) {\n ctxt.reportInputMismatch(_beanType,\n \"Missing external type id property '%s'\",\n extProp.getTypePropertyName());\n } else {\n typeId = extProp.getDefaultTypeId();\n }\n } else if (_tokens[i] == null) {\n SettableBeanProperty prop = extProp.getProperty();\n ctxt.reportInputMismatch(_beanType,\n \"Missing property '%s' for external type id '%s'\",\n prop.getName(), _properties[i].getTypePropertyName());\n }\n values[i] = _deserialize(p, ctxt, i, typeId);\n final SettableBeanProperty prop = extProp.getProperty();\n if (prop.getCreatorIndex() >= 0) {\n buffer.assignParameter(prop, values[i]);\n SettableBeanProperty typeProp = extProp.getTypeProperty();\n if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {\n buffer.assignParameter(typeProp, typeId);\n }\n }\n }\n Object bean = creator.build(ctxt, buffer);\n for (int i = 0; i < len; ++i) {\n SettableBeanProperty prop = _properties[i].getProperty();\n if (prop.getCreatorIndex() < 0) {\n prop.set(bean, values[i]);\n }\n }\n return bean;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Object complete(JsonParser p, DeserializationContext ctxt,\n PropertyValueBuffer buffer, PropertyBasedCreator creator)\n throws IOException\n {\n final int len = _properties.length;\n Object[] values = new Object[len];\n for (int i = 0; i < len; ++i) {\n String typeId = _typeIds[i];\n final ExtTypedProperty extProp = _properties[i];\n if (typeId == null) {\n if (_tokens[i] == null) {\n continue;\n }\n if (!extProp.hasDefaultType()) {\n ctxt.reportInputMismatch(_beanType,\n \"Missing external type id property '%s'\",\n extProp.getTypePropertyName());\n } else {\n typeId = extProp.getDefaultTypeId();\n }\n } else if (_tokens[i] == null) {\n SettableBeanProperty prop = extProp.getProperty();\n ctxt.reportInputMismatch(_beanType,\n \"Missing property '%s' for external type id '%s'\",\n prop.getName(), _properties[i].getTypePropertyName());\n }\n values[i] = _deserialize(p, ctxt, i, typeId);\n final SettableBeanProperty prop = extProp.getProperty();\n if (prop.getCreatorIndex() >= 0) {\n buffer.assignParameter(prop, values[i]);\n SettableBeanProperty typeProp = extProp.getTypeProperty();\n if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {\n buffer.assignParameter(typeProp, typeId);\n }\n }\n }\n Object bean = creator.build(ctxt, buffer);\n for (int i = 0; i < len; ++i) {\n SettableBeanProperty prop = _properties[i].getProperty();\n if (prop.getCreatorIndex() < 0) {\n prop.set(bean, values[i]);\n }\n }\n return bean;\n }\n"}, "reference": " public Object complete(JsonParser p, DeserializationContext ctxt,\n PropertyValueBuffer buffer, PropertyBasedCreator creator)\n throws IOException\n {\n final int len = _properties.length;\n Object[] values = new Object[len];\n for (int i = 0; i < len; ++i) {\n String typeId = _typeIds[i];\n final ExtTypedProperty extProp = _properties[i];\n if (typeId == null) {\n if (_tokens[i] == null) {\n continue;\n }\n if (!extProp.hasDefaultType()) {\n ctxt.reportInputMismatch(_beanType,\n \"Missing external type id property '%s'\",\n extProp.getTypePropertyName());\n } else {\n typeId = extProp.getDefaultTypeId();\n }\n } else if (_tokens[i] == null) {\n SettableBeanProperty prop = extProp.getProperty();\n ctxt.reportInputMismatch(_beanType,\n \"Missing property '%s' for external type id '%s'\",\n prop.getName(), _properties[i].getTypePropertyName());\n }\n values[i] = _deserialize(p, ctxt, i, typeId);\n final SettableBeanProperty prop = extProp.getProperty();\n if (prop.getCreatorIndex() >= 0) {\n buffer.assignParameter(prop, values[i]);\n SettableBeanProperty typeProp = extProp.getTypeProperty();\n if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {\n final Object v;\n if (typeProp.getType().hasRawClass(String.class)) {\n v = typeId;\n } else {\n TokenBuffer tb = new TokenBuffer(p, ctxt);\n tb.writeString(typeId);\n v = typeProp.getValueDeserializer().deserialize(tb.asParserOnFirstToken(), ctxt);\n tb.close();\n }\n buffer.assignParameter(typeProp, v);\n }\n }\n }\n Object bean = creator.build(ctxt, buffer);\n for (int i = 0; i < len; ++i) {\n SettableBeanProperty prop = _properties[i].getProperty();\n if (prop.getCreatorIndex() < 0) {\n prop.set(bean, values[i]);\n }\n }\n return bean;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-98"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-98"}} {"sample_uid": "defects4j_function_repair::Math-69", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public RealMatrix getCorrelationPValues() throws MathException {\n TDistribution tDistribution = new TDistributionImpl(nObs - 2);\n int nVars = correlationMatrix.getColumnDimension();\n double[][] out = new double[nVars][nVars];\n for (int i = 0; i < nVars; i++) {\n for (int j = 0; j < nVars; j++) {\n if (i == j) {\n out[i][j] = 0d;\n } else {\n double r = correlationMatrix.getEntry(i, j);\n double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r)));\n out[i][j] = 2 * (1 - tDistribution.cumulativeProbability(t));\n }\n }\n }\n return new BlockRealMatrix(out);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public RealMatrix getCorrelationPValues() throws MathException {\n TDistribution tDistribution = new TDistributionImpl(nObs - 2);\n int nVars = correlationMatrix.getColumnDimension();\n double[][] out = new double[nVars][nVars];\n for (int i = 0; i < nVars; i++) {\n for (int j = 0; j < nVars; j++) {\n if (i == j) {\n out[i][j] = 0d;\n } else {\n double r = correlationMatrix.getEntry(i, j);\n double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r)));\n out[i][j] = 2 * (1 - tDistribution.cumulativeProbability(t));\n }\n }\n }\n return new BlockRealMatrix(out);\n }\n"}, "reference": " public RealMatrix getCorrelationPValues() throws MathException {\n TDistribution tDistribution = new TDistributionImpl(nObs - 2);\n int nVars = correlationMatrix.getColumnDimension();\n double[][] out = new double[nVars][nVars];\n for (int i = 0; i < nVars; i++) {\n for (int j = 0; j < nVars; j++) {\n if (i == j) {\n out[i][j] = 0d;\n } else {\n double r = correlationMatrix.getEntry(i, j);\n double t = Math.abs(r * Math.sqrt((nObs - 2)/(1 - r * r)));\n out[i][j] = 2 * tDistribution.cumulativeProbability(-t);\n }\n }\n }\n return new BlockRealMatrix(out);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-69"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-69"}} {"sample_uid": "defects4j_function_repair::Csv-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Map initializeHeader() throws IOException {\n Map hdrMap = null;\n final String[] formatHeader = this.format.getHeader();\n if (formatHeader != null) {\n hdrMap = new LinkedHashMap();\n String[] headerRecord = null;\n if (formatHeader.length == 0) {\n final CSVRecord nextRecord = this.nextRecord();\n if (nextRecord != null) {\n headerRecord = nextRecord.values();\n }\n } else {\n if (this.format.getSkipHeaderRecord()) {\n this.nextRecord();\n }\n headerRecord = formatHeader;\n }\n if (headerRecord != null) {\n for (int i = 0; i < headerRecord.length; i++) {\n final String header = headerRecord[i];\n final boolean containsHeader = hdrMap.containsKey(header);\n final boolean emptyHeader = header.trim().isEmpty();\n if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) {\n throw new IllegalArgumentException(\"The header contains a duplicate name: \\\"\" + header +\n \"\\\" in \" + Arrays.toString(headerRecord));\n }\n hdrMap.put(header, Integer.valueOf(i));\n }\n }\n }\n return hdrMap;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Map initializeHeader() throws IOException {\n Map hdrMap = null;\n final String[] formatHeader = this.format.getHeader();\n if (formatHeader != null) {\n hdrMap = new LinkedHashMap();\n String[] headerRecord = null;\n if (formatHeader.length == 0) {\n final CSVRecord nextRecord = this.nextRecord();\n if (nextRecord != null) {\n headerRecord = nextRecord.values();\n }\n } else {\n if (this.format.getSkipHeaderRecord()) {\n this.nextRecord();\n }\n headerRecord = formatHeader;\n }\n if (headerRecord != null) {\n for (int i = 0; i < headerRecord.length; i++) {\n final String header = headerRecord[i];\n final boolean containsHeader = hdrMap.containsKey(header);\n final boolean emptyHeader = header.trim().isEmpty();\n if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) {\n throw new IllegalArgumentException(\"The header contains a duplicate name: \\\"\" + header +\n \"\\\" in \" + Arrays.toString(headerRecord));\n }\n hdrMap.put(header, Integer.valueOf(i));\n }\n }\n }\n return hdrMap;\n }\n"}, "reference": " private Map initializeHeader() throws IOException {\n Map hdrMap = null;\n final String[] formatHeader = this.format.getHeader();\n if (formatHeader != null) {\n hdrMap = new LinkedHashMap();\n String[] headerRecord = null;\n if (formatHeader.length == 0) {\n final CSVRecord nextRecord = this.nextRecord();\n if (nextRecord != null) {\n headerRecord = nextRecord.values();\n }\n } else {\n if (this.format.getSkipHeaderRecord()) {\n this.nextRecord();\n }\n headerRecord = formatHeader;\n }\n if (headerRecord != null) {\n for (int i = 0; i < headerRecord.length; i++) {\n final String header = headerRecord[i];\n final boolean containsHeader = hdrMap.containsKey(header);\n final boolean emptyHeader = header == null || header.trim().isEmpty();\n if (containsHeader && (!emptyHeader || (emptyHeader && !this.format.getIgnoreEmptyHeaders()))) {\n throw new IllegalArgumentException(\"The header contains a duplicate name: \\\"\" + header +\n \"\\\" in \" + Arrays.toString(headerRecord));\n }\n hdrMap.put(header, Integer.valueOf(i));\n }\n }\n }\n return hdrMap;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-11"}} {"sample_uid": "defects4j_function_repair::Closure-97", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryFoldShift(Node n, Node left, Node right) {\n if (left.getType() == Token.NUMBER &&\n right.getType() == Token.NUMBER) {\n double result;\n double lval = left.getDouble();\n double rval = right.getDouble();\n if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {\n error(BITWISE_OPERAND_OUT_OF_RANGE, left);\n return n;\n }\n if (!(rval >= 0 && rval < 32)) {\n error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);\n return n;\n }\n int lvalInt = (int) lval;\n if (lvalInt != lval) {\n error(FRACTIONAL_BITWISE_OPERAND, left);\n return n;\n }\n int rvalInt = (int) rval;\n if (rvalInt != rval) {\n error(FRACTIONAL_BITWISE_OPERAND, right);\n return n;\n }\n switch (n.getType()) {\n case Token.LSH:\n result = lvalInt << rvalInt;\n break;\n case Token.RSH:\n result = lvalInt >> rvalInt;\n break;\n case Token.URSH:\n result = lvalInt >>> rvalInt;\n break;\n default:\n throw new AssertionError(\"Unknown shift operator: \" +\n Node.tokenToName(n.getType()));\n }\n Node newNumber = Node.newNumber(result);\n n.getParent().replaceChild(n, newNumber);\n reportCodeChange();\n return newNumber;\n }\n return n;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryFoldShift(Node n, Node left, Node right) {\n if (left.getType() == Token.NUMBER &&\n right.getType() == Token.NUMBER) {\n double result;\n double lval = left.getDouble();\n double rval = right.getDouble();\n if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {\n error(BITWISE_OPERAND_OUT_OF_RANGE, left);\n return n;\n }\n if (!(rval >= 0 && rval < 32)) {\n error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);\n return n;\n }\n int lvalInt = (int) lval;\n if (lvalInt != lval) {\n error(FRACTIONAL_BITWISE_OPERAND, left);\n return n;\n }\n int rvalInt = (int) rval;\n if (rvalInt != rval) {\n error(FRACTIONAL_BITWISE_OPERAND, right);\n return n;\n }\n switch (n.getType()) {\n case Token.LSH:\n result = lvalInt << rvalInt;\n break;\n case Token.RSH:\n result = lvalInt >> rvalInt;\n break;\n case Token.URSH:\n result = lvalInt >>> rvalInt;\n break;\n default:\n throw new AssertionError(\"Unknown shift operator: \" +\n Node.tokenToName(n.getType()));\n }\n Node newNumber = Node.newNumber(result);\n n.getParent().replaceChild(n, newNumber);\n reportCodeChange();\n return newNumber;\n }\n return n;\n }\n"}, "reference": " private Node tryFoldShift(Node n, Node left, Node right) {\n if (left.getType() == Token.NUMBER &&\n right.getType() == Token.NUMBER) {\n double result;\n double lval = left.getDouble();\n double rval = right.getDouble();\n if (!(lval >= Integer.MIN_VALUE && lval <= Integer.MAX_VALUE)) {\n error(BITWISE_OPERAND_OUT_OF_RANGE, left);\n return n;\n }\n if (!(rval >= 0 && rval < 32)) {\n error(SHIFT_AMOUNT_OUT_OF_BOUNDS, right);\n return n;\n }\n int lvalInt = (int) lval;\n if (lvalInt != lval) {\n error(FRACTIONAL_BITWISE_OPERAND, left);\n return n;\n }\n int rvalInt = (int) rval;\n if (rvalInt != rval) {\n error(FRACTIONAL_BITWISE_OPERAND, right);\n return n;\n }\n switch (n.getType()) {\n case Token.LSH:\n result = lvalInt << rvalInt;\n break;\n case Token.RSH:\n result = lvalInt >> rvalInt;\n break;\n case Token.URSH:\n long lvalLong = lvalInt & 0xffffffffL;\n result = lvalLong >>> rvalInt;\n break;\n default:\n throw new AssertionError(\"Unknown shift operator: \" +\n Node.tokenToName(n.getType()));\n }\n Node newNumber = Node.newNumber(result);\n n.getParent().replaceChild(n, newNumber);\n reportCodeChange();\n return newNumber;\n }\n return n;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-97"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-97"}} {"sample_uid": "defects4j_function_repair::Jsoup-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void parseStartTag() {\n tq.consume(\"<\");\n String tagName = tq.consumeWord();\n if (tagName.length() == 0) { \n tq.addFirst(\"<\");\n parseTextNode();\n return;\n }\n Attributes attributes = new Attributes();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.isEmpty()) {\n Attribute attribute = parseAttribute();\n if (attribute != null)\n attributes.put(attribute);\n }\n Tag tag = Tag.valueOf(tagName);\n Element child = new Element(tag, baseUri, attributes);\n boolean isEmptyElement = tag.isEmpty(); \n if (tq.matchChomp(\"/>\")) { \n isEmptyElement = true;\n } else {\n tq.matchChomp(\">\");\n }\n addChildToParent(child, isEmptyElement);\n if (tag.isData()) {\n String data = tq.chompTo(\"\");\n Node dataNode;\n if (tag.equals(titleTag) || tag.equals(textareaTag)) \n dataNode = TextNode.createFromEncoded(data, baseUri);\n else\n dataNode = new DataNode(data, baseUri); \n child.appendChild(dataNode); \n }\n if (child.tagName().equals(\"base\")) {\n String href = child.absUrl(\"href\");\n if (href.length() != 0) { \n baseUri = href;\n doc.setBaseUri(href); \n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void parseStartTag() {\n tq.consume(\"<\");\n String tagName = tq.consumeWord();\n if (tagName.length() == 0) { \n tq.addFirst(\"<\");\n parseTextNode();\n return;\n }\n Attributes attributes = new Attributes();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.isEmpty()) {\n Attribute attribute = parseAttribute();\n if (attribute != null)\n attributes.put(attribute);\n }\n Tag tag = Tag.valueOf(tagName);\n Element child = new Element(tag, baseUri, attributes);\n boolean isEmptyElement = tag.isEmpty(); \n if (tq.matchChomp(\"/>\")) { \n isEmptyElement = true;\n } else {\n tq.matchChomp(\">\");\n }\n addChildToParent(child, isEmptyElement);\n if (tag.isData()) {\n String data = tq.chompTo(\"\");\n Node dataNode;\n if (tag.equals(titleTag) || tag.equals(textareaTag)) \n dataNode = TextNode.createFromEncoded(data, baseUri);\n else\n dataNode = new DataNode(data, baseUri); \n child.appendChild(dataNode); \n }\n if (child.tagName().equals(\"base\")) {\n String href = child.absUrl(\"href\");\n if (href.length() != 0) { \n baseUri = href;\n doc.setBaseUri(href); \n }\n }\n }\n"}, "reference": " private void parseStartTag() {\n tq.consume(\"<\");\n String tagName = tq.consumeWord();\n if (tagName.length() == 0) { \n tq.addFirst(\"<\");\n parseTextNode();\n return;\n }\n Attributes attributes = new Attributes();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.isEmpty()) {\n Attribute attribute = parseAttribute();\n if (attribute != null)\n attributes.put(attribute);\n }\n Tag tag = Tag.valueOf(tagName);\n Element child = new Element(tag, baseUri, attributes);\n boolean isEmptyElement = tag.isEmpty(); \n if (tq.matchChomp(\"/>\")) { \n isEmptyElement = true;\n } else {\n tq.matchChomp(\">\");\n }\n addChildToParent(child, isEmptyElement);\n if (tag.isData()) {\n String data = tq.chompTo(\"\");\n popStackToClose(tag);\n Node dataNode;\n if (tag.equals(titleTag) || tag.equals(textareaTag)) \n dataNode = TextNode.createFromEncoded(data, baseUri);\n else\n dataNode = new DataNode(data, baseUri); \n child.appendChild(dataNode); \n }\n if (child.tagName().equals(\"base\")) {\n String href = child.absUrl(\"href\");\n if (href.length() != 0) { \n baseUri = href;\n doc.setBaseUri(href); \n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-2"}} {"sample_uid": "defects4j_function_repair::Jsoup-88", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String getValue() {\n return val;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String getValue() {\n return val;\n }\n"}, "reference": " public String getValue() {\n return Attributes.checkNotNull(val);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-88"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-88"}} {"sample_uid": "defects4j_function_repair::Jsoup-86", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public XmlDeclaration asXmlDeclaration() {\n String data = getData();\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri(), Parser.xmlParser());\n XmlDeclaration decl = null;\n if (doc.childNodeSize() > 0) {\n Element el = doc.child(0);\n decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith(\"!\"));\n decl.attributes().addAll(el.attributes());\n }\n return decl;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public XmlDeclaration asXmlDeclaration() {\n String data = getData();\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri(), Parser.xmlParser());\n XmlDeclaration decl = null;\n if (doc.childNodeSize() > 0) {\n Element el = doc.child(0);\n decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith(\"!\"));\n decl.attributes().addAll(el.attributes());\n }\n return decl;\n }\n"}, "reference": " public XmlDeclaration asXmlDeclaration() {\n String data = getData();\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri(), Parser.xmlParser());\n XmlDeclaration decl = null;\n if (doc.children().size() > 0) {\n Element el = doc.child(0);\n decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith(\"!\"));\n decl.attributes().addAll(el.attributes());\n }\n return decl;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-86"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-86"}} {"sample_uid": "defects4j_function_repair::Closure-105", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right,\n Node parent) {\n if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {\n return;\n }\n Node arrayNode = left.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return;\n }\n String joinString = NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = new StringBuilder();\n int foldedSize = 0;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem)) {\n if (sb.length() > 0) {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getStringValue(elem));\n } else {\n if (sb.length() > 0) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n sb = new StringBuilder();\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n elem = elem.getNext();\n }\n if (sb.length() > 0) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n parent.replaceChild(n, emptyStringNode);\n break;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\"), foldedStringNode);\n foldedStringNode = replacement;\n }\n parent.replaceChild(n, foldedStringNode);\n break;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += InlineCostEstimator.getCost(right);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n break;\n }\n t.getCompiler().reportCodeChange();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right,\n Node parent) {\n if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {\n return;\n }\n Node arrayNode = left.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return;\n }\n String joinString = NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = new StringBuilder();\n int foldedSize = 0;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem)) {\n if (sb.length() > 0) {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getStringValue(elem));\n } else {\n if (sb.length() > 0) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n sb = new StringBuilder();\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n elem = elem.getNext();\n }\n if (sb.length() > 0) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n parent.replaceChild(n, emptyStringNode);\n break;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\"), foldedStringNode);\n foldedStringNode = replacement;\n }\n parent.replaceChild(n, foldedStringNode);\n break;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += InlineCostEstimator.getCost(right);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n break;\n }\n t.getCompiler().reportCodeChange();\n }\n"}, "reference": " void tryFoldStringJoin(NodeTraversal t, Node n, Node left, Node right,\n Node parent) {\n if (!NodeUtil.isGetProp(left) || !NodeUtil.isImmutableValue(right)) {\n return;\n }\n Node arrayNode = left.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return;\n }\n String joinString = NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = null;\n int foldedSize = 0;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem)) {\n if (sb == null) {\n sb = new StringBuilder();\n } else {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getStringValue(elem));\n } else {\n if (sb != null) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n sb = null;\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n elem = elem.getNext();\n }\n if (sb != null) {\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(Node.newString(sb.toString()));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n parent.replaceChild(n, emptyStringNode);\n break;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\"), foldedStringNode);\n foldedStringNode = replacement;\n }\n parent.replaceChild(n, foldedStringNode);\n break;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += InlineCostEstimator.getCost(right);\n if (foldedSize > originalSize) {\n return;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n break;\n }\n t.getCompiler().reportCodeChange();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-105"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-105"}} {"sample_uid": "defects4j_function_repair::Compress-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {\n int cache = 0;\n int shift = 7;\n for (int i = 0; i < length; i++) {\n cache |= ((bits.get(i) ? 1 : 0) << shift);\n --shift;\n if (shift == 0) {\n header.write(cache);\n shift = 7;\n cache = 0;\n }\n }\n if (length > 0 && shift > 0) {\n header.write(cache);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {\n int cache = 0;\n int shift = 7;\n for (int i = 0; i < length; i++) {\n cache |= ((bits.get(i) ? 1 : 0) << shift);\n --shift;\n if (shift == 0) {\n header.write(cache);\n shift = 7;\n cache = 0;\n }\n }\n if (length > 0 && shift > 0) {\n header.write(cache);\n }\n }\n"}, "reference": " private void writeBits(final DataOutput header, final BitSet bits, final int length) throws IOException {\n int cache = 0;\n int shift = 7;\n for (int i = 0; i < length; i++) {\n cache |= ((bits.get(i) ? 1 : 0) << shift);\n if (--shift < 0) {\n header.write(cache);\n shift = 7;\n cache = 0;\n }\n }\n if (shift != 7) {\n header.write(cache);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-21"}} {"sample_uid": "defects4j_function_repair::Codec-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void encode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n switch (modulus) {\n case 1:\n buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 4) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n buf[pos++] = PAD;\n }\n break;\n case 2:\n buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 2) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n }\n break;\n }\n if (lineLength > 0) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n }\n } else {\n for (int i = 0; i < inAvail; i++) {\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n modulus = (++modulus) % 3;\n int b = in[inPos++];\n if (b < 0) { b += 256; }\n x = (x << 8) + b;\n if (0 == modulus) {\n buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS];\n buf[pos++] = encodeTable[x & MASK_6BITS];\n currentLinePos += 4;\n if (lineLength > 0 && lineLength <= currentLinePos) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n currentLinePos = 0;\n }\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void encode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n switch (modulus) {\n case 1:\n buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 4) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n buf[pos++] = PAD;\n }\n break;\n case 2:\n buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 2) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n }\n break;\n }\n if (lineLength > 0) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n }\n } else {\n for (int i = 0; i < inAvail; i++) {\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n modulus = (++modulus) % 3;\n int b = in[inPos++];\n if (b < 0) { b += 256; }\n x = (x << 8) + b;\n if (0 == modulus) {\n buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS];\n buf[pos++] = encodeTable[x & MASK_6BITS];\n currentLinePos += 4;\n if (lineLength > 0 && lineLength <= currentLinePos) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n currentLinePos = 0;\n }\n }\n }\n }\n }\n"}, "reference": " void encode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n switch (modulus) {\n case 1:\n buf[pos++] = encodeTable[(x >> 2) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 4) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n buf[pos++] = PAD;\n }\n break;\n case 2:\n buf[pos++] = encodeTable[(x >> 10) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 4) & MASK_6BITS];\n buf[pos++] = encodeTable[(x << 2) & MASK_6BITS];\n if (encodeTable == STANDARD_ENCODE_TABLE) {\n buf[pos++] = PAD;\n }\n break;\n }\n if (lineLength > 0 && pos > 0) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n }\n } else {\n for (int i = 0; i < inAvail; i++) {\n if (buf == null || buf.length - pos < encodeSize) {\n resizeBuf();\n }\n modulus = (++modulus) % 3;\n int b = in[inPos++];\n if (b < 0) { b += 256; }\n x = (x << 8) + b;\n if (0 == modulus) {\n buf[pos++] = encodeTable[(x >> 18) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 12) & MASK_6BITS];\n buf[pos++] = encodeTable[(x >> 6) & MASK_6BITS];\n buf[pos++] = encodeTable[x & MASK_6BITS];\n currentLinePos += 4;\n if (lineLength > 0 && lineLength <= currentLinePos) {\n System.arraycopy(lineSeparator, 0, buf, pos, lineSeparator.length);\n pos += lineSeparator.length;\n currentLinePos = 0;\n }\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-2"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-76", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,\n \t\tDeserializationContext ctxt)\n throws IOException, JsonProcessingException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt))) {\n t = p.nextToken();\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n continue;\n }\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken();\n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n tokens.writeEndObject();\n if (bean.getClass() != _beanType.getRawClass()) {\n ctxt.reportMappingException(\"Can not create polymorphic instances with unwrapped values\");\n return null;\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n return wrapInstantiationProblem(e, ctxt);\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,\n \t\tDeserializationContext ctxt)\n throws IOException, JsonProcessingException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt))) {\n t = p.nextToken();\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n continue;\n }\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken();\n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n tokens.writeEndObject();\n if (bean.getClass() != _beanType.getRawClass()) {\n ctxt.reportMappingException(\"Can not create polymorphic instances with unwrapped values\");\n return null;\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n return wrapInstantiationProblem(e, ctxt);\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n"}, "reference": " protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,\n \t\tDeserializationContext ctxt)\n throws IOException, JsonProcessingException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt));\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n return wrapInstantiationProblem(e, ctxt);\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-76"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-76"}} {"sample_uid": "defects4j_function_repair::Mockito-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public T createMock(MockCreationSettings settings, MockHandler handler) {\n if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {\n throw new MockitoException(\"Serialization across classloaders not yet supported with ByteBuddyMockMaker\");\n }\n Class mockedProxyType = cachingMockBytecodeGenerator.get(\n settings.getTypeToMock(),\n settings.getExtraInterfaces()\n );\n T mockInstance = null;\n try {\n mockInstance = classInstantiator.instantiate(mockedProxyType);\n MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance;\n mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings));\n return ensureMockIsAssignableToMockedType(settings, mockInstance);\n } catch (ClassCastException cce) {\n throw new MockitoException(join(\n \"ClassCastException occurred while creating the mockito mock :\",\n \" class to mock : \" + describeClass(mockedProxyType),\n \" created class : \" + describeClass(settings.getTypeToMock()),\n \" proxy instance class : \" + describeClass(mockInstance),\n \" instance creation by : \" + classInstantiator.getClass().getSimpleName(),\n \"\",\n \"You might experience classloading issues, please ask the mockito mailing-list.\",\n \"\"\n ),cce);\n } catch (org.mockito.internal.creation.instance.InstantiationException e) {\n throw new MockitoException(\"Unable to create mock instance of type '\" + mockedProxyType.getSuperclass().getSimpleName() + \"'\", e);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public T createMock(MockCreationSettings settings, MockHandler handler) {\n if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {\n throw new MockitoException(\"Serialization across classloaders not yet supported with ByteBuddyMockMaker\");\n }\n Class mockedProxyType = cachingMockBytecodeGenerator.get(\n settings.getTypeToMock(),\n settings.getExtraInterfaces()\n );\n T mockInstance = null;\n try {\n mockInstance = classInstantiator.instantiate(mockedProxyType);\n MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance;\n mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings));\n return ensureMockIsAssignableToMockedType(settings, mockInstance);\n } catch (ClassCastException cce) {\n throw new MockitoException(join(\n \"ClassCastException occurred while creating the mockito mock :\",\n \" class to mock : \" + describeClass(mockedProxyType),\n \" created class : \" + describeClass(settings.getTypeToMock()),\n \" proxy instance class : \" + describeClass(mockInstance),\n \" instance creation by : \" + classInstantiator.getClass().getSimpleName(),\n \"\",\n \"You might experience classloading issues, please ask the mockito mailing-list.\",\n \"\"\n ),cce);\n } catch (org.mockito.internal.creation.instance.InstantiationException e) {\n throw new MockitoException(\"Unable to create mock instance of type '\" + mockedProxyType.getSuperclass().getSimpleName() + \"'\", e);\n }\n }\n"}, "reference": " public T createMock(MockCreationSettings settings, MockHandler handler) {\n if (settings.getSerializableMode() == SerializableMode.ACROSS_CLASSLOADERS) {\n throw new MockitoException(\"Serialization across classloaders not yet supported with ByteBuddyMockMaker\");\n }\n Class mockedProxyType = cachingMockBytecodeGenerator.get(\n settings.getTypeToMock(),\n settings.getExtraInterfaces()\n );\n Instantiator instantiator = new InstantiatorProvider().getInstantiator(settings);\n T mockInstance = null;\n try {\n mockInstance = instantiator.newInstance(mockedProxyType);\n MockMethodInterceptor.MockAccess mockAccess = (MockMethodInterceptor.MockAccess) mockInstance;\n mockAccess.setMockitoInterceptor(new MockMethodInterceptor(asInternalMockHandler(handler), settings));\n return ensureMockIsAssignableToMockedType(settings, mockInstance);\n } catch (ClassCastException cce) {\n throw new MockitoException(join(\n \"ClassCastException occurred while creating the mockito mock :\",\n \" class to mock : \" + describeClass(mockedProxyType),\n \" created class : \" + describeClass(settings.getTypeToMock()),\n \" proxy instance class : \" + describeClass(mockInstance),\n \" instance creation by : \" + instantiator.getClass().getSimpleName(),\n \"\",\n \"You might experience classloading issues, please ask the mockito mailing-list.\",\n \"\"\n ),cce);\n } catch (org.mockito.internal.creation.instance.InstantiationException e) {\n throw new MockitoException(\"Unable to create mock instance of type '\" + mockedProxyType.getSuperclass().getSimpleName() + \"'\", e);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-20"}} {"sample_uid": "defects4j_function_repair::Jsoup-39", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n } else {\n foundCharset = meta.attr(\"charset\");\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (docData.length() > 0 && docData.charAt(0) == 65279) {\n byteData.rewind();\n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n docData = docData.substring(1);\n charsetName = defaultCharset;\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n } else {\n foundCharset = meta.attr(\"charset\");\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (docData.length() > 0 && docData.charAt(0) == 65279) {\n byteData.rewind();\n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n docData = docData.substring(1);\n charsetName = defaultCharset;\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n"}, "reference": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n } else {\n foundCharset = meta.attr(\"charset\");\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (docData.length() > 0 && docData.charAt(0) == 65279) {\n byteData.rewind();\n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n docData = docData.substring(1);\n charsetName = defaultCharset;\n doc = null;\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-39"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-39"}} {"sample_uid": "defects4j_function_repair::Jsoup-90", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static boolean looksLikeUtf8(byte[] input) {\n int i = 0;\n if (input.length >= 3 && (input[0] & 0xFF) == 0xEF\n && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {\n i = 3;\n }\n int end;\n for (int j = input.length; i < j; ++i) {\n int o = input[i];\n if ((o & 0x80) == 0) {\n continue; \n }\n if ((o & 0xE0) == 0xC0) {\n end = i + 1;\n } else if ((o & 0xF0) == 0xE0) {\n end = i + 2;\n } else if ((o & 0xF8) == 0xF0) {\n end = i + 3;\n } else {\n return false;\n }\n while (i < end) {\n i++;\n o = input[i];\n if ((o & 0xC0) != 0x80) {\n return false;\n }\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static boolean looksLikeUtf8(byte[] input) {\n int i = 0;\n if (input.length >= 3 && (input[0] & 0xFF) == 0xEF\n && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {\n i = 3;\n }\n int end;\n for (int j = input.length; i < j; ++i) {\n int o = input[i];\n if ((o & 0x80) == 0) {\n continue; \n }\n if ((o & 0xE0) == 0xC0) {\n end = i + 1;\n } else if ((o & 0xF0) == 0xE0) {\n end = i + 2;\n } else if ((o & 0xF8) == 0xF0) {\n end = i + 3;\n } else {\n return false;\n }\n while (i < end) {\n i++;\n o = input[i];\n if ((o & 0xC0) != 0x80) {\n return false;\n }\n }\n }\n return true;\n }\n"}, "reference": " private static boolean looksLikeUtf8(byte[] input) {\n int i = 0;\n if (input.length >= 3 && (input[0] & 0xFF) == 0xEF\n && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {\n i = 3;\n }\n int end;\n for (int j = input.length; i < j; ++i) {\n int o = input[i];\n if ((o & 0x80) == 0) {\n continue; \n }\n if ((o & 0xE0) == 0xC0) {\n end = i + 1;\n } else if ((o & 0xF0) == 0xE0) {\n end = i + 2;\n } else if ((o & 0xF8) == 0xF0) {\n end = i + 3;\n } else {\n return false;\n }\n if (end >= input.length)\n return false;\n while (i < end) {\n i++;\n o = input[i];\n if ((o & 0xC0) != 0x80) {\n return false;\n }\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-90"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-90"}} {"sample_uid": "defects4j_function_repair::Time-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Period normalizedStandard(PeriodType type) {\n type = DateTimeUtils.getPeriodType(type);\n long millis = getMillis(); \n millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND));\n millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE));\n millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR));\n millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY));\n millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK));\n Period result = new Period(millis, type, ISOChronology.getInstanceUTC());\n int years = getYears();\n int months = getMonths();\n if (years != 0 || months != 0) {\n years = FieldUtils.safeAdd(years, months / 12);\n months = months % 12;\n if (years != 0) {\n result = result.withYears(years);\n }\n if (months != 0) {\n result = result.withMonths(months);\n }\n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Period normalizedStandard(PeriodType type) {\n type = DateTimeUtils.getPeriodType(type);\n long millis = getMillis(); \n millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND));\n millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE));\n millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR));\n millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY));\n millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK));\n Period result = new Period(millis, type, ISOChronology.getInstanceUTC());\n int years = getYears();\n int months = getMonths();\n if (years != 0 || months != 0) {\n years = FieldUtils.safeAdd(years, months / 12);\n months = months % 12;\n if (years != 0) {\n result = result.withYears(years);\n }\n if (months != 0) {\n result = result.withMonths(months);\n }\n }\n return result;\n }\n"}, "reference": " public Period normalizedStandard(PeriodType type) {\n type = DateTimeUtils.getPeriodType(type);\n long millis = getMillis(); \n millis += (((long) getSeconds()) * ((long) DateTimeConstants.MILLIS_PER_SECOND));\n millis += (((long) getMinutes()) * ((long) DateTimeConstants.MILLIS_PER_MINUTE));\n millis += (((long) getHours()) * ((long) DateTimeConstants.MILLIS_PER_HOUR));\n millis += (((long) getDays()) * ((long) DateTimeConstants.MILLIS_PER_DAY));\n millis += (((long) getWeeks()) * ((long) DateTimeConstants.MILLIS_PER_WEEK));\n Period result = new Period(millis, type, ISOChronology.getInstanceUTC());\n int years = getYears();\n int months = getMonths();\n if (years != 0 || months != 0) {\n long totalMonths = years * 12L + months;\n if (type.isSupported(DurationFieldType.YEARS_TYPE)) {\n int normalizedYears = FieldUtils.safeToInt(totalMonths / 12);\n result = result.withYears(normalizedYears);\n totalMonths = totalMonths - (normalizedYears * 12);\n }\n if (type.isSupported(DurationFieldType.MONTHS_TYPE)) {\n int normalizedMonths = FieldUtils.safeToInt(totalMonths);\n result = result.withMonths(normalizedMonths);\n totalMonths = totalMonths - normalizedMonths;\n }\n if (totalMonths != 0) {\n throw new UnsupportedOperationException(\"Unable to normalize as PeriodType is missing either years or months but period has a month/year amount: \" + toString());\n }\n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-5"}} {"sample_uid": "defects4j_function_repair::Mockito-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void verify(VerificationData data) {\n AssertionError error = null;\n timer.start();\n while (timer.isCounting()) {\n try {\n delegate.verify(data);\n if (returnOnSuccess) {\n return;\n } else {\n error = null;\n }\n } catch (MockitoAssertionError e) {\n error = handleVerifyException(e);\n }\n catch (org.mockito.exceptions.verification.junit.ArgumentsAreDifferent e) {\n error = handleVerifyException(e);\n }\n }\n if (error != null) {\n throw error;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void verify(VerificationData data) {\n AssertionError error = null;\n timer.start();\n while (timer.isCounting()) {\n try {\n delegate.verify(data);\n if (returnOnSuccess) {\n return;\n } else {\n error = null;\n }\n } catch (MockitoAssertionError e) {\n error = handleVerifyException(e);\n }\n catch (org.mockito.exceptions.verification.junit.ArgumentsAreDifferent e) {\n error = handleVerifyException(e);\n }\n }\n if (error != null) {\n throw error;\n }\n }\n"}, "reference": " public void verify(VerificationData data) {\n AssertionError error = null;\n timer.start();\n while (timer.isCounting()) {\n try {\n delegate.verify(data);\n if (returnOnSuccess) {\n return;\n } else {\n error = null;\n }\n } catch (MockitoAssertionError e) {\n error = handleVerifyException(e);\n }\n catch (AssertionError e) {\n error = handleVerifyException(e);\n }\n }\n if (error != null) {\n throw error;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-5"}} {"sample_uid": "defects4j_function_repair::Lang-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = Character.codePointCount(input, 0, input.length());\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n }\n else {\n for (int pt = 0; pt < consumed; pt++) {\n if (pos < len - 2) {\n pos += Character.charCount(Character.codePointAt(input, pos));\n } else {\n pos++;\n }\n }\n pos--;\n }\n pos++;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = Character.codePointCount(input, 0, input.length());\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n }\n else {\n for (int pt = 0; pt < consumed; pt++) {\n if (pos < len - 2) {\n pos += Character.charCount(Character.codePointAt(input, pos));\n } else {\n pos++;\n }\n }\n pos--;\n }\n pos++;\n }\n }\n"}, "reference": " public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = input.length();\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n pos+= c.length;\n continue;\n }\n for (int pt = 0; pt < consumed; pt++) {\n pos += Character.charCount(Character.codePointAt(input, pos));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-17"}} {"sample_uid": "defects4j_function_repair::Compress-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void close() throws IOException {\n if (!this.closed) {\n super.close();\n this.closed = true;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void close() throws IOException {\n if (!this.closed) {\n super.close();\n this.closed = true;\n }\n }\n"}, "reference": " public void close() throws IOException {\n if (!this.closed) {\n this.finish();\n super.close();\n this.closed = true;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-1"}} {"sample_uid": "defects4j_function_repair::Closure-22", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (parent.getType() == Token.COMMA) {\n Node gramps = parent.getParent();\n if (gramps.isCall() && parent == gramps.getFirstChild()) {\n if (n == parent.getFirstChild() && parent.getChildCount() == 2 && n.getNext().isName() && \"eval\".equals(n.getNext().getString())) {\n return;\n }\n }\n if (n == parent.getLastChild()) {\n for (Node an : parent.getAncestors()) {\n int ancestorType = an.getType();\n if (ancestorType == Token.COMMA)\n continue;\n if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK)\n return;\n else\n break;\n }\n }\n } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {\n if (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() ||\n n == parent.getFirstChild().getNext().getNext())) {\n } else {\n return;\n }\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (!isResultUsed &&\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n } else if (n.isExprResult()) {\n return;\n }\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (parent.getType() == Token.COMMA) {\n Node gramps = parent.getParent();\n if (gramps.isCall() && parent == gramps.getFirstChild()) {\n if (n == parent.getFirstChild() && parent.getChildCount() == 2 && n.getNext().isName() && \"eval\".equals(n.getNext().getString())) {\n return;\n }\n }\n if (n == parent.getLastChild()) {\n for (Node an : parent.getAncestors()) {\n int ancestorType = an.getType();\n if (ancestorType == Token.COMMA)\n continue;\n if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK)\n return;\n else\n break;\n }\n }\n } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {\n if (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() ||\n n == parent.getFirstChild().getNext().getNext())) {\n } else {\n return;\n }\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (!isResultUsed &&\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n } else if (n.isExprResult()) {\n return;\n }\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n"}, "reference": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (n.isExprResult() || n.isBlock()) {\n return;\n }\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (!isResultUsed &&\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-22"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-22"}} {"sample_uid": "defects4j_function_repair::JacksonCore-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException\n {\n _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));\n char[] outBuf = _textBuffer.getCurrentSegment();\n int outPtr = _textBuffer.getCurrentSegmentSize();\n final int maxCode = codes.length;\n while (true) {\n if (_inputPtr >= _inputEnd) {\n if (!_loadMore()) { \n break;\n }\n }\n char c = _inputBuffer[_inputPtr];\n int i = (int) c;\n if (i <= maxCode) {\n if (codes[i] != 0) {\n break;\n }\n } else if (!Character.isJavaIdentifierPart(c)) {\n break;\n }\n ++_inputPtr;\n hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;\n outBuf[outPtr++] = c;\n if (outPtr >= outBuf.length) {\n outBuf = _textBuffer.finishCurrentSegment();\n outPtr = 0;\n }\n }\n _textBuffer.setCurrentLength(outPtr);\n {\n TextBuffer tb = _textBuffer;\n char[] buf = tb.getTextBuffer();\n int start = tb.getTextOffset();\n int len = tb.size();\n return _symbols.findSymbol(buf, start, len, hash);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException\n {\n _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));\n char[] outBuf = _textBuffer.getCurrentSegment();\n int outPtr = _textBuffer.getCurrentSegmentSize();\n final int maxCode = codes.length;\n while (true) {\n if (_inputPtr >= _inputEnd) {\n if (!_loadMore()) { \n break;\n }\n }\n char c = _inputBuffer[_inputPtr];\n int i = (int) c;\n if (i <= maxCode) {\n if (codes[i] != 0) {\n break;\n }\n } else if (!Character.isJavaIdentifierPart(c)) {\n break;\n }\n ++_inputPtr;\n hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;\n outBuf[outPtr++] = c;\n if (outPtr >= outBuf.length) {\n outBuf = _textBuffer.finishCurrentSegment();\n outPtr = 0;\n }\n }\n _textBuffer.setCurrentLength(outPtr);\n {\n TextBuffer tb = _textBuffer;\n char[] buf = tb.getTextBuffer();\n int start = tb.getTextOffset();\n int len = tb.size();\n return _symbols.findSymbol(buf, start, len, hash);\n }\n }\n"}, "reference": " private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException\n {\n _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));\n char[] outBuf = _textBuffer.getCurrentSegment();\n int outPtr = _textBuffer.getCurrentSegmentSize();\n final int maxCode = codes.length;\n while (true) {\n if (_inputPtr >= _inputEnd) {\n if (!_loadMore()) { \n break;\n }\n }\n char c = _inputBuffer[_inputPtr];\n int i = (int) c;\n if (i < maxCode) {\n if (codes[i] != 0) {\n break;\n }\n } else if (!Character.isJavaIdentifierPart(c)) {\n break;\n }\n ++_inputPtr;\n hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;\n outBuf[outPtr++] = c;\n if (outPtr >= outBuf.length) {\n outBuf = _textBuffer.finishCurrentSegment();\n outPtr = 0;\n }\n }\n _textBuffer.setCurrentLength(outPtr);\n {\n TextBuffer tb = _textBuffer;\n char[] buf = tb.getTextBuffer();\n int start = tb.getTextOffset();\n int len = tb.size();\n return _symbols.findSymbol(buf, start, len, hash);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-25"}} {"sample_uid": "defects4j_function_repair::Lang-44", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(String val) throws NumberFormatException {\n if (val == null) {\n return null;\n }\n if (val.length() == 0) {\n throw new NumberFormatException(\"\\\"\\\" is not a valid number.\");\n }\n if (val.startsWith(\"--\")) {\n return null;\n }\n if (val.startsWith(\"0x\") || val.startsWith(\"-0x\")) {\n return createInteger(val);\n } \n char lastChar = val.charAt(val.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = val.indexOf('.');\n int expPos = val.indexOf('e') + val.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n dec = val.substring(decPos + 1, expPos);\n } else {\n dec = val.substring(decPos + 1);\n }\n mant = val.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = val.substring(0, expPos);\n } else {\n mant = val;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length() - 1);\n } else {\n exp = null;\n }\n String numeric = val.substring(0, val.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(val + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException e) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(val);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(val);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(val);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(val);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(val);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(val);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(String val) throws NumberFormatException {\n if (val == null) {\n return null;\n }\n if (val.length() == 0) {\n throw new NumberFormatException(\"\\\"\\\" is not a valid number.\");\n }\n if (val.startsWith(\"--\")) {\n return null;\n }\n if (val.startsWith(\"0x\") || val.startsWith(\"-0x\")) {\n return createInteger(val);\n } \n char lastChar = val.charAt(val.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = val.indexOf('.');\n int expPos = val.indexOf('e') + val.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n dec = val.substring(decPos + 1, expPos);\n } else {\n dec = val.substring(decPos + 1);\n }\n mant = val.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = val.substring(0, expPos);\n } else {\n mant = val;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length() - 1);\n } else {\n exp = null;\n }\n String numeric = val.substring(0, val.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(val + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException e) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(val);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(val);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(val);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(val);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(val);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(val);\n }\n }\n }\n"}, "reference": " public static Number createNumber(String val) throws NumberFormatException {\n if (val == null) {\n return null;\n }\n if (val.length() == 0) {\n throw new NumberFormatException(\"\\\"\\\" is not a valid number.\");\n }\n if (val.length() == 1 && !Character.isDigit(val.charAt(0))) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n if (val.startsWith(\"--\")) {\n return null;\n }\n if (val.startsWith(\"0x\") || val.startsWith(\"-0x\")) {\n return createInteger(val);\n } \n char lastChar = val.charAt(val.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = val.indexOf('.');\n int expPos = val.indexOf('e') + val.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n dec = val.substring(decPos + 1, expPos);\n } else {\n dec = val.substring(decPos + 1);\n }\n mant = val.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = val.substring(0, expPos);\n } else {\n mant = val;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length() - 1);\n } else {\n exp = null;\n }\n String numeric = val.substring(0, val.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(val + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException e) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(val + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < val.length() - 1) {\n exp = val.substring(expPos + 1, val.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(val);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(val);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(val);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(val);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(val);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(val);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-44"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-44"}} {"sample_uid": "defects4j_function_repair::Chart-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)\n throws CloneNotSupportedException {\n if (start == null) {\n throw new IllegalArgumentException(\"Null 'start' argument.\");\n }\n if (end == null) {\n throw new IllegalArgumentException(\"Null 'end' argument.\");\n }\n if (start.compareTo(end) > 0) {\n throw new IllegalArgumentException(\n \"Requires start on or before end.\");\n }\n boolean emptyRange = false;\n int startIndex = getIndex(start);\n if (startIndex < 0) {\n startIndex = -(startIndex + 1);\n if (startIndex == this.data.size()) {\n emptyRange = true; \n }\n }\n int endIndex = getIndex(end);\n if (endIndex < 0) { \n endIndex = -(endIndex + 1); \n endIndex = endIndex - 1; \n }\n if (endIndex < 0) {\n emptyRange = true;\n }\n if (emptyRange) {\n TimeSeries copy = (TimeSeries) super.clone();\n copy.data = new java.util.ArrayList();\n return copy;\n }\n else {\n return createCopy(startIndex, endIndex);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)\n throws CloneNotSupportedException {\n if (start == null) {\n throw new IllegalArgumentException(\"Null 'start' argument.\");\n }\n if (end == null) {\n throw new IllegalArgumentException(\"Null 'end' argument.\");\n }\n if (start.compareTo(end) > 0) {\n throw new IllegalArgumentException(\n \"Requires start on or before end.\");\n }\n boolean emptyRange = false;\n int startIndex = getIndex(start);\n if (startIndex < 0) {\n startIndex = -(startIndex + 1);\n if (startIndex == this.data.size()) {\n emptyRange = true; \n }\n }\n int endIndex = getIndex(end);\n if (endIndex < 0) { \n endIndex = -(endIndex + 1); \n endIndex = endIndex - 1; \n }\n if (endIndex < 0) {\n emptyRange = true;\n }\n if (emptyRange) {\n TimeSeries copy = (TimeSeries) super.clone();\n copy.data = new java.util.ArrayList();\n return copy;\n }\n else {\n return createCopy(startIndex, endIndex);\n }\n }\n"}, "reference": " public TimeSeries createCopy(RegularTimePeriod start, RegularTimePeriod end)\n throws CloneNotSupportedException {\n if (start == null) {\n throw new IllegalArgumentException(\"Null 'start' argument.\");\n }\n if (end == null) {\n throw new IllegalArgumentException(\"Null 'end' argument.\");\n }\n if (start.compareTo(end) > 0) {\n throw new IllegalArgumentException(\n \"Requires start on or before end.\");\n }\n boolean emptyRange = false;\n int startIndex = getIndex(start);\n if (startIndex < 0) {\n startIndex = -(startIndex + 1);\n if (startIndex == this.data.size()) {\n emptyRange = true; \n }\n }\n int endIndex = getIndex(end);\n if (endIndex < 0) { \n endIndex = -(endIndex + 1); \n endIndex = endIndex - 1; \n }\n if ((endIndex < 0) || (endIndex < startIndex)) {\n emptyRange = true;\n }\n if (emptyRange) {\n TimeSeries copy = (TimeSeries) super.clone();\n copy.data = new java.util.ArrayList();\n return copy;\n }\n else {\n return createCopy(startIndex, endIndex);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-9"}} {"sample_uid": "defects4j_function_repair::Closure-81", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Node processFunctionNode(FunctionNode functionNode) {\n Name name = functionNode.getFunctionName();\n Boolean isUnnamedFunction = false;\n if (name == null) {\n name = new Name();\n name.setIdentifier(\"\");\n isUnnamedFunction = true;\n }\n Node node = newNode(Token.FUNCTION);\n Node newName = transform(name);\n if (isUnnamedFunction) {\n newName.setLineno(functionNode.getLineno());\n int lpColumn = functionNode.getAbsolutePosition() +\n functionNode.getLp();\n newName.setCharno(position2charno(lpColumn));\n }\n node.addChildToBack(newName);\n Node lp = newNode(Token.LP);\n Name fnName = functionNode.getFunctionName();\n if (fnName != null) {\n lp.setLineno(fnName.getLineno());\n } else {\n lp.setLineno(functionNode.getLineno());\n }\n int lparenCharno = functionNode.getLp() +\n functionNode.getAbsolutePosition();\n lp.setCharno(position2charno(lparenCharno));\n for (AstNode param : functionNode.getParams()) {\n lp.addChildToBack(transform(param));\n }\n node.addChildToBack(lp);\n Node bodyNode = transform(functionNode.getBody());\n parseDirectives(bodyNode);\n node.addChildToBack(bodyNode);\n return node;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Node processFunctionNode(FunctionNode functionNode) {\n Name name = functionNode.getFunctionName();\n Boolean isUnnamedFunction = false;\n if (name == null) {\n name = new Name();\n name.setIdentifier(\"\");\n isUnnamedFunction = true;\n }\n Node node = newNode(Token.FUNCTION);\n Node newName = transform(name);\n if (isUnnamedFunction) {\n newName.setLineno(functionNode.getLineno());\n int lpColumn = functionNode.getAbsolutePosition() +\n functionNode.getLp();\n newName.setCharno(position2charno(lpColumn));\n }\n node.addChildToBack(newName);\n Node lp = newNode(Token.LP);\n Name fnName = functionNode.getFunctionName();\n if (fnName != null) {\n lp.setLineno(fnName.getLineno());\n } else {\n lp.setLineno(functionNode.getLineno());\n }\n int lparenCharno = functionNode.getLp() +\n functionNode.getAbsolutePosition();\n lp.setCharno(position2charno(lparenCharno));\n for (AstNode param : functionNode.getParams()) {\n lp.addChildToBack(transform(param));\n }\n node.addChildToBack(lp);\n Node bodyNode = transform(functionNode.getBody());\n parseDirectives(bodyNode);\n node.addChildToBack(bodyNode);\n return node;\n }\n"}, "reference": " Node processFunctionNode(FunctionNode functionNode) {\n Name name = functionNode.getFunctionName();\n Boolean isUnnamedFunction = false;\n if (name == null) {\n int functionType = functionNode.getFunctionType();\n if (functionType != FunctionNode.FUNCTION_EXPRESSION) {\n errorReporter.error(\n \"unnamed function statement\",\n sourceName,\n functionNode.getLineno(), \"\", 0);\n }\n name = new Name();\n name.setIdentifier(\"\");\n isUnnamedFunction = true;\n }\n Node node = newNode(Token.FUNCTION);\n Node newName = transform(name);\n if (isUnnamedFunction) {\n newName.setLineno(functionNode.getLineno());\n int lpColumn = functionNode.getAbsolutePosition() +\n functionNode.getLp();\n newName.setCharno(position2charno(lpColumn));\n }\n node.addChildToBack(newName);\n Node lp = newNode(Token.LP);\n Name fnName = functionNode.getFunctionName();\n if (fnName != null) {\n lp.setLineno(fnName.getLineno());\n } else {\n lp.setLineno(functionNode.getLineno());\n }\n int lparenCharno = functionNode.getLp() +\n functionNode.getAbsolutePosition();\n lp.setCharno(position2charno(lparenCharno));\n for (AstNode param : functionNode.getParams()) {\n lp.addChildToBack(transform(param));\n }\n node.addChildToBack(lp);\n Node bodyNode = transform(functionNode.getBody());\n parseDirectives(bodyNode);\n node.addChildToBack(bodyNode);\n return node;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-81"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-81"}} {"sample_uid": "defects4j_function_repair::Jsoup-50", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = null;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n }\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (docData.length() > 0 && docData.charAt(0) == UNICODE_BOM) {\n byteData.rewind();\n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n docData = docData.substring(1);\n charsetName = defaultCharset;\n doc = null;\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = null;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n }\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (docData.length() > 0 && docData.charAt(0) == UNICODE_BOM) {\n byteData.rewind();\n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n docData = docData.substring(1);\n charsetName = defaultCharset;\n doc = null;\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n"}, "reference": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n byteData.mark();\n byte[] bom = new byte[4];\n byteData.get(bom);\n byteData.rewind();\n if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF || \n bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { \n charsetName = \"UTF-32\"; \n } else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF || \n bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {\n charsetName = \"UTF-16\"; \n } else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) {\n charsetName = \"UTF-8\"; \n byteData.position(3); \n }\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = null;\n if (meta.hasAttr(\"http-equiv\")) {\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n }\n if (foundCharset == null && meta.hasAttr(\"charset\")) {\n try {\n if (Charset.isSupported(meta.attr(\"charset\"))) {\n foundCharset = meta.attr(\"charset\");\n }\n } catch (IllegalCharsetNameException e) {\n foundCharset = null;\n }\n }\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-50"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-50"}} {"sample_uid": "defects4j_function_repair::Jsoup-55", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void read(Tokeniser t, CharacterReader r) {\n char c = r.consume();\n switch (c) {\n case '>':\n t.tagPending.selfClosing = true;\n t.emitTagPending();\n t.transition(Data);\n break;\n case eof:\n t.eofError(this);\n t.transition(Data);\n break;\n default:\n t.error(this);\n t.transition(BeforeAttributeName);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void read(Tokeniser t, CharacterReader r) {\n char c = r.consume();\n switch (c) {\n case '>':\n t.tagPending.selfClosing = true;\n t.emitTagPending();\n t.transition(Data);\n break;\n case eof:\n t.eofError(this);\n t.transition(Data);\n break;\n default:\n t.error(this);\n t.transition(BeforeAttributeName);\n }\n }\n"}, "reference": " void read(Tokeniser t, CharacterReader r) {\n char c = r.consume();\n switch (c) {\n case '>':\n t.tagPending.selfClosing = true;\n t.emitTagPending();\n t.transition(Data);\n break;\n case eof:\n t.eofError(this);\n t.transition(Data);\n break;\n default:\n t.error(this);\n r.unconsume();\n t.transition(BeforeAttributeName);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-55"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-55"}} {"sample_uid": "defects4j_function_repair::Jsoup-49", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void addChildren(int index, Node... children) {\n Validate.noNullElements(children);\n ensureChildNodes();\n for (int i = children.length - 1; i >= 0; i--) {\n Node in = children[i];\n reparentChild(in);\n childNodes.add(index, in);\n }\n reindexChildren(index);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void addChildren(int index, Node... children) {\n Validate.noNullElements(children);\n ensureChildNodes();\n for (int i = children.length - 1; i >= 0; i--) {\n Node in = children[i];\n reparentChild(in);\n childNodes.add(index, in);\n }\n reindexChildren(index);\n }\n"}, "reference": " protected void addChildren(int index, Node... children) {\n Validate.noNullElements(children);\n ensureChildNodes();\n for (int i = children.length - 1; i >= 0; i--) {\n Node in = children[i];\n reparentChild(in);\n childNodes.add(index, in);\n reindexChildren(index);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-49"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-49"}} {"sample_uid": "defects4j_function_repair::Lang-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {\n if (cal1 == null || cal2 == null) {\n throw new IllegalArgumentException(\"The date must not be null\");\n }\n return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&\n cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&\n cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&\n cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&\n cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&\n cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&\n cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&\n cal1.getClass() == cal2.getClass());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {\n if (cal1 == null || cal2 == null) {\n throw new IllegalArgumentException(\"The date must not be null\");\n }\n return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&\n cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&\n cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&\n cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&\n cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&\n cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&\n cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&\n cal1.getClass() == cal2.getClass());\n }\n"}, "reference": " public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {\n if (cal1 == null || cal2 == null) {\n throw new IllegalArgumentException(\"The date must not be null\");\n }\n return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&\n cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&\n cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&\n cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) &&\n cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&\n cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&\n cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&\n cal1.getClass() == cal2.getClass());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-21"}} {"sample_uid": "defects4j_function_repair::Jsoup-43", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static Integer indexInList(Element search, List elements) {\n Validate.notNull(search);\n Validate.notNull(elements);\n for (int i = 0; i < elements.size(); i++) {\n E element = elements.get(i);\n if (element.equals(search))\n return i;\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static Integer indexInList(Element search, List elements) {\n Validate.notNull(search);\n Validate.notNull(elements);\n for (int i = 0; i < elements.size(); i++) {\n E element = elements.get(i);\n if (element.equals(search))\n return i;\n }\n return null;\n }\n"}, "reference": " private static Integer indexInList(Element search, List elements) {\n Validate.notNull(search);\n Validate.notNull(elements);\n for (int i = 0; i < elements.size(); i++) {\n E element = elements.get(i);\n if (element == search)\n return i;\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-43"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-43"}} {"sample_uid": "defects4j_function_repair::Cli-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected StringBuffer renderWrappedText(StringBuffer sb, int width, \n int nextLineTabStop, String text)\n {\n int pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(rtrim(text));\n return sb;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n if (nextLineTabStop >= width)\n {\n nextLineTabStop = width - 1;\n }\n final String padding = createPadding(nextLineTabStop);\n while (true)\n {\n text = padding + text.substring(pos).trim();\n pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(text);\n return sb;\n }\n if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) \n {\n pos = width;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected StringBuffer renderWrappedText(StringBuffer sb, int width, \n int nextLineTabStop, String text)\n {\n int pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(rtrim(text));\n return sb;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n if (nextLineTabStop >= width)\n {\n nextLineTabStop = width - 1;\n }\n final String padding = createPadding(nextLineTabStop);\n while (true)\n {\n text = padding + text.substring(pos).trim();\n pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(text);\n return sb;\n }\n if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) \n {\n pos = width;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n }\n }\n"}, "reference": " protected StringBuffer renderWrappedText(StringBuffer sb, int width, \n int nextLineTabStop, String text)\n {\n int pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(rtrim(text));\n return sb;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n if (nextLineTabStop >= width)\n {\n nextLineTabStop = 1;\n }\n final String padding = createPadding(nextLineTabStop);\n while (true)\n {\n text = padding + text.substring(pos).trim();\n pos = findWrapPos(text, width, 0);\n if (pos == -1)\n {\n sb.append(text);\n return sb;\n }\n if ( (text.length() > width) && (pos == nextLineTabStop - 1) ) \n {\n pos = width;\n }\n sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-25"}} {"sample_uid": "defects4j_function_repair::Lang-59", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {\n if (width > 0) {\n ensureCapacity(size + width);\n String str = (obj == null ? getNullText() : obj.toString());\n int strLen = str.length();\n if (strLen >= width) {\n str.getChars(0, strLen, buffer, size);\n } else {\n int padLen = width - strLen;\n str.getChars(0, strLen, buffer, size);\n for (int i = 0; i < padLen; i++) {\n buffer[size + strLen + i] = padChar;\n }\n }\n size += width;\n }\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {\n if (width > 0) {\n ensureCapacity(size + width);\n String str = (obj == null ? getNullText() : obj.toString());\n int strLen = str.length();\n if (strLen >= width) {\n str.getChars(0, strLen, buffer, size);\n } else {\n int padLen = width - strLen;\n str.getChars(0, strLen, buffer, size);\n for (int i = 0; i < padLen; i++) {\n buffer[size + strLen + i] = padChar;\n }\n }\n size += width;\n }\n return this;\n }\n"}, "reference": " public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {\n if (width > 0) {\n ensureCapacity(size + width);\n String str = (obj == null ? getNullText() : obj.toString());\n int strLen = str.length();\n if (strLen >= width) {\n str.getChars(0, width, buffer, size);\n } else {\n int padLen = width - strLen;\n str.getChars(0, strLen, buffer, size);\n for (int i = 0; i < padLen; i++) {\n buffer[size + strLen + i] = padChar;\n }\n }\n size += width;\n }\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-59"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-59"}} {"sample_uid": "defects4j_function_repair::Closure-118", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void handleObjectLit(NodeTraversal t, Node n) {\n for (Node child = n.getFirstChild();\n child != null;\n child = child.getNext()) {\n String name = child.getString();\n T type = typeSystem.getType(getScope(), n, name);\n Property prop = getProperty(name);\n if (!prop.scheduleRenaming(child,\n processProperty(t, prop, type, null))) {\n if (propertiesToErrorFor.containsKey(name)) {\n compiler.report(JSError.make(\n t.getSourceName(), child, propertiesToErrorFor.get(name),\n Warnings.INVALIDATION, name,\n (type == null ? \"null\" : type.toString()), n.toString(), \"\"));\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void handleObjectLit(NodeTraversal t, Node n) {\n for (Node child = n.getFirstChild();\n child != null;\n child = child.getNext()) {\n String name = child.getString();\n T type = typeSystem.getType(getScope(), n, name);\n Property prop = getProperty(name);\n if (!prop.scheduleRenaming(child,\n processProperty(t, prop, type, null))) {\n if (propertiesToErrorFor.containsKey(name)) {\n compiler.report(JSError.make(\n t.getSourceName(), child, propertiesToErrorFor.get(name),\n Warnings.INVALIDATION, name,\n (type == null ? \"null\" : type.toString()), n.toString(), \"\"));\n }\n }\n }\n }\n"}, "reference": " private void handleObjectLit(NodeTraversal t, Node n) {\n for (Node child = n.getFirstChild();\n child != null;\n child = child.getNext()) {\n if (child.isQuotedString()) {\n continue;\n }\n String name = child.getString();\n T type = typeSystem.getType(getScope(), n, name);\n Property prop = getProperty(name);\n if (!prop.scheduleRenaming(child,\n processProperty(t, prop, type, null))) {\n if (propertiesToErrorFor.containsKey(name)) {\n compiler.report(JSError.make(\n t.getSourceName(), child, propertiesToErrorFor.get(name),\n Warnings.INVALIDATION, name,\n (type == null ? \"null\" : type.toString()), n.toString(), \"\"));\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-118"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-118"}} {"sample_uid": "defects4j_function_repair::JacksonCore-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public char[] expandCurrentSegment()\n {\n final char[] curr = _currentSegment;\n final int len = curr.length;\n int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1));\n return (_currentSegment = Arrays.copyOf(curr, newLen));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public char[] expandCurrentSegment()\n {\n final char[] curr = _currentSegment;\n final int len = curr.length;\n int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1));\n return (_currentSegment = Arrays.copyOf(curr, newLen));\n }\n"}, "reference": " public char[] expandCurrentSegment()\n {\n final char[] curr = _currentSegment;\n final int len = curr.length;\n int newLen = len + (len >> 1);\n if (newLen > MAX_SEGMENT_LEN) {\n newLen = len + (len >> 2);\n }\n return (_currentSegment = Arrays.copyOf(curr, newLen));\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-4"}} {"sample_uid": "defects4j_function_repair::Closure-133", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private String getRemainingJSDocLine() {\n String result = stream.getRemainingJSDocLine();\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private String getRemainingJSDocLine() {\n String result = stream.getRemainingJSDocLine();\n return result;\n }\n"}, "reference": " private String getRemainingJSDocLine() {\n String result = stream.getRemainingJSDocLine();\n unreadToken = NO_UNREAD_TOKEN;\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-133"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-133"}} {"sample_uid": "defects4j_function_repair::Jsoup-80", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void insert(Token.Comment commentToken) {\n Comment comment = new Comment(commentToken.getData());\n Node insert = comment;\n if (commentToken.bogus) { \n String data = comment.getData();\n if (data.length() > 1 && (data.startsWith(\"!\") || data.startsWith(\"?\"))) {\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri, Parser.xmlParser());\n Element el = doc.child(0);\n insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith(\"!\"));\n insert.attributes().addAll(el.attributes());\n }\n }\n insertNode(insert);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void insert(Token.Comment commentToken) {\n Comment comment = new Comment(commentToken.getData());\n Node insert = comment;\n if (commentToken.bogus) { \n String data = comment.getData();\n if (data.length() > 1 && (data.startsWith(\"!\") || data.startsWith(\"?\"))) {\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri, Parser.xmlParser());\n Element el = doc.child(0);\n insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith(\"!\"));\n insert.attributes().addAll(el.attributes());\n }\n }\n insertNode(insert);\n }\n"}, "reference": " void insert(Token.Comment commentToken) {\n Comment comment = new Comment(commentToken.getData());\n Node insert = comment;\n if (commentToken.bogus) { \n String data = comment.getData();\n if (data.length() > 1 && (data.startsWith(\"!\") || data.startsWith(\"?\"))) {\n Document doc = Jsoup.parse(\"<\" + data.substring(1, data.length() -1) + \">\", baseUri, Parser.xmlParser());\n if (doc.childNodeSize() > 0) {\n Element el = doc.child(0);\n insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith(\"!\"));\n insert.attributes().addAll(el.attributes());\n } \n }\n }\n insertNode(insert);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-80"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-80"}} {"sample_uid": "defects4j_function_repair::Math-48", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n"}, "reference": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n if (x == x1) {\n throw new ConvergenceException();\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-48"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-48"}} {"sample_uid": "defects4j_function_repair::Closure-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private FlowScope traverseNew(Node n, FlowScope scope) {\n Node constructor = n.getFirstChild();\n scope = traverse(constructor, scope);\n JSType constructorType = constructor.getJSType();\n JSType type = null;\n if (constructorType != null) {\n constructorType = constructorType.restrictByNotNullOrUndefined();\n if (constructorType.isUnknownType()) {\n type = getNativeType(UNKNOWN_TYPE);\n } else {\n FunctionType ct = constructorType.toMaybeFunctionType();\n if (ct == null && constructorType instanceof FunctionType) {\n ct = (FunctionType) constructorType;\n }\n if (ct != null && ct.isConstructor()) {\n type = ct.getInstanceType();\n }\n }\n }\n n.setJSType(type);\n for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) {\n scope = traverse(arg, scope);\n }\n return scope;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private FlowScope traverseNew(Node n, FlowScope scope) {\n Node constructor = n.getFirstChild();\n scope = traverse(constructor, scope);\n JSType constructorType = constructor.getJSType();\n JSType type = null;\n if (constructorType != null) {\n constructorType = constructorType.restrictByNotNullOrUndefined();\n if (constructorType.isUnknownType()) {\n type = getNativeType(UNKNOWN_TYPE);\n } else {\n FunctionType ct = constructorType.toMaybeFunctionType();\n if (ct == null && constructorType instanceof FunctionType) {\n ct = (FunctionType) constructorType;\n }\n if (ct != null && ct.isConstructor()) {\n type = ct.getInstanceType();\n }\n }\n }\n n.setJSType(type);\n for (Node arg = constructor.getNext(); arg != null; arg = arg.getNext()) {\n scope = traverse(arg, scope);\n }\n return scope;\n }\n"}, "reference": " private FlowScope traverseNew(Node n, FlowScope scope) {\n scope = traverseChildren(n, scope);\n Node constructor = n.getFirstChild();\n JSType constructorType = constructor.getJSType();\n JSType type = null;\n if (constructorType != null) {\n constructorType = constructorType.restrictByNotNullOrUndefined();\n if (constructorType.isUnknownType()) {\n type = getNativeType(UNKNOWN_TYPE);\n } else {\n FunctionType ct = constructorType.toMaybeFunctionType();\n if (ct == null && constructorType instanceof FunctionType) {\n ct = (FunctionType) constructorType;\n }\n if (ct != null && ct.isConstructor()) {\n type = ct.getInstanceType();\n backwardsInferenceFromCallSite(n, ct);\n }\n }\n }\n n.setJSType(type);\n return scope;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-25"}} {"sample_uid": "defects4j_function_repair::Time-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Partial with(DateTimeFieldType fieldType, int value) {\n if (fieldType == null) {\n throw new IllegalArgumentException(\"The field type must not be null\");\n }\n int index = indexOf(fieldType);\n if (index == -1) {\n DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1];\n int[] newValues = new int[newTypes.length];\n int i = 0;\n DurationField unitField = fieldType.getDurationType().getField(iChronology);\n if (unitField.isSupported()) {\n for (; i < iTypes.length; i++) {\n DateTimeFieldType loopType = iTypes[i];\n DurationField loopUnitField = loopType.getDurationType().getField(iChronology);\n if (loopUnitField.isSupported()) {\n int compare = unitField.compareTo(loopUnitField);\n if (compare > 0) {\n break;\n } else if (compare == 0) {\n DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology);\n DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology);\n if (rangeField.compareTo(loopRangeField) > 0) {\n break;\n }\n }\n }\n }\n }\n System.arraycopy(iTypes, 0, newTypes, 0, i);\n System.arraycopy(iValues, 0, newValues, 0, i);\n newTypes[i] = fieldType;\n newValues[i] = value;\n System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1);\n System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1);\n Partial newPartial = new Partial(iChronology, newTypes, newValues);\n iChronology.validate(newPartial, newValues);\n return newPartial;\n }\n if (value == getValue(index)) {\n return this;\n }\n int[] newValues = getValues();\n newValues = getField(index).set(this, index, newValues, value);\n return new Partial(this, newValues);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Partial with(DateTimeFieldType fieldType, int value) {\n if (fieldType == null) {\n throw new IllegalArgumentException(\"The field type must not be null\");\n }\n int index = indexOf(fieldType);\n if (index == -1) {\n DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1];\n int[] newValues = new int[newTypes.length];\n int i = 0;\n DurationField unitField = fieldType.getDurationType().getField(iChronology);\n if (unitField.isSupported()) {\n for (; i < iTypes.length; i++) {\n DateTimeFieldType loopType = iTypes[i];\n DurationField loopUnitField = loopType.getDurationType().getField(iChronology);\n if (loopUnitField.isSupported()) {\n int compare = unitField.compareTo(loopUnitField);\n if (compare > 0) {\n break;\n } else if (compare == 0) {\n DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology);\n DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology);\n if (rangeField.compareTo(loopRangeField) > 0) {\n break;\n }\n }\n }\n }\n }\n System.arraycopy(iTypes, 0, newTypes, 0, i);\n System.arraycopy(iValues, 0, newValues, 0, i);\n newTypes[i] = fieldType;\n newValues[i] = value;\n System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1);\n System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1);\n Partial newPartial = new Partial(iChronology, newTypes, newValues);\n iChronology.validate(newPartial, newValues);\n return newPartial;\n }\n if (value == getValue(index)) {\n return this;\n }\n int[] newValues = getValues();\n newValues = getField(index).set(this, index, newValues, value);\n return new Partial(this, newValues);\n }\n"}, "reference": " public Partial with(DateTimeFieldType fieldType, int value) {\n if (fieldType == null) {\n throw new IllegalArgumentException(\"The field type must not be null\");\n }\n int index = indexOf(fieldType);\n if (index == -1) {\n DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1];\n int[] newValues = new int[newTypes.length];\n int i = 0;\n DurationField unitField = fieldType.getDurationType().getField(iChronology);\n if (unitField.isSupported()) {\n for (; i < iTypes.length; i++) {\n DateTimeFieldType loopType = iTypes[i];\n DurationField loopUnitField = loopType.getDurationType().getField(iChronology);\n if (loopUnitField.isSupported()) {\n int compare = unitField.compareTo(loopUnitField);\n if (compare > 0) {\n break;\n } else if (compare == 0) {\n DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology);\n DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology);\n if (rangeField.compareTo(loopRangeField) > 0) {\n break;\n }\n }\n }\n }\n }\n System.arraycopy(iTypes, 0, newTypes, 0, i);\n System.arraycopy(iValues, 0, newValues, 0, i);\n newTypes[i] = fieldType;\n newValues[i] = value;\n System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1);\n System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1);\n Partial newPartial = new Partial(newTypes, newValues, iChronology);\n iChronology.validate(newPartial, newValues);\n return newPartial;\n }\n if (value == getValue(index)) {\n return this;\n }\n int[] newValues = getValues();\n newValues = getField(index).set(this, index, newValues, value);\n return new Partial(this, newValues);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-4"}} {"sample_uid": "defects4j_function_repair::Math-85", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static double[] bracket(UnivariateRealFunction function,\n double initial, double lowerBound, double upperBound, \n int maximumIterations) throws ConvergenceException, \n FunctionEvaluationException {\n if (function == null) {\n throw MathRuntimeException.createIllegalArgumentException(\"function is null\");\n }\n if (maximumIterations <= 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"bad value for maximum iterations number: {0}\", maximumIterations);\n }\n if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}\",\n lowerBound, initial, upperBound);\n }\n double a = initial;\n double b = initial;\n double fa;\n double fb;\n int numIterations = 0 ;\n do {\n a = Math.max(a - 1.0, lowerBound);\n b = Math.min(b + 1.0, upperBound);\n fa = function.value(a);\n fb = function.value(b);\n numIterations++ ;\n } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && \n ((a > lowerBound) || (b < upperBound)));\n if (fa * fb >= 0.0 ) {\n throw new ConvergenceException(\n \"number of iterations={0}, maximum iterations={1}, \" +\n \"initial={2}, lower bound={3}, upper bound={4}, final a value={5}, \" +\n \"final b value={6}, f(a)={7}, f(b)={8}\",\n numIterations, maximumIterations, initial,\n lowerBound, upperBound, a, b, fa, fb);\n }\n return new double[]{a, b};\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static double[] bracket(UnivariateRealFunction function,\n double initial, double lowerBound, double upperBound, \n int maximumIterations) throws ConvergenceException, \n FunctionEvaluationException {\n if (function == null) {\n throw MathRuntimeException.createIllegalArgumentException(\"function is null\");\n }\n if (maximumIterations <= 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"bad value for maximum iterations number: {0}\", maximumIterations);\n }\n if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}\",\n lowerBound, initial, upperBound);\n }\n double a = initial;\n double b = initial;\n double fa;\n double fb;\n int numIterations = 0 ;\n do {\n a = Math.max(a - 1.0, lowerBound);\n b = Math.min(b + 1.0, upperBound);\n fa = function.value(a);\n fb = function.value(b);\n numIterations++ ;\n } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && \n ((a > lowerBound) || (b < upperBound)));\n if (fa * fb >= 0.0 ) {\n throw new ConvergenceException(\n \"number of iterations={0}, maximum iterations={1}, \" +\n \"initial={2}, lower bound={3}, upper bound={4}, final a value={5}, \" +\n \"final b value={6}, f(a)={7}, f(b)={8}\",\n numIterations, maximumIterations, initial,\n lowerBound, upperBound, a, b, fa, fb);\n }\n return new double[]{a, b};\n }\n"}, "reference": " public static double[] bracket(UnivariateRealFunction function,\n double initial, double lowerBound, double upperBound, \n int maximumIterations) throws ConvergenceException, \n FunctionEvaluationException {\n if (function == null) {\n throw MathRuntimeException.createIllegalArgumentException(\"function is null\");\n }\n if (maximumIterations <= 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"bad value for maximum iterations number: {0}\", maximumIterations);\n }\n if (initial < lowerBound || initial > upperBound || lowerBound >= upperBound) {\n throw MathRuntimeException.createIllegalArgumentException(\n \"invalid bracketing parameters: lower bound={0}, initial={1}, upper bound={2}\",\n lowerBound, initial, upperBound);\n }\n double a = initial;\n double b = initial;\n double fa;\n double fb;\n int numIterations = 0 ;\n do {\n a = Math.max(a - 1.0, lowerBound);\n b = Math.min(b + 1.0, upperBound);\n fa = function.value(a);\n fb = function.value(b);\n numIterations++ ;\n } while ((fa * fb > 0.0) && (numIterations < maximumIterations) && \n ((a > lowerBound) || (b < upperBound)));\n if (fa * fb > 0.0 ) {\n throw new ConvergenceException(\n \"number of iterations={0}, maximum iterations={1}, \" +\n \"initial={2}, lower bound={3}, upper bound={4}, final a value={5}, \" +\n \"final b value={6}, f(a)={7}, f(b)={8}\",\n numIterations, maximumIterations, initial,\n lowerBound, upperBound, a, b, fa, fb);\n }\n return new double[]{a, b};\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-85"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-85"}} {"sample_uid": "defects4j_function_repair::Lang-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) {\n boolean wasWhite= false;\n for(int i= 0; i 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static void modify(Calendar val, int field, boolean round) {\n if (val.get(Calendar.YEAR) > 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n"}, "reference": " private static void modify(Calendar val, int field, boolean round) {\n if (val.get(Calendar.YEAR) > 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n if (field == Calendar.MILLISECOND) {\n return;\n }\n Date date = val.getTime();\n long time = date.getTime();\n boolean done = false;\n int millisecs = val.get(Calendar.MILLISECOND);\n if (!round || millisecs < 500) {\n time = time - millisecs;\n if (field == Calendar.SECOND) {\n done = true;\n }\n }\n int seconds = val.get(Calendar.SECOND);\n if (!done && (!round || seconds < 30)) {\n time = time - (seconds * 1000L);\n if (field == Calendar.MINUTE) {\n done = true;\n }\n }\n int minutes = val.get(Calendar.MINUTE);\n if (!done && (!round || minutes < 30)) {\n time = time - (minutes * 60000L);\n }\n if (date.getTime() != time) {\n date.setTime(time);\n val.setTime(date);\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n if (offset != 0) {\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-65"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-65"}} {"sample_uid": "defects4j_function_repair::JacksonCore-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void writeEmbeddedObject(Object object) throws IOException {\n throw new JsonGenerationException(\"No native support for writing embedded objects\",\n this);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void writeEmbeddedObject(Object object) throws IOException {\n throw new JsonGenerationException(\"No native support for writing embedded objects\",\n this);\n }\n"}, "reference": " public void writeEmbeddedObject(Object object) throws IOException {\n if (object == null) {\n writeNull();\n return;\n }\n if (object instanceof byte[]) {\n writeBinary((byte[]) object);\n return;\n }\n throw new JsonGenerationException(\"No native support for writing embedded objects of type \"\n +object.getClass().getName(),\n this);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-20"}} {"sample_uid": "defects4j_function_repair::Closure-61", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean functionCallHasSideEffects(\n Node callNode, @Nullable AbstractCompiler compiler) {\n if (callNode.getType() != Token.CALL) {\n throw new IllegalStateException(\n \"Expected CALL node, got \" + Token.name(callNode.getType()));\n }\n if (callNode.isNoSideEffectsCall()) {\n return false;\n }\n Node nameNode = callNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n String name = nameNode.getString();\n if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) {\n return false;\n }\n } else if (nameNode.getType() == Token.GETPROP) {\n if (callNode.hasOneChild()\n && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains(\n nameNode.getLastChild().getString())) {\n return false;\n }\n if (callNode.isOnlyModifiesThisCall()\n && evaluatesToLocalValue(nameNode.getFirstChild())) {\n return false;\n }\n if (compiler != null && !compiler.hasRegExpGlobalReferences()) {\n if (nameNode.getFirstChild().getType() == Token.REGEXP\n && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) {\n return false;\n } else if (nameNode.getFirstChild().getType() == Token.STRING\n && STRING_REGEXP_METHODS.contains(\n nameNode.getLastChild().getString())) {\n Node param = nameNode.getNext();\n if (param != null &&\n (param.getType() == Token.STRING\n || param.getType() == Token.REGEXP))\n return false;\n }\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean functionCallHasSideEffects(\n Node callNode, @Nullable AbstractCompiler compiler) {\n if (callNode.getType() != Token.CALL) {\n throw new IllegalStateException(\n \"Expected CALL node, got \" + Token.name(callNode.getType()));\n }\n if (callNode.isNoSideEffectsCall()) {\n return false;\n }\n Node nameNode = callNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n String name = nameNode.getString();\n if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) {\n return false;\n }\n } else if (nameNode.getType() == Token.GETPROP) {\n if (callNode.hasOneChild()\n && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains(\n nameNode.getLastChild().getString())) {\n return false;\n }\n if (callNode.isOnlyModifiesThisCall()\n && evaluatesToLocalValue(nameNode.getFirstChild())) {\n return false;\n }\n if (compiler != null && !compiler.hasRegExpGlobalReferences()) {\n if (nameNode.getFirstChild().getType() == Token.REGEXP\n && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) {\n return false;\n } else if (nameNode.getFirstChild().getType() == Token.STRING\n && STRING_REGEXP_METHODS.contains(\n nameNode.getLastChild().getString())) {\n Node param = nameNode.getNext();\n if (param != null &&\n (param.getType() == Token.STRING\n || param.getType() == Token.REGEXP))\n return false;\n }\n }\n }\n return true;\n }\n"}, "reference": " static boolean functionCallHasSideEffects(\n Node callNode, @Nullable AbstractCompiler compiler) {\n if (callNode.getType() != Token.CALL) {\n throw new IllegalStateException(\n \"Expected CALL node, got \" + Token.name(callNode.getType()));\n }\n if (callNode.isNoSideEffectsCall()) {\n return false;\n }\n Node nameNode = callNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n String name = nameNode.getString();\n if (BUILTIN_FUNCTIONS_WITHOUT_SIDEEFFECTS.contains(name)) {\n return false;\n }\n } else if (nameNode.getType() == Token.GETPROP) {\n if (callNode.hasOneChild()\n && OBJECT_METHODS_WITHOUT_SIDEEFFECTS.contains(\n nameNode.getLastChild().getString())) {\n return false;\n }\n if (callNode.isOnlyModifiesThisCall()\n && evaluatesToLocalValue(nameNode.getFirstChild())) {\n return false;\n }\n if (nameNode.getFirstChild().getType() == Token.NAME) {\n String namespaceName = nameNode.getFirstChild().getString();\n if (namespaceName.equals(\"Math\")) {\n return false;\n }\n }\n if (compiler != null && !compiler.hasRegExpGlobalReferences()) {\n if (nameNode.getFirstChild().getType() == Token.REGEXP\n && REGEXP_METHODS.contains(nameNode.getLastChild().getString())) {\n return false;\n } else if (nameNode.getFirstChild().getType() == Token.STRING\n && STRING_REGEXP_METHODS.contains(\n nameNode.getLastChild().getString())) {\n Node param = nameNode.getNext();\n if (param != null &&\n (param.getType() == Token.STRING\n || param.getType() == Token.REGEXP))\n return false;\n }\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-61"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-61"}} {"sample_uid": "defects4j_function_repair::Closure-161", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (right.getType() != Token.NUMBER) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node elem = left.getFirstChild();\n for (int i = 0; elem != null && i < intIndex; i++) {\n elem = elem.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.getType() == Token.EMPTY) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (right.getType() != Token.NUMBER) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node elem = left.getFirstChild();\n for (int i = 0; elem != null && i < intIndex; i++) {\n elem = elem.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.getType() == Token.EMPTY) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n"}, "reference": " private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (isAssignmentTarget(n)) {\n return n;\n }\n if (right.getType() != Token.NUMBER) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node elem = left.getFirstChild();\n for (int i = 0; elem != null && i < intIndex; i++) {\n elem = elem.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.getType() == Token.EMPTY) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-161"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-161"}} {"sample_uid": "defects4j_function_repair::Lang-49", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Fraction reduce() {\n int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);\n if (gcd == 1) {\n return this;\n }\n return Fraction.getFraction(numerator / gcd, denominator / gcd);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Fraction reduce() {\n int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);\n if (gcd == 1) {\n return this;\n }\n return Fraction.getFraction(numerator / gcd, denominator / gcd);\n }\n"}, "reference": " public Fraction reduce() {\n if (numerator == 0) {\n return equals(ZERO) ? this : ZERO;\n }\n int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);\n if (gcd == 1) {\n return this;\n }\n return Fraction.getFraction(numerator / gcd, denominator / gcd);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-49"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-49"}} {"sample_uid": "defects4j_function_repair::Lang-55", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void stop() {\n if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {\n throw new IllegalStateException(\"Stopwatch is not running. \");\n }\n stopTime = System.currentTimeMillis();\n this.runningState = STATE_STOPPED;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void stop() {\n if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {\n throw new IllegalStateException(\"Stopwatch is not running. \");\n }\n stopTime = System.currentTimeMillis();\n this.runningState = STATE_STOPPED;\n }\n"}, "reference": " public void stop() {\n if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {\n throw new IllegalStateException(\"Stopwatch is not running. \");\n }\n if(this.runningState == STATE_RUNNING) {\n stopTime = System.currentTimeMillis();\n }\n this.runningState = STATE_STOPPED;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-55"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-55"}} {"sample_uid": "defects4j_function_repair::Closure-53", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void replaceAssignmentExpression(Var v, Reference ref,\n Map varmap) {\n List nodes = Lists.newArrayList();\n Node val = ref.getAssignedValue();\n blacklistVarReferencesInTree(val, v.scope);\n Preconditions.checkState(val.getType() == Token.OBJECTLIT);\n Set all = Sets.newLinkedHashSet(varmap.keySet());\n for (Node key = val.getFirstChild(); key != null;\n key = key.getNext()) {\n String var = key.getString();\n Node value = key.removeFirstChild();\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)), value));\n all.remove(var);\n }\n for (String var : all) {\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)),\n NodeUtil.newUndefinedNode(null)));\n }\n Node replacement;\n nodes.add(new Node(Token.TRUE));\n nodes = Lists.reverse(nodes);\n replacement = new Node(Token.COMMA);\n Node cur = replacement;\n int i;\n for (i = 0; i < nodes.size() - 2; i++) {\n cur.addChildToFront(nodes.get(i));\n Node t = new Node(Token.COMMA);\n cur.addChildToFront(t);\n cur = t;\n }\n cur.addChildToFront(nodes.get(i));\n cur.addChildToFront(nodes.get(i + 1));\n Node replace = ref.getParent();\n replacement.copyInformationFromForTree(replace);\n if (replace.getType() == Token.VAR) {\n replace.getParent().replaceChild(\n replace, NodeUtil.newExpr(replacement));\n } else {\n replace.getParent().replaceChild(replace, replacement);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void replaceAssignmentExpression(Var v, Reference ref,\n Map varmap) {\n List nodes = Lists.newArrayList();\n Node val = ref.getAssignedValue();\n blacklistVarReferencesInTree(val, v.scope);\n Preconditions.checkState(val.getType() == Token.OBJECTLIT);\n Set all = Sets.newLinkedHashSet(varmap.keySet());\n for (Node key = val.getFirstChild(); key != null;\n key = key.getNext()) {\n String var = key.getString();\n Node value = key.removeFirstChild();\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)), value));\n all.remove(var);\n }\n for (String var : all) {\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)),\n NodeUtil.newUndefinedNode(null)));\n }\n Node replacement;\n nodes.add(new Node(Token.TRUE));\n nodes = Lists.reverse(nodes);\n replacement = new Node(Token.COMMA);\n Node cur = replacement;\n int i;\n for (i = 0; i < nodes.size() - 2; i++) {\n cur.addChildToFront(nodes.get(i));\n Node t = new Node(Token.COMMA);\n cur.addChildToFront(t);\n cur = t;\n }\n cur.addChildToFront(nodes.get(i));\n cur.addChildToFront(nodes.get(i + 1));\n Node replace = ref.getParent();\n replacement.copyInformationFromForTree(replace);\n if (replace.getType() == Token.VAR) {\n replace.getParent().replaceChild(\n replace, NodeUtil.newExpr(replacement));\n } else {\n replace.getParent().replaceChild(replace, replacement);\n }\n }\n"}, "reference": " private void replaceAssignmentExpression(Var v, Reference ref,\n Map varmap) {\n List nodes = Lists.newArrayList();\n Node val = ref.getAssignedValue();\n blacklistVarReferencesInTree(val, v.scope);\n Preconditions.checkState(val.getType() == Token.OBJECTLIT);\n Set all = Sets.newLinkedHashSet(varmap.keySet());\n for (Node key = val.getFirstChild(); key != null;\n key = key.getNext()) {\n String var = key.getString();\n Node value = key.removeFirstChild();\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)), value));\n all.remove(var);\n }\n for (String var : all) {\n nodes.add(\n new Node(Token.ASSIGN,\n Node.newString(Token.NAME, varmap.get(var)),\n NodeUtil.newUndefinedNode(null)));\n }\n Node replacement;\n if (nodes.isEmpty()) {\n replacement = new Node(Token.TRUE);\n } else {\n nodes.add(new Node(Token.TRUE));\n nodes = Lists.reverse(nodes);\n replacement = new Node(Token.COMMA);\n Node cur = replacement;\n int i;\n for (i = 0; i < nodes.size() - 2; i++) {\n cur.addChildToFront(nodes.get(i));\n Node t = new Node(Token.COMMA);\n cur.addChildToFront(t);\n cur = t;\n }\n cur.addChildToFront(nodes.get(i));\n cur.addChildToFront(nodes.get(i + 1));\n }\n Node replace = ref.getParent();\n replacement.copyInformationFromForTree(replace);\n if (replace.getType() == Token.VAR) {\n replace.getParent().replaceChild(\n replace, NodeUtil.newExpr(replacement));\n } else {\n replace.getParent().replaceChild(replace, replacement);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-53"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-53"}} {"sample_uid": "defects4j_function_repair::Chart-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Range getDataRange(ValueAxis axis) {\n Range result = null;\n List mappedDatasets = new ArrayList();\n List includedAnnotations = new ArrayList();\n boolean isDomainAxis = true;\n int domainIndex = getDomainAxisIndex(axis);\n if (domainIndex >= 0) {\n isDomainAxis = true;\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(\n new Integer(domainIndex)));\n if (domainIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n int rangeIndex = getRangeAxisIndex(axis);\n if (rangeIndex >= 0) {\n isDomainAxis = false;\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(\n new Integer(rangeIndex)));\n if (rangeIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n Iterator iterator = mappedDatasets.iterator();\n while (iterator.hasNext()) {\n XYDataset d = (XYDataset) iterator.next();\n if (d != null) {\n XYItemRenderer r = getRendererForDataset(d);\n if (isDomainAxis) {\n if (r != null) {\n result = Range.combine(result, r.findDomainBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findDomainBounds(d));\n }\n }\n else {\n if (r != null) {\n result = Range.combine(result, r.findRangeBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findRangeBounds(d));\n }\n }\n Collection c = r.getAnnotations();\n Iterator i = c.iterator();\n while (i.hasNext()) {\n XYAnnotation a = (XYAnnotation) i.next();\n if (a instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(a);\n }\n }\n }\n }\n Iterator it = includedAnnotations.iterator();\n while (it.hasNext()) {\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\n if (xyabi.getIncludeInDataBounds()) {\n if (isDomainAxis) {\n result = Range.combine(result, xyabi.getXRange());\n }\n else {\n result = Range.combine(result, xyabi.getYRange());\n }\n }\n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Range getDataRange(ValueAxis axis) {\n Range result = null;\n List mappedDatasets = new ArrayList();\n List includedAnnotations = new ArrayList();\n boolean isDomainAxis = true;\n int domainIndex = getDomainAxisIndex(axis);\n if (domainIndex >= 0) {\n isDomainAxis = true;\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(\n new Integer(domainIndex)));\n if (domainIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n int rangeIndex = getRangeAxisIndex(axis);\n if (rangeIndex >= 0) {\n isDomainAxis = false;\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(\n new Integer(rangeIndex)));\n if (rangeIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n Iterator iterator = mappedDatasets.iterator();\n while (iterator.hasNext()) {\n XYDataset d = (XYDataset) iterator.next();\n if (d != null) {\n XYItemRenderer r = getRendererForDataset(d);\n if (isDomainAxis) {\n if (r != null) {\n result = Range.combine(result, r.findDomainBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findDomainBounds(d));\n }\n }\n else {\n if (r != null) {\n result = Range.combine(result, r.findRangeBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findRangeBounds(d));\n }\n }\n Collection c = r.getAnnotations();\n Iterator i = c.iterator();\n while (i.hasNext()) {\n XYAnnotation a = (XYAnnotation) i.next();\n if (a instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(a);\n }\n }\n }\n }\n Iterator it = includedAnnotations.iterator();\n while (it.hasNext()) {\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\n if (xyabi.getIncludeInDataBounds()) {\n if (isDomainAxis) {\n result = Range.combine(result, xyabi.getXRange());\n }\n else {\n result = Range.combine(result, xyabi.getYRange());\n }\n }\n }\n return result;\n }\n"}, "reference": " public Range getDataRange(ValueAxis axis) {\n Range result = null;\n List mappedDatasets = new ArrayList();\n List includedAnnotations = new ArrayList();\n boolean isDomainAxis = true;\n int domainIndex = getDomainAxisIndex(axis);\n if (domainIndex >= 0) {\n isDomainAxis = true;\n mappedDatasets.addAll(getDatasetsMappedToDomainAxis(\n new Integer(domainIndex)));\n if (domainIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n int rangeIndex = getRangeAxisIndex(axis);\n if (rangeIndex >= 0) {\n isDomainAxis = false;\n mappedDatasets.addAll(getDatasetsMappedToRangeAxis(\n new Integer(rangeIndex)));\n if (rangeIndex == 0) {\n Iterator iterator = this.annotations.iterator();\n while (iterator.hasNext()) {\n XYAnnotation annotation = (XYAnnotation) iterator.next();\n if (annotation instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(annotation);\n }\n }\n }\n }\n Iterator iterator = mappedDatasets.iterator();\n while (iterator.hasNext()) {\n XYDataset d = (XYDataset) iterator.next();\n if (d != null) {\n XYItemRenderer r = getRendererForDataset(d);\n if (isDomainAxis) {\n if (r != null) {\n result = Range.combine(result, r.findDomainBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findDomainBounds(d));\n }\n }\n else {\n if (r != null) {\n result = Range.combine(result, r.findRangeBounds(d));\n }\n else {\n result = Range.combine(result,\n DatasetUtilities.findRangeBounds(d));\n }\n }\n if (r != null) {\n Collection c = r.getAnnotations();\n Iterator i = c.iterator();\n while (i.hasNext()) {\n XYAnnotation a = (XYAnnotation) i.next();\n if (a instanceof XYAnnotationBoundsInfo) {\n includedAnnotations.add(a);\n }\n }\n }\n }\n }\n Iterator it = includedAnnotations.iterator();\n while (it.hasNext()) {\n XYAnnotationBoundsInfo xyabi = (XYAnnotationBoundsInfo) it.next();\n if (xyabi.getIncludeInDataBounds()) {\n if (isDomainAxis) {\n result = Range.combine(result, xyabi.getXRange());\n }\n else {\n result = Range.combine(result, xyabi.getYRange());\n }\n }\n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-4"}} {"sample_uid": "defects4j_function_repair::Closure-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n if (NodeUtil.isVarDeclaration(n)) {\n NameInformation ns = createNameInformation(t, n, parent);\n Preconditions.checkNotNull(ns);\n recordSet(ns.name, n);\n } else if (NodeUtil.isFunctionDeclaration(n)) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n JsName nameInfo = getName(nameNode.getString(), true);\n recordSet(nameInfo.name, nameNode);\n }\n } else if (NodeUtil.isObjectLitKey(n, parent)) {\n NameInformation ns = createNameInformation(t, n, parent);\n if (ns != null) {\n recordSet(ns.name, n);\n }\n }\n }\n if (n.isAssign()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n if (ns.isPrototype) {\n recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);\n } else {\n recordSet(ns.name, nameNode);\n }\n }\n } else if (n.isCall()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null && ns.onlyAffectsClassDef) {\n JsName name = getName(ns.name, false);\n if (name != null) {\n refNodes.add(new ClassDefiningFunctionNode(\n name, n, parent, parent.getParent()));\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n if (NodeUtil.isVarDeclaration(n)) {\n NameInformation ns = createNameInformation(t, n, parent);\n Preconditions.checkNotNull(ns);\n recordSet(ns.name, n);\n } else if (NodeUtil.isFunctionDeclaration(n)) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n JsName nameInfo = getName(nameNode.getString(), true);\n recordSet(nameInfo.name, nameNode);\n }\n } else if (NodeUtil.isObjectLitKey(n, parent)) {\n NameInformation ns = createNameInformation(t, n, parent);\n if (ns != null) {\n recordSet(ns.name, n);\n }\n }\n }\n if (n.isAssign()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n if (ns.isPrototype) {\n recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);\n } else {\n recordSet(ns.name, nameNode);\n }\n }\n } else if (n.isCall()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null && ns.onlyAffectsClassDef) {\n JsName name = getName(ns.name, false);\n if (name != null) {\n refNodes.add(new ClassDefiningFunctionNode(\n name, n, parent, parent.getParent()));\n }\n }\n }\n }\n"}, "reference": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n if (NodeUtil.isVarDeclaration(n)) {\n NameInformation ns = createNameInformation(t, n, parent);\n Preconditions.checkNotNull(ns);\n recordSet(ns.name, n);\n } else if (NodeUtil.isFunctionDeclaration(n)) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n JsName nameInfo = getName(nameNode.getString(), true);\n recordSet(nameInfo.name, nameNode);\n }\n } else if (NodeUtil.isObjectLitKey(n, parent)) {\n NameInformation ns = createNameInformation(t, n, parent);\n if (ns != null) {\n recordSet(ns.name, n);\n }\n }\n }\n if (n.isAssign()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null) {\n if (ns.isPrototype) {\n recordPrototypeSet(ns.prototypeClass, ns.prototypeProperty, n);\n } else {\n recordSet(ns.name, nameNode);\n }\n }\n } else if (n.isCall()) {\n Node nameNode = n.getFirstChild();\n NameInformation ns = createNameInformation(t, nameNode, n);\n if (ns != null && ns.onlyAffectsClassDef) {\n JsName name = getName(ns.name, true);\n refNodes.add(new ClassDefiningFunctionNode(\n name, n, parent, parent.getParent()));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-40"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public BaseSettings withDateFormat(DateFormat df) {\n if (_dateFormat == df) {\n return this;\n }\n TimeZone tz = (df == null) ? _timeZone : df.getTimeZone();\n return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,\n _typeResolverBuilder, df, _handlerInstantiator, _locale,\n tz, _defaultBase64);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public BaseSettings withDateFormat(DateFormat df) {\n if (_dateFormat == df) {\n return this;\n }\n TimeZone tz = (df == null) ? _timeZone : df.getTimeZone();\n return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,\n _typeResolverBuilder, df, _handlerInstantiator, _locale,\n tz, _defaultBase64);\n }\n"}, "reference": " public BaseSettings withDateFormat(DateFormat df) {\n if (_dateFormat == df) {\n return this;\n }\n return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,\n _typeResolverBuilder, df, _handlerInstantiator, _locale,\n _timeZone, _defaultBase64);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-24"}} {"sample_uid": "defects4j_function_repair::Math-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private RealMatrix squareRoot(RealMatrix m) {\n final EigenDecomposition dec = new EigenDecomposition(m);\n return dec.getSquareRoot();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private RealMatrix squareRoot(RealMatrix m) {\n final EigenDecomposition dec = new EigenDecomposition(m);\n return dec.getSquareRoot();\n }\n"}, "reference": " private RealMatrix squareRoot(RealMatrix m) {\n if (m instanceof DiagonalMatrix) {\n final int dim = m.getRowDimension();\n final RealMatrix sqrtM = new DiagonalMatrix(dim);\n for (int i = 0; i < dim; i++) {\n sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));\n }\n return sqrtM;\n } else {\n final EigenDecomposition dec = new EigenDecomposition(m);\n return dec.getSquareRoot();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-13"}} {"sample_uid": "defects4j_function_repair::Codec-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean equals(final CharSequence cs1, final CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n if (cs1 instanceof String && cs2 instanceof String) {\n return cs1.equals(cs2);\n }\n return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean equals(final CharSequence cs1, final CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n if (cs1 instanceof String && cs2 instanceof String) {\n return cs1.equals(cs2);\n }\n return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));\n }\n"}, "reference": " public static boolean equals(final CharSequence cs1, final CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n if (cs1 instanceof String && cs2 instanceof String) {\n return cs1.equals(cs2);\n }\n return cs1.length() == cs2.length() && CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-18"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-93", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException\n {\n final Class raw = type.getRawClass();\n String full = raw.getName();\n main_check:\n do {\n if (_cfgIllegalClassNames.contains(full)) {\n break;\n }\n if (full.startsWith(PREFIX_STRING)) {\n for (Class cls = raw; cls != Object.class; cls = cls.getSuperclass()) {\n String name = cls.getSimpleName();\n if (\"AbstractPointcutAdvisor\".equals(name)\n || \"AbstractApplicationContext\".equals(name)) {\n break main_check;\n }\n }\n }\n return;\n } while (false);\n throw JsonMappingException.from(ctxt,\n String.format(\"Illegal type (%s) to deserialize: prevented for security reasons\", full));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException\n {\n final Class raw = type.getRawClass();\n String full = raw.getName();\n main_check:\n do {\n if (_cfgIllegalClassNames.contains(full)) {\n break;\n }\n if (full.startsWith(PREFIX_STRING)) {\n for (Class cls = raw; cls != Object.class; cls = cls.getSuperclass()) {\n String name = cls.getSimpleName();\n if (\"AbstractPointcutAdvisor\".equals(name)\n || \"AbstractApplicationContext\".equals(name)) {\n break main_check;\n }\n }\n }\n return;\n } while (false);\n throw JsonMappingException.from(ctxt,\n String.format(\"Illegal type (%s) to deserialize: prevented for security reasons\", full));\n }\n"}, "reference": " public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException\n {\n final Class raw = type.getRawClass();\n String full = raw.getName();\n main_check:\n do {\n if (_cfgIllegalClassNames.contains(full)) {\n break;\n }\n if (!raw.isInterface() && full.startsWith(PREFIX_STRING)) {\n for (Class cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()) {\n String name = cls.getSimpleName();\n if (\"AbstractPointcutAdvisor\".equals(name)\n || \"AbstractApplicationContext\".equals(name)) {\n break main_check;\n }\n }\n }\n return;\n } while (false);\n throw JsonMappingException.from(ctxt,\n String.format(\"Illegal type (%s) to deserialize: prevented for security reasons\", full));\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-93"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-93"}} {"sample_uid": "defects4j_function_repair::Closure-145", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isOneExactlyFunctionOrDo(Node n) {\n return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isOneExactlyFunctionOrDo(Node n) {\n return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);\n }\n"}, "reference": " private boolean isOneExactlyFunctionOrDo(Node n) {\n if (n.getType() == Token.LABEL) {\n Node labeledStatement = n.getLastChild();\n if (labeledStatement.getType() != Token.BLOCK) {\n return isOneExactlyFunctionOrDo(labeledStatement);\n } else {\n if (getNonEmptyChildCount(n, 2) == 1) { \n return isOneExactlyFunctionOrDo(getFirstNonEmptyChild(n));\n } else {\n return false;\n }\n }\n } else {\n return (n.getType() == Token.FUNCTION || n.getType() == Token.DO);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-145"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-145"}} {"sample_uid": "defects4j_function_repair::Closure-176", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void updateScopeForTypeChange(\n FlowScope scope, Node left, JSType leftType, JSType resultType) {\n Preconditions.checkNotNull(resultType);\n switch (left.getType()) {\n case Token.NAME:\n String varName = left.getString();\n Var var = syntacticScope.getVar(varName);\n boolean isVarDeclaration = left.hasChildren();\n boolean isVarTypeBetter = !isVarDeclaration || var == null || var.isTypeInferred();\n if (isVarTypeBetter) {\n redeclareSimpleVar(scope, left, resultType);\n }\n left.setJSType(isVarDeclaration || leftType == null ?\n resultType : null);\n if (var != null && var.isTypeInferred()) {\n JSType oldType = var.getType();\n var.setType(oldType == null ?\n resultType : oldType.getLeastSupertype(resultType));\n }\n break;\n case Token.GETPROP:\n String qualifiedName = left.getQualifiedName();\n if (qualifiedName != null) {\n scope.inferQualifiedSlot(left, qualifiedName,\n leftType == null ? unknownType : leftType,\n resultType);\n }\n left.setJSType(resultType);\n ensurePropertyDefined(left, resultType);\n break;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void updateScopeForTypeChange(\n FlowScope scope, Node left, JSType leftType, JSType resultType) {\n Preconditions.checkNotNull(resultType);\n switch (left.getType()) {\n case Token.NAME:\n String varName = left.getString();\n Var var = syntacticScope.getVar(varName);\n boolean isVarDeclaration = left.hasChildren();\n boolean isVarTypeBetter = !isVarDeclaration || var == null || var.isTypeInferred();\n if (isVarTypeBetter) {\n redeclareSimpleVar(scope, left, resultType);\n }\n left.setJSType(isVarDeclaration || leftType == null ?\n resultType : null);\n if (var != null && var.isTypeInferred()) {\n JSType oldType = var.getType();\n var.setType(oldType == null ?\n resultType : oldType.getLeastSupertype(resultType));\n }\n break;\n case Token.GETPROP:\n String qualifiedName = left.getQualifiedName();\n if (qualifiedName != null) {\n scope.inferQualifiedSlot(left, qualifiedName,\n leftType == null ? unknownType : leftType,\n resultType);\n }\n left.setJSType(resultType);\n ensurePropertyDefined(left, resultType);\n break;\n }\n }\n"}, "reference": " private void updateScopeForTypeChange(\n FlowScope scope, Node left, JSType leftType, JSType resultType) {\n Preconditions.checkNotNull(resultType);\n switch (left.getType()) {\n case Token.NAME:\n String varName = left.getString();\n Var var = syntacticScope.getVar(varName);\n JSType varType = var == null ? null : var.getType();\n boolean isVarDeclaration = left.hasChildren()\n && varType != null && !var.isTypeInferred();\n boolean isVarTypeBetter = isVarDeclaration &&\n !resultType.isNullType() && !resultType.isVoidType();\n if (isVarTypeBetter) {\n redeclareSimpleVar(scope, left, varType);\n } else {\n redeclareSimpleVar(scope, left, resultType);\n }\n left.setJSType(resultType);\n if (var != null && var.isTypeInferred()) {\n JSType oldType = var.getType();\n var.setType(oldType == null ?\n resultType : oldType.getLeastSupertype(resultType));\n }\n break;\n case Token.GETPROP:\n String qualifiedName = left.getQualifiedName();\n if (qualifiedName != null) {\n scope.inferQualifiedSlot(left, qualifiedName,\n leftType == null ? unknownType : leftType,\n resultType);\n }\n left.setJSType(resultType);\n ensurePropertyDefined(left, resultType);\n break;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-176"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-176"}} {"sample_uid": "defects4j_function_repair::Cli-35", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public List getMatchingOptions(String opt)\n {\n opt = Util.stripLeadingHyphens(opt);\n List matchingOpts = new ArrayList();\n for (String longOpt : longOpts.keySet())\n {\n if (longOpt.startsWith(opt))\n {\n matchingOpts.add(longOpt);\n }\n }\n return matchingOpts;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public List getMatchingOptions(String opt)\n {\n opt = Util.stripLeadingHyphens(opt);\n List matchingOpts = new ArrayList();\n for (String longOpt : longOpts.keySet())\n {\n if (longOpt.startsWith(opt))\n {\n matchingOpts.add(longOpt);\n }\n }\n return matchingOpts;\n }\n"}, "reference": " public List getMatchingOptions(String opt)\n {\n opt = Util.stripLeadingHyphens(opt);\n List matchingOpts = new ArrayList();\n if(longOpts.keySet().contains(opt)) {\n return Collections.singletonList(opt);\n }\n for (String longOpt : longOpts.keySet())\n {\n if (longOpt.startsWith(opt))\n {\n matchingOpts.add(longOpt);\n }\n }\n return matchingOpts;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-35"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-35"}} {"sample_uid": "defects4j_function_repair::Closure-119", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void collect(JSModule module, Scope scope, Node n) {\n Node parent = n.getParent();\n String name;\n boolean isSet = false;\n Name.Type type = Name.Type.OTHER;\n boolean isPropAssign = false;\n switch (n.getType()) {\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n case Token.STRING_KEY:\n name = null;\n if (parent != null && parent.isObjectLit()) {\n name = getNameForObjLitKey(n);\n }\n if (name == null) {\n return;\n }\n isSet = true;\n switch (n.getType()) {\n case Token.STRING_KEY:\n type = getValueType(n.getFirstChild());\n break;\n case Token.GETTER_DEF:\n type = Name.Type.GET;\n break;\n case Token.SETTER_DEF:\n type = Name.Type.SET;\n break;\n default:\n throw new IllegalStateException(\"unexpected:\" + n);\n }\n break;\n case Token.NAME:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.VAR:\n isSet = true;\n Node rvalue = n.getFirstChild();\n type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue);\n break;\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n }\n break;\n case Token.GETPROP:\n return;\n case Token.FUNCTION:\n Node gramps = parent.getParent();\n if (gramps == null || NodeUtil.isFunctionExpression(parent)) {\n return;\n }\n isSet = true;\n type = Name.Type.FUNCTION;\n break;\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getString();\n break;\n case Token.GETPROP:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n isPropAssign = true;\n }\n break;\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n case Token.GETPROP:\n return;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getQualifiedName();\n if (name == null) {\n return;\n }\n break;\n default:\n return;\n }\n if (!isGlobalNameReference(name, scope)) {\n return;\n }\n if (isSet) {\n if (isGlobalScope(scope)) {\n handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type);\n } else {\n handleSetFromLocal(module, scope, n, parent, name);\n }\n } else {\n handleGet(module, scope, n, parent, name);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void collect(JSModule module, Scope scope, Node n) {\n Node parent = n.getParent();\n String name;\n boolean isSet = false;\n Name.Type type = Name.Type.OTHER;\n boolean isPropAssign = false;\n switch (n.getType()) {\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n case Token.STRING_KEY:\n name = null;\n if (parent != null && parent.isObjectLit()) {\n name = getNameForObjLitKey(n);\n }\n if (name == null) {\n return;\n }\n isSet = true;\n switch (n.getType()) {\n case Token.STRING_KEY:\n type = getValueType(n.getFirstChild());\n break;\n case Token.GETTER_DEF:\n type = Name.Type.GET;\n break;\n case Token.SETTER_DEF:\n type = Name.Type.SET;\n break;\n default:\n throw new IllegalStateException(\"unexpected:\" + n);\n }\n break;\n case Token.NAME:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.VAR:\n isSet = true;\n Node rvalue = n.getFirstChild();\n type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue);\n break;\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n }\n break;\n case Token.GETPROP:\n return;\n case Token.FUNCTION:\n Node gramps = parent.getParent();\n if (gramps == null || NodeUtil.isFunctionExpression(parent)) {\n return;\n }\n isSet = true;\n type = Name.Type.FUNCTION;\n break;\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getString();\n break;\n case Token.GETPROP:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n isPropAssign = true;\n }\n break;\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n case Token.GETPROP:\n return;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getQualifiedName();\n if (name == null) {\n return;\n }\n break;\n default:\n return;\n }\n if (!isGlobalNameReference(name, scope)) {\n return;\n }\n if (isSet) {\n if (isGlobalScope(scope)) {\n handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type);\n } else {\n handleSetFromLocal(module, scope, n, parent, name);\n }\n } else {\n handleGet(module, scope, n, parent, name);\n }\n }\n"}, "reference": " public void collect(JSModule module, Scope scope, Node n) {\n Node parent = n.getParent();\n String name;\n boolean isSet = false;\n Name.Type type = Name.Type.OTHER;\n boolean isPropAssign = false;\n switch (n.getType()) {\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n case Token.STRING_KEY:\n name = null;\n if (parent != null && parent.isObjectLit()) {\n name = getNameForObjLitKey(n);\n }\n if (name == null) {\n return;\n }\n isSet = true;\n switch (n.getType()) {\n case Token.STRING_KEY:\n type = getValueType(n.getFirstChild());\n break;\n case Token.GETTER_DEF:\n type = Name.Type.GET;\n break;\n case Token.SETTER_DEF:\n type = Name.Type.SET;\n break;\n default:\n throw new IllegalStateException(\"unexpected:\" + n);\n }\n break;\n case Token.NAME:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.VAR:\n isSet = true;\n Node rvalue = n.getFirstChild();\n type = rvalue == null ? Name.Type.OTHER : getValueType(rvalue);\n break;\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n }\n break;\n case Token.GETPROP:\n return;\n case Token.FUNCTION:\n Node gramps = parent.getParent();\n if (gramps == null || NodeUtil.isFunctionExpression(parent)) {\n return;\n }\n isSet = true;\n type = Name.Type.FUNCTION;\n break;\n case Token.CATCH:\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getString();\n break;\n case Token.GETPROP:\n if (parent != null) {\n switch (parent.getType()) {\n case Token.ASSIGN:\n if (parent.getFirstChild() == n) {\n isSet = true;\n type = getValueType(n.getNext());\n isPropAssign = true;\n }\n break;\n case Token.INC:\n case Token.DEC:\n isSet = true;\n type = Name.Type.OTHER;\n break;\n case Token.GETPROP:\n return;\n default:\n if (NodeUtil.isAssignmentOp(parent) &&\n parent.getFirstChild() == n) {\n isSet = true;\n type = Name.Type.OTHER;\n }\n }\n }\n name = n.getQualifiedName();\n if (name == null) {\n return;\n }\n break;\n default:\n return;\n }\n if (!isGlobalNameReference(name, scope)) {\n return;\n }\n if (isSet) {\n if (isGlobalScope(scope)) {\n handleSetFromGlobal(module, scope, n, parent, name, isPropAssign, type);\n } else {\n handleSetFromLocal(module, scope, n, parent, name);\n }\n } else {\n handleGet(module, scope, n, parent, name);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-119"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-119"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-19", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private JavaType _mapType(Class rawClass)\n {\n JavaType[] typeParams = findTypeParameters(rawClass, Map.class);\n if (typeParams == null) {\n return MapType.construct(rawClass, _unknownType(), _unknownType());\n }\n if (typeParams.length != 2) {\n throw new IllegalArgumentException(\"Strange Map type \"+rawClass.getName()+\": can not determine type parameters\");\n }\n return MapType.construct(rawClass, typeParams[0], typeParams[1]);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private JavaType _mapType(Class rawClass)\n {\n JavaType[] typeParams = findTypeParameters(rawClass, Map.class);\n if (typeParams == null) {\n return MapType.construct(rawClass, _unknownType(), _unknownType());\n }\n if (typeParams.length != 2) {\n throw new IllegalArgumentException(\"Strange Map type \"+rawClass.getName()+\": can not determine type parameters\");\n }\n return MapType.construct(rawClass, typeParams[0], typeParams[1]);\n }\n"}, "reference": " private JavaType _mapType(Class rawClass)\n {\n if (rawClass == Properties.class) {\n return MapType.construct(rawClass, CORE_TYPE_STRING, CORE_TYPE_STRING);\n }\n JavaType[] typeParams = findTypeParameters(rawClass, Map.class);\n if (typeParams == null) {\n return MapType.construct(rawClass, _unknownType(), _unknownType());\n }\n if (typeParams.length != 2) {\n throw new IllegalArgumentException(\"Strange Map type \"+rawClass.getName()+\": can not determine type parameters\");\n }\n return MapType.construct(rawClass, typeParams[0], typeParams[1]);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-19"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-19"}} {"sample_uid": "defects4j_function_repair::Closure-56", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String getLine(int lineNumber) {\n String js = \"\";\n try {\n js = getCode();\n } catch (IOException e) {\n return null;\n }\n int pos = 0;\n int startLine = 1;\n if (lineNumber >= lastLine) {\n pos = lastOffset;\n startLine = lastLine;\n }\n for (int n = startLine; n < lineNumber; n++) {\n int nextpos = js.indexOf('\\n', pos);\n if (nextpos == -1) {\n return null;\n }\n pos = nextpos + 1;\n }\n lastOffset = pos;\n lastLine = lineNumber;\n if (js.indexOf('\\n', pos) == -1) {\n return null;\n } else {\n return js.substring(pos, js.indexOf('\\n', pos));\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String getLine(int lineNumber) {\n String js = \"\";\n try {\n js = getCode();\n } catch (IOException e) {\n return null;\n }\n int pos = 0;\n int startLine = 1;\n if (lineNumber >= lastLine) {\n pos = lastOffset;\n startLine = lastLine;\n }\n for (int n = startLine; n < lineNumber; n++) {\n int nextpos = js.indexOf('\\n', pos);\n if (nextpos == -1) {\n return null;\n }\n pos = nextpos + 1;\n }\n lastOffset = pos;\n lastLine = lineNumber;\n if (js.indexOf('\\n', pos) == -1) {\n return null;\n } else {\n return js.substring(pos, js.indexOf('\\n', pos));\n }\n }\n"}, "reference": " public String getLine(int lineNumber) {\n String js = \"\";\n try {\n js = getCode();\n } catch (IOException e) {\n return null;\n }\n int pos = 0;\n int startLine = 1;\n if (lineNumber >= lastLine) {\n pos = lastOffset;\n startLine = lastLine;\n }\n for (int n = startLine; n < lineNumber; n++) {\n int nextpos = js.indexOf('\\n', pos);\n if (nextpos == -1) {\n return null;\n }\n pos = nextpos + 1;\n }\n lastOffset = pos;\n lastLine = lineNumber;\n if (js.indexOf('\\n', pos) == -1) {\n if (pos >= js.length()) {\n return null;\n } else {\n return js.substring(pos, js.length());\n }\n } else {\n return js.substring(pos, js.indexOf('\\n', pos));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-56"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-56"}} {"sample_uid": "defects4j_function_repair::Math-103", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double cumulativeProbability(double x) throws MathException {\n return 0.5 * (1.0 + Erf.erf((x - mean) /\n (standardDeviation * Math.sqrt(2.0))));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double cumulativeProbability(double x) throws MathException {\n return 0.5 * (1.0 + Erf.erf((x - mean) /\n (standardDeviation * Math.sqrt(2.0))));\n }\n"}, "reference": " public double cumulativeProbability(double x) throws MathException {\n try {\n return 0.5 * (1.0 + Erf.erf((x - mean) /\n (standardDeviation * Math.sqrt(2.0))));\n } catch (MaxIterationsExceededException ex) {\n if (x < (mean - 20 * standardDeviation)) { \n return 0.0d;\n } else if (x > (mean + 20 * standardDeviation)) {\n return 1.0d;\n } else {\n throw ex;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-103"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-103"}} {"sample_uid": "defects4j_function_repair::Math-80", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean flipIfWarranted(final int n, final int step) {\n if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) {\n int j = 4 * n - 1;\n for (int i = 0; i < j; i += 4) {\n for (int k = 0; k < 4; k += step) {\n final double tmp = work[i + k];\n work[i + k] = work[j - k];\n work[j - k] = tmp;\n }\n j -= 4;\n }\n return true;\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean flipIfWarranted(final int n, final int step) {\n if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) {\n int j = 4 * n - 1;\n for (int i = 0; i < j; i += 4) {\n for (int k = 0; k < 4; k += step) {\n final double tmp = work[i + k];\n work[i + k] = work[j - k];\n work[j - k] = tmp;\n }\n j -= 4;\n }\n return true;\n }\n return false;\n }\n"}, "reference": " private boolean flipIfWarranted(final int n, final int step) {\n if (1.5 * work[pingPong] < work[4 * (n - 1) + pingPong]) {\n int j = 4 * (n - 1);\n for (int i = 0; i < j; i += 4) {\n for (int k = 0; k < 4; k += step) {\n final double tmp = work[i + k];\n work[i + k] = work[j - k];\n work[j - k] = tmp;\n }\n j -= 4;\n }\n return true;\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-80"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-80"}} {"sample_uid": "defects4j_function_repair::Math-41", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double evaluate(final double[] values, final double[] weights,\n final double mean, final int begin, final int length) {\n double var = Double.NaN;\n if (test(values, weights, begin, length)) {\n if (length == 1) {\n var = 0.0;\n } else if (length > 1) {\n double accum = 0.0;\n double dev = 0.0;\n double accum2 = 0.0;\n for (int i = begin; i < begin + length; i++) {\n dev = values[i] - mean;\n accum += weights[i] * (dev * dev);\n accum2 += weights[i] * dev;\n }\n double sumWts = 0;\n for (int i = 0; i < weights.length; i++) {\n sumWts += weights[i];\n }\n if (isBiasCorrected) {\n var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0);\n } else {\n var = (accum - (accum2 * accum2 / sumWts)) / sumWts;\n }\n }\n }\n return var;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double evaluate(final double[] values, final double[] weights,\n final double mean, final int begin, final int length) {\n double var = Double.NaN;\n if (test(values, weights, begin, length)) {\n if (length == 1) {\n var = 0.0;\n } else if (length > 1) {\n double accum = 0.0;\n double dev = 0.0;\n double accum2 = 0.0;\n for (int i = begin; i < begin + length; i++) {\n dev = values[i] - mean;\n accum += weights[i] * (dev * dev);\n accum2 += weights[i] * dev;\n }\n double sumWts = 0;\n for (int i = 0; i < weights.length; i++) {\n sumWts += weights[i];\n }\n if (isBiasCorrected) {\n var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0);\n } else {\n var = (accum - (accum2 * accum2 / sumWts)) / sumWts;\n }\n }\n }\n return var;\n }\n"}, "reference": " public double evaluate(final double[] values, final double[] weights,\n final double mean, final int begin, final int length) {\n double var = Double.NaN;\n if (test(values, weights, begin, length)) {\n if (length == 1) {\n var = 0.0;\n } else if (length > 1) {\n double accum = 0.0;\n double dev = 0.0;\n double accum2 = 0.0;\n for (int i = begin; i < begin + length; i++) {\n dev = values[i] - mean;\n accum += weights[i] * (dev * dev);\n accum2 += weights[i] * dev;\n }\n double sumWts = 0;\n for (int i = begin; i < begin + length; i++) {\n sumWts += weights[i];\n }\n if (isBiasCorrected) {\n var = (accum - (accum2 * accum2 / sumWts)) / (sumWts - 1.0);\n } else {\n var = (accum - (accum2 * accum2 / sumWts)) / sumWts;\n }\n }\n }\n return var;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-41"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-41"}} {"sample_uid": "defects4j_function_repair::Math-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Dfp multiply(final int x) {\n return multiplyFast(x);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Dfp multiply(final int x) {\n return multiplyFast(x);\n }\n"}, "reference": " public Dfp multiply(final int x) {\n if (x >= 0 && x < RADIX) {\n return multiplyFast(x);\n } else {\n return multiply(newInstance(x));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-17"}} {"sample_uid": "defects4j_function_repair::Math-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void prelim(double[] lowerBound,\n double[] upperBound) {\n printMethod(); \n final int n = currentBest.getDimension();\n final int npt = numberOfInterpolationPoints;\n final int ndim = bMatrix.getRowDimension();\n final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius;\n final double recip = 1d / rhosq;\n final int np = n + 1;\n for (int j = 0; j < n; j++) {\n originShift.setEntry(j, currentBest.getEntry(j));\n for (int k = 0; k < npt; k++) {\n interpolationPoints.setEntry(k, j, ZERO);\n }\n for (int i = 0; i < ndim; i++) {\n bMatrix.setEntry(i, j, ZERO);\n }\n }\n for (int i = 0, max = n * np / 2; i < max; i++) {\n modelSecondDerivativesValues.setEntry(i, ZERO);\n }\n for (int k = 0; k < npt; k++) {\n modelSecondDerivativesParameters.setEntry(k, ZERO);\n for (int j = 0, max = npt - np; j < max; j++) {\n zMatrix.setEntry(k, j, ZERO);\n }\n }\n int ipt = 0;\n int jpt = 0;\n double fbeg = Double.NaN;\n do {\n final int nfm = getEvaluations();\n final int nfx = nfm - n;\n final int nfmm = nfm - 1;\n final int nfxm = nfx - 1;\n double stepa = 0;\n double stepb = 0;\n if (nfm <= 2 * n) {\n if (nfm >= 1 &&\n nfm <= n) {\n stepa = initialTrustRegionRadius;\n if (upperDifference.getEntry(nfmm) == ZERO) {\n stepa = -stepa;\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfmm, stepa);\n } else if (nfm > n) {\n stepa = interpolationPoints.getEntry(nfx, nfxm);\n stepb = -initialTrustRegionRadius;\n if (lowerDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n if (upperDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfxm, stepb);\n }\n } else {\n final int tmp1 = (nfm - np) / n;\n jpt = nfm - tmp1 * n - n;\n ipt = jpt + tmp1;\n if (ipt > n) {\n final int tmp2 = jpt;\n jpt = ipt - n;\n ipt = tmp2;\n throw new PathIsExploredException(); \n }\n final int iptMinus1 = ipt;\n final int jptMinus1 = jpt;\n interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1));\n interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1));\n }\n for (int j = 0; j < n; j++) {\n currentBest.setEntry(j, Math.min(Math.max(lowerBound[j],\n originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)),\n upperBound[j]));\n if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) {\n currentBest.setEntry(j, lowerBound[j]);\n }\n if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) {\n currentBest.setEntry(j, upperBound[j]);\n }\n }\n final double objectiveValue = computeObjectiveValue(currentBest.toArray());\n final double f = isMinimize ? objectiveValue : -objectiveValue;\n final int numEval = getEvaluations(); \n fAtInterpolationPoints.setEntry(nfm, f);\n if (numEval == 1) {\n fbeg = f;\n trustRegionCenterInterpolationPointIndex = 0;\n } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) {\n trustRegionCenterInterpolationPointIndex = nfm;\n }\n if (numEval <= 2 * n + 1) {\n if (numEval >= 2 &&\n numEval <= n + 1) {\n gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa);\n if (npt < numEval + n) {\n final double oneOverStepA = ONE / stepa;\n bMatrix.setEntry(0, nfmm, -oneOverStepA);\n bMatrix.setEntry(nfm, nfmm, oneOverStepA);\n bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq);\n throw new PathIsExploredException(); \n }\n } else if (numEval >= n + 2) {\n final int ih = nfx * (nfx + 1) / 2 - 1;\n final double tmp = (f - fbeg) / stepb;\n final double diff = stepb - stepa;\n modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff);\n gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff);\n if (stepa * stepb < ZERO) {\n if (f < fAtInterpolationPoints.getEntry(nfm - n)) {\n fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n));\n fAtInterpolationPoints.setEntry(nfm - n, f);\n if (trustRegionCenterInterpolationPointIndex == nfm) {\n trustRegionCenterInterpolationPointIndex = nfm - n;\n }\n interpolationPoints.setEntry(nfm - n, nfxm, stepb);\n interpolationPoints.setEntry(nfm, nfxm, stepa);\n }\n }\n bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb));\n bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm));\n bMatrix.setEntry(nfm - n, nfxm,\n -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm));\n zMatrix.setEntry(0, nfxm, Math.sqrt(TWO) / (stepa * stepb));\n zMatrix.setEntry(nfm, nfxm, Math.sqrt(HALF) / rhosq);\n zMatrix.setEntry(nfm - n, nfxm,\n -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm));\n }\n } else {\n zMatrix.setEntry(0, nfxm, recip);\n zMatrix.setEntry(nfm, nfxm, recip);\n zMatrix.setEntry(ipt, nfxm, -recip);\n zMatrix.setEntry(jpt, nfxm, -recip);\n final int ih = ipt * (ipt - 1) / 2 + jpt - 1;\n final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1);\n modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp);\n throw new PathIsExploredException(); \n }\n } while (getEvaluations() < npt);\n } \n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void prelim(double[] lowerBound,\n double[] upperBound) {\n printMethod(); \n final int n = currentBest.getDimension();\n final int npt = numberOfInterpolationPoints;\n final int ndim = bMatrix.getRowDimension();\n final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius;\n final double recip = 1d / rhosq;\n final int np = n + 1;\n for (int j = 0; j < n; j++) {\n originShift.setEntry(j, currentBest.getEntry(j));\n for (int k = 0; k < npt; k++) {\n interpolationPoints.setEntry(k, j, ZERO);\n }\n for (int i = 0; i < ndim; i++) {\n bMatrix.setEntry(i, j, ZERO);\n }\n }\n for (int i = 0, max = n * np / 2; i < max; i++) {\n modelSecondDerivativesValues.setEntry(i, ZERO);\n }\n for (int k = 0; k < npt; k++) {\n modelSecondDerivativesParameters.setEntry(k, ZERO);\n for (int j = 0, max = npt - np; j < max; j++) {\n zMatrix.setEntry(k, j, ZERO);\n }\n }\n int ipt = 0;\n int jpt = 0;\n double fbeg = Double.NaN;\n do {\n final int nfm = getEvaluations();\n final int nfx = nfm - n;\n final int nfmm = nfm - 1;\n final int nfxm = nfx - 1;\n double stepa = 0;\n double stepb = 0;\n if (nfm <= 2 * n) {\n if (nfm >= 1 &&\n nfm <= n) {\n stepa = initialTrustRegionRadius;\n if (upperDifference.getEntry(nfmm) == ZERO) {\n stepa = -stepa;\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfmm, stepa);\n } else if (nfm > n) {\n stepa = interpolationPoints.getEntry(nfx, nfxm);\n stepb = -initialTrustRegionRadius;\n if (lowerDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n if (upperDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfxm, stepb);\n }\n } else {\n final int tmp1 = (nfm - np) / n;\n jpt = nfm - tmp1 * n - n;\n ipt = jpt + tmp1;\n if (ipt > n) {\n final int tmp2 = jpt;\n jpt = ipt - n;\n ipt = tmp2;\n throw new PathIsExploredException(); \n }\n final int iptMinus1 = ipt;\n final int jptMinus1 = jpt;\n interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1));\n interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1));\n }\n for (int j = 0; j < n; j++) {\n currentBest.setEntry(j, Math.min(Math.max(lowerBound[j],\n originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)),\n upperBound[j]));\n if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) {\n currentBest.setEntry(j, lowerBound[j]);\n }\n if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) {\n currentBest.setEntry(j, upperBound[j]);\n }\n }\n final double objectiveValue = computeObjectiveValue(currentBest.toArray());\n final double f = isMinimize ? objectiveValue : -objectiveValue;\n final int numEval = getEvaluations(); \n fAtInterpolationPoints.setEntry(nfm, f);\n if (numEval == 1) {\n fbeg = f;\n trustRegionCenterInterpolationPointIndex = 0;\n } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) {\n trustRegionCenterInterpolationPointIndex = nfm;\n }\n if (numEval <= 2 * n + 1) {\n if (numEval >= 2 &&\n numEval <= n + 1) {\n gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa);\n if (npt < numEval + n) {\n final double oneOverStepA = ONE / stepa;\n bMatrix.setEntry(0, nfmm, -oneOverStepA);\n bMatrix.setEntry(nfm, nfmm, oneOverStepA);\n bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq);\n throw new PathIsExploredException(); \n }\n } else if (numEval >= n + 2) {\n final int ih = nfx * (nfx + 1) / 2 - 1;\n final double tmp = (f - fbeg) / stepb;\n final double diff = stepb - stepa;\n modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff);\n gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff);\n if (stepa * stepb < ZERO) {\n if (f < fAtInterpolationPoints.getEntry(nfm - n)) {\n fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n));\n fAtInterpolationPoints.setEntry(nfm - n, f);\n if (trustRegionCenterInterpolationPointIndex == nfm) {\n trustRegionCenterInterpolationPointIndex = nfm - n;\n }\n interpolationPoints.setEntry(nfm - n, nfxm, stepb);\n interpolationPoints.setEntry(nfm, nfxm, stepa);\n }\n }\n bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb));\n bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm));\n bMatrix.setEntry(nfm - n, nfxm,\n -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm));\n zMatrix.setEntry(0, nfxm, Math.sqrt(TWO) / (stepa * stepb));\n zMatrix.setEntry(nfm, nfxm, Math.sqrt(HALF) / rhosq);\n zMatrix.setEntry(nfm - n, nfxm,\n -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm));\n }\n } else {\n zMatrix.setEntry(0, nfxm, recip);\n zMatrix.setEntry(nfm, nfxm, recip);\n zMatrix.setEntry(ipt, nfxm, -recip);\n zMatrix.setEntry(jpt, nfxm, -recip);\n final int ih = ipt * (ipt - 1) / 2 + jpt - 1;\n final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1);\n modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp);\n throw new PathIsExploredException(); \n }\n } while (getEvaluations() < npt);\n } \n"}, "reference": " private void prelim(double[] lowerBound,\n double[] upperBound) {\n printMethod(); \n final int n = currentBest.getDimension();\n final int npt = numberOfInterpolationPoints;\n final int ndim = bMatrix.getRowDimension();\n final double rhosq = initialTrustRegionRadius * initialTrustRegionRadius;\n final double recip = 1d / rhosq;\n final int np = n + 1;\n for (int j = 0; j < n; j++) {\n originShift.setEntry(j, currentBest.getEntry(j));\n for (int k = 0; k < npt; k++) {\n interpolationPoints.setEntry(k, j, ZERO);\n }\n for (int i = 0; i < ndim; i++) {\n bMatrix.setEntry(i, j, ZERO);\n }\n }\n for (int i = 0, max = n * np / 2; i < max; i++) {\n modelSecondDerivativesValues.setEntry(i, ZERO);\n }\n for (int k = 0; k < npt; k++) {\n modelSecondDerivativesParameters.setEntry(k, ZERO);\n for (int j = 0, max = npt - np; j < max; j++) {\n zMatrix.setEntry(k, j, ZERO);\n }\n }\n int ipt = 0;\n int jpt = 0;\n double fbeg = Double.NaN;\n do {\n final int nfm = getEvaluations();\n final int nfx = nfm - n;\n final int nfmm = nfm - 1;\n final int nfxm = nfx - 1;\n double stepa = 0;\n double stepb = 0;\n if (nfm <= 2 * n) {\n if (nfm >= 1 &&\n nfm <= n) {\n stepa = initialTrustRegionRadius;\n if (upperDifference.getEntry(nfmm) == ZERO) {\n stepa = -stepa;\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfmm, stepa);\n } else if (nfm > n) {\n stepa = interpolationPoints.getEntry(nfx, nfxm);\n stepb = -initialTrustRegionRadius;\n if (lowerDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.min(TWO * initialTrustRegionRadius, upperDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n if (upperDifference.getEntry(nfxm) == ZERO) {\n stepb = Math.max(-TWO * initialTrustRegionRadius, lowerDifference.getEntry(nfxm));\n throw new PathIsExploredException(); \n }\n interpolationPoints.setEntry(nfm, nfxm, stepb);\n }\n } else {\n final int tmp1 = (nfm - np) / n;\n jpt = nfm - tmp1 * n - n;\n ipt = jpt + tmp1;\n if (ipt > n) {\n final int tmp2 = jpt;\n jpt = ipt - n;\n ipt = tmp2;\n }\n final int iptMinus1 = ipt - 1;\n final int jptMinus1 = jpt - 1;\n interpolationPoints.setEntry(nfm, iptMinus1, interpolationPoints.getEntry(ipt, iptMinus1));\n interpolationPoints.setEntry(nfm, jptMinus1, interpolationPoints.getEntry(jpt, jptMinus1));\n }\n for (int j = 0; j < n; j++) {\n currentBest.setEntry(j, Math.min(Math.max(lowerBound[j],\n originShift.getEntry(j) + interpolationPoints.getEntry(nfm, j)),\n upperBound[j]));\n if (interpolationPoints.getEntry(nfm, j) == lowerDifference.getEntry(j)) {\n currentBest.setEntry(j, lowerBound[j]);\n }\n if (interpolationPoints.getEntry(nfm, j) == upperDifference.getEntry(j)) {\n currentBest.setEntry(j, upperBound[j]);\n }\n }\n final double objectiveValue = computeObjectiveValue(currentBest.toArray());\n final double f = isMinimize ? objectiveValue : -objectiveValue;\n final int numEval = getEvaluations(); \n fAtInterpolationPoints.setEntry(nfm, f);\n if (numEval == 1) {\n fbeg = f;\n trustRegionCenterInterpolationPointIndex = 0;\n } else if (f < fAtInterpolationPoints.getEntry(trustRegionCenterInterpolationPointIndex)) {\n trustRegionCenterInterpolationPointIndex = nfm;\n }\n if (numEval <= 2 * n + 1) {\n if (numEval >= 2 &&\n numEval <= n + 1) {\n gradientAtTrustRegionCenter.setEntry(nfmm, (f - fbeg) / stepa);\n if (npt < numEval + n) {\n final double oneOverStepA = ONE / stepa;\n bMatrix.setEntry(0, nfmm, -oneOverStepA);\n bMatrix.setEntry(nfm, nfmm, oneOverStepA);\n bMatrix.setEntry(npt + nfmm, nfmm, -HALF * rhosq);\n throw new PathIsExploredException(); \n }\n } else if (numEval >= n + 2) {\n final int ih = nfx * (nfx + 1) / 2 - 1;\n final double tmp = (f - fbeg) / stepb;\n final double diff = stepb - stepa;\n modelSecondDerivativesValues.setEntry(ih, TWO * (tmp - gradientAtTrustRegionCenter.getEntry(nfxm)) / diff);\n gradientAtTrustRegionCenter.setEntry(nfxm, (gradientAtTrustRegionCenter.getEntry(nfxm) * stepb - tmp * stepa) / diff);\n if (stepa * stepb < ZERO) {\n if (f < fAtInterpolationPoints.getEntry(nfm - n)) {\n fAtInterpolationPoints.setEntry(nfm, fAtInterpolationPoints.getEntry(nfm - n));\n fAtInterpolationPoints.setEntry(nfm - n, f);\n if (trustRegionCenterInterpolationPointIndex == nfm) {\n trustRegionCenterInterpolationPointIndex = nfm - n;\n }\n interpolationPoints.setEntry(nfm - n, nfxm, stepb);\n interpolationPoints.setEntry(nfm, nfxm, stepa);\n }\n }\n bMatrix.setEntry(0, nfxm, -(stepa + stepb) / (stepa * stepb));\n bMatrix.setEntry(nfm, nfxm, -HALF / interpolationPoints.getEntry(nfm - n, nfxm));\n bMatrix.setEntry(nfm - n, nfxm,\n -bMatrix.getEntry(0, nfxm) - bMatrix.getEntry(nfm, nfxm));\n zMatrix.setEntry(0, nfxm, Math.sqrt(TWO) / (stepa * stepb));\n zMatrix.setEntry(nfm, nfxm, Math.sqrt(HALF) / rhosq);\n zMatrix.setEntry(nfm - n, nfxm,\n -zMatrix.getEntry(0, nfxm) - zMatrix.getEntry(nfm, nfxm));\n }\n } else {\n zMatrix.setEntry(0, nfxm, recip);\n zMatrix.setEntry(nfm, nfxm, recip);\n zMatrix.setEntry(ipt, nfxm, -recip);\n zMatrix.setEntry(jpt, nfxm, -recip);\n final int ih = ipt * (ipt - 1) / 2 + jpt - 1;\n final double tmp = interpolationPoints.getEntry(nfm, ipt - 1) * interpolationPoints.getEntry(nfm, jpt - 1);\n modelSecondDerivativesValues.setEntry(ih, (fbeg - fAtInterpolationPoints.getEntry(ipt) - fAtInterpolationPoints.getEntry(jpt) + f) / tmp);\n }\n } while (getEvaluations() < npt);\n } \n", "tests": {}, "repo_meta": {"bug_id": "Math-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-38"}} {"sample_uid": "defects4j_function_repair::Lang-37", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static T[] addAll(T[] array1, T... array2) {\n if (array1 == null) {\n return clone(array2);\n } else if (array2 == null) {\n return clone(array1);\n }\n final Class type1 = array1.getClass().getComponentType();\n T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static T[] addAll(T[] array1, T... array2) {\n if (array1 == null) {\n return clone(array2);\n } else if (array2 == null) {\n return clone(array1);\n }\n final Class type1 = array1.getClass().getComponentType();\n T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n return joinedArray;\n }\n"}, "reference": " public static T[] addAll(T[] array1, T... array2) {\n if (array1 == null) {\n return clone(array2);\n } else if (array2 == null) {\n return clone(array1);\n }\n final Class type1 = array1.getClass().getComponentType();\n T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);\n System.arraycopy(array1, 0, joinedArray, 0, array1.length);\n try {\n System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);\n } catch (ArrayStoreException ase) {\n final Class type2 = array2.getClass().getComponentType();\n if (!type1.isAssignableFrom(type2)){\n throw new IllegalArgumentException(\"Cannot store \"+type2.getName()+\" in an array of \"+type1.getName());\n }\n throw ase; \n }\n return joinedArray;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-37"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-37"}} {"sample_uid": "defects4j_function_repair::Closure-132", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryMinimizeIf(Node n) {\n Node parent = n.getParent();\n Node cond = n.getFirstChild();\n if (NodeUtil.isLiteralValue(cond, true)) {\n return n;\n }\n Node thenBranch = cond.getNext();\n Node elseBranch = thenBranch.getNext();\n if (elseBranch == null) {\n if (isFoldableExpressBlock(thenBranch)) {\n Node expr = getBlockExpression(thenBranch);\n if (!late && isPropertyAssignmentInExpression(expr)) {\n return n;\n }\n if (cond.isNot()) {\n if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n OR_PRECEDENCE)) {\n return n;\n }\n Node or = IR.or(\n cond.removeFirstChild(),\n expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(or);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n }\n if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n AND_PRECEDENCE)) {\n return n;\n }\n n.removeChild(cond);\n Node and = IR.and(cond, expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(and);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n } else {\n if (NodeUtil.isStatementBlock(thenBranch) &&\n thenBranch.hasOneChild()) {\n Node innerIf = thenBranch.getFirstChild();\n if (innerIf.isIf()) {\n Node innerCond = innerIf.getFirstChild();\n Node innerThenBranch = innerCond.getNext();\n Node innerElseBranch = innerThenBranch.getNext();\n if (innerElseBranch == null &&\n !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) {\n n.detachChildren();\n n.addChildToBack(\n IR.and(\n cond,\n innerCond.detachFromParent())\n .srcref(cond));\n n.addChildrenToBack(innerThenBranch.detachFromParent());\n reportCodeChange();\n return n;\n }\n }\n }\n }\n return n;\n }\n tryRemoveRepeatedStatements(n);\n if (cond.isNot() && !consumesDanglingElse(elseBranch)) {\n n.replaceChild(cond, cond.removeFirstChild());\n n.removeChild(thenBranch);\n n.addChildToBack(thenBranch);\n reportCodeChange();\n return n;\n }\n if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) {\n Node thenExpr = getBlockReturnExpression(thenBranch);\n Node elseExpr = getBlockReturnExpression(elseBranch);\n n.removeChild(cond);\n thenExpr.detachFromParent();\n elseExpr.detachFromParent();\n Node returnNode = IR.returnNode(\n IR.hook(cond, thenExpr, elseExpr)\n .srcref(n));\n parent.replaceChild(n, returnNode);\n reportCodeChange();\n return returnNode;\n }\n boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch);\n boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch);\n if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) {\n Node thenOp = getBlockExpression(thenBranch).getFirstChild();\n Node elseOp = getBlockExpression(elseBranch).getFirstChild();\n if (thenOp.getType() == elseOp.getType()) {\n if (NodeUtil.isAssignmentOp(thenOp)) {\n Node lhs = thenOp.getFirstChild();\n if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) &&\n !mayEffectMutableState(lhs)) {\n n.removeChild(cond);\n Node assignName = thenOp.removeFirstChild();\n Node thenExpr = thenOp.removeFirstChild();\n Node elseExpr = elseOp.getLastChild();\n elseOp.removeChild(elseExpr);\n Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n);\n Node assign = new Node(thenOp.getType(), assignName, hookNode)\n .srcref(thenOp);\n Node expr = NodeUtil.newExpr(assign);\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n }\n }\n n.removeChild(cond);\n thenOp.detachFromParent();\n elseOp.detachFromParent();\n Node expr = IR.exprResult(\n IR.hook(cond, thenOp, elseOp).srcref(n));\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n boolean thenBranchIsVar = isVarBlock(thenBranch);\n boolean elseBranchIsVar = isVarBlock(elseBranch);\n if (thenBranchIsVar && elseBranchIsExpressionBlock &&\n getBlockExpression(elseBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(thenBranch);\n Node elseAssign = getBlockExpression(elseBranch).getFirstChild();\n Node name1 = var.getFirstChild();\n Node maybeName2 = elseAssign.getFirstChild();\n if (name1.hasChildren()\n && maybeName2.isName()\n && name1.getString().equals(maybeName2.getString())) {\n Node thenExpr = name1.removeChildren();\n Node elseExpr = elseAssign.getLastChild().detachFromParent();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name1.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n } else if (elseBranchIsVar && thenBranchIsExpressionBlock &&\n getBlockExpression(thenBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(elseBranch);\n Node thenAssign = getBlockExpression(thenBranch).getFirstChild();\n Node maybeName1 = thenAssign.getFirstChild();\n Node name2 = var.getFirstChild();\n if (name2.hasChildren()\n && maybeName1.isName()\n && maybeName1.getString().equals(name2.getString())) {\n Node thenExpr = thenAssign.getLastChild().detachFromParent();\n Node elseExpr = name2.removeChildren();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name2.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n }\n return n;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryMinimizeIf(Node n) {\n Node parent = n.getParent();\n Node cond = n.getFirstChild();\n if (NodeUtil.isLiteralValue(cond, true)) {\n return n;\n }\n Node thenBranch = cond.getNext();\n Node elseBranch = thenBranch.getNext();\n if (elseBranch == null) {\n if (isFoldableExpressBlock(thenBranch)) {\n Node expr = getBlockExpression(thenBranch);\n if (!late && isPropertyAssignmentInExpression(expr)) {\n return n;\n }\n if (cond.isNot()) {\n if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n OR_PRECEDENCE)) {\n return n;\n }\n Node or = IR.or(\n cond.removeFirstChild(),\n expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(or);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n }\n if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n AND_PRECEDENCE)) {\n return n;\n }\n n.removeChild(cond);\n Node and = IR.and(cond, expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(and);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n } else {\n if (NodeUtil.isStatementBlock(thenBranch) &&\n thenBranch.hasOneChild()) {\n Node innerIf = thenBranch.getFirstChild();\n if (innerIf.isIf()) {\n Node innerCond = innerIf.getFirstChild();\n Node innerThenBranch = innerCond.getNext();\n Node innerElseBranch = innerThenBranch.getNext();\n if (innerElseBranch == null &&\n !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) {\n n.detachChildren();\n n.addChildToBack(\n IR.and(\n cond,\n innerCond.detachFromParent())\n .srcref(cond));\n n.addChildrenToBack(innerThenBranch.detachFromParent());\n reportCodeChange();\n return n;\n }\n }\n }\n }\n return n;\n }\n tryRemoveRepeatedStatements(n);\n if (cond.isNot() && !consumesDanglingElse(elseBranch)) {\n n.replaceChild(cond, cond.removeFirstChild());\n n.removeChild(thenBranch);\n n.addChildToBack(thenBranch);\n reportCodeChange();\n return n;\n }\n if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) {\n Node thenExpr = getBlockReturnExpression(thenBranch);\n Node elseExpr = getBlockReturnExpression(elseBranch);\n n.removeChild(cond);\n thenExpr.detachFromParent();\n elseExpr.detachFromParent();\n Node returnNode = IR.returnNode(\n IR.hook(cond, thenExpr, elseExpr)\n .srcref(n));\n parent.replaceChild(n, returnNode);\n reportCodeChange();\n return returnNode;\n }\n boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch);\n boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch);\n if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) {\n Node thenOp = getBlockExpression(thenBranch).getFirstChild();\n Node elseOp = getBlockExpression(elseBranch).getFirstChild();\n if (thenOp.getType() == elseOp.getType()) {\n if (NodeUtil.isAssignmentOp(thenOp)) {\n Node lhs = thenOp.getFirstChild();\n if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) &&\n !mayEffectMutableState(lhs)) {\n n.removeChild(cond);\n Node assignName = thenOp.removeFirstChild();\n Node thenExpr = thenOp.removeFirstChild();\n Node elseExpr = elseOp.getLastChild();\n elseOp.removeChild(elseExpr);\n Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n);\n Node assign = new Node(thenOp.getType(), assignName, hookNode)\n .srcref(thenOp);\n Node expr = NodeUtil.newExpr(assign);\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n }\n }\n n.removeChild(cond);\n thenOp.detachFromParent();\n elseOp.detachFromParent();\n Node expr = IR.exprResult(\n IR.hook(cond, thenOp, elseOp).srcref(n));\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n boolean thenBranchIsVar = isVarBlock(thenBranch);\n boolean elseBranchIsVar = isVarBlock(elseBranch);\n if (thenBranchIsVar && elseBranchIsExpressionBlock &&\n getBlockExpression(elseBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(thenBranch);\n Node elseAssign = getBlockExpression(elseBranch).getFirstChild();\n Node name1 = var.getFirstChild();\n Node maybeName2 = elseAssign.getFirstChild();\n if (name1.hasChildren()\n && maybeName2.isName()\n && name1.getString().equals(maybeName2.getString())) {\n Node thenExpr = name1.removeChildren();\n Node elseExpr = elseAssign.getLastChild().detachFromParent();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name1.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n } else if (elseBranchIsVar && thenBranchIsExpressionBlock &&\n getBlockExpression(thenBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(elseBranch);\n Node thenAssign = getBlockExpression(thenBranch).getFirstChild();\n Node maybeName1 = thenAssign.getFirstChild();\n Node name2 = var.getFirstChild();\n if (name2.hasChildren()\n && maybeName1.isName()\n && maybeName1.getString().equals(name2.getString())) {\n Node thenExpr = thenAssign.getLastChild().detachFromParent();\n Node elseExpr = name2.removeChildren();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name2.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n }\n return n;\n }\n"}, "reference": " private Node tryMinimizeIf(Node n) {\n Node parent = n.getParent();\n Node cond = n.getFirstChild();\n if (NodeUtil.isLiteralValue(cond, true)) {\n return n;\n }\n Node thenBranch = cond.getNext();\n Node elseBranch = thenBranch.getNext();\n if (elseBranch == null) {\n if (isFoldableExpressBlock(thenBranch)) {\n Node expr = getBlockExpression(thenBranch);\n if (!late && isPropertyAssignmentInExpression(expr)) {\n return n;\n }\n if (cond.isNot()) {\n if (isLowerPrecedenceInExpression(cond, OR_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n OR_PRECEDENCE)) {\n return n;\n }\n Node or = IR.or(\n cond.removeFirstChild(),\n expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(or);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n }\n if (isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(expr.getFirstChild(),\n AND_PRECEDENCE)) {\n return n;\n }\n n.removeChild(cond);\n Node and = IR.and(cond, expr.removeFirstChild()).srcref(n);\n Node newExpr = NodeUtil.newExpr(and);\n parent.replaceChild(n, newExpr);\n reportCodeChange();\n return newExpr;\n } else {\n if (NodeUtil.isStatementBlock(thenBranch) &&\n thenBranch.hasOneChild()) {\n Node innerIf = thenBranch.getFirstChild();\n if (innerIf.isIf()) {\n Node innerCond = innerIf.getFirstChild();\n Node innerThenBranch = innerCond.getNext();\n Node innerElseBranch = innerThenBranch.getNext();\n if (innerElseBranch == null &&\n !(isLowerPrecedenceInExpression(cond, AND_PRECEDENCE) &&\n isLowerPrecedenceInExpression(innerCond, AND_PRECEDENCE))) {\n n.detachChildren();\n n.addChildToBack(\n IR.and(\n cond,\n innerCond.detachFromParent())\n .srcref(cond));\n n.addChildrenToBack(innerThenBranch.detachFromParent());\n reportCodeChange();\n return n;\n }\n }\n }\n }\n return n;\n }\n tryRemoveRepeatedStatements(n);\n if (cond.isNot() && !consumesDanglingElse(elseBranch)) {\n n.replaceChild(cond, cond.removeFirstChild());\n n.removeChild(thenBranch);\n n.addChildToBack(thenBranch);\n reportCodeChange();\n return n;\n }\n if (isReturnExpressBlock(thenBranch) && isReturnExpressBlock(elseBranch)) {\n Node thenExpr = getBlockReturnExpression(thenBranch);\n Node elseExpr = getBlockReturnExpression(elseBranch);\n n.removeChild(cond);\n thenExpr.detachFromParent();\n elseExpr.detachFromParent();\n Node returnNode = IR.returnNode(\n IR.hook(cond, thenExpr, elseExpr)\n .srcref(n));\n parent.replaceChild(n, returnNode);\n reportCodeChange();\n return returnNode;\n }\n boolean thenBranchIsExpressionBlock = isFoldableExpressBlock(thenBranch);\n boolean elseBranchIsExpressionBlock = isFoldableExpressBlock(elseBranch);\n if (thenBranchIsExpressionBlock && elseBranchIsExpressionBlock) {\n Node thenOp = getBlockExpression(thenBranch).getFirstChild();\n Node elseOp = getBlockExpression(elseBranch).getFirstChild();\n if (thenOp.getType() == elseOp.getType()) {\n if (NodeUtil.isAssignmentOp(thenOp)) {\n Node lhs = thenOp.getFirstChild();\n if (areNodesEqualForInlining(lhs, elseOp.getFirstChild()) &&\n !mayEffectMutableState(lhs) &&\n (!mayHaveSideEffects(cond) ||\n (thenOp.isAssign() && thenOp.getFirstChild().isName()))) {\n n.removeChild(cond);\n Node assignName = thenOp.removeFirstChild();\n Node thenExpr = thenOp.removeFirstChild();\n Node elseExpr = elseOp.getLastChild();\n elseOp.removeChild(elseExpr);\n Node hookNode = IR.hook(cond, thenExpr, elseExpr).srcref(n);\n Node assign = new Node(thenOp.getType(), assignName, hookNode)\n .srcref(thenOp);\n Node expr = NodeUtil.newExpr(assign);\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n }\n }\n n.removeChild(cond);\n thenOp.detachFromParent();\n elseOp.detachFromParent();\n Node expr = IR.exprResult(\n IR.hook(cond, thenOp, elseOp).srcref(n));\n parent.replaceChild(n, expr);\n reportCodeChange();\n return expr;\n }\n boolean thenBranchIsVar = isVarBlock(thenBranch);\n boolean elseBranchIsVar = isVarBlock(elseBranch);\n if (thenBranchIsVar && elseBranchIsExpressionBlock &&\n getBlockExpression(elseBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(thenBranch);\n Node elseAssign = getBlockExpression(elseBranch).getFirstChild();\n Node name1 = var.getFirstChild();\n Node maybeName2 = elseAssign.getFirstChild();\n if (name1.hasChildren()\n && maybeName2.isName()\n && name1.getString().equals(maybeName2.getString())) {\n Node thenExpr = name1.removeChildren();\n Node elseExpr = elseAssign.getLastChild().detachFromParent();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name1.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n } else if (elseBranchIsVar && thenBranchIsExpressionBlock &&\n getBlockExpression(thenBranch).getFirstChild().isAssign()) {\n Node var = getBlockVar(elseBranch);\n Node thenAssign = getBlockExpression(thenBranch).getFirstChild();\n Node maybeName1 = thenAssign.getFirstChild();\n Node name2 = var.getFirstChild();\n if (name2.hasChildren()\n && maybeName1.isName()\n && maybeName1.getString().equals(name2.getString())) {\n Node thenExpr = thenAssign.getLastChild().detachFromParent();\n Node elseExpr = name2.removeChildren();\n cond.detachFromParent();\n Node hookNode = IR.hook(cond, thenExpr, elseExpr)\n .srcref(n);\n var.detachFromParent();\n name2.addChildrenToBack(hookNode);\n parent.replaceChild(n, var);\n reportCodeChange();\n return var;\n }\n }\n return n;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-132"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-132"}} {"sample_uid": "defects4j_function_repair::Chart-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public MultiplePiePlot(CategoryDataset dataset) {\n super();\n this.dataset = dataset;\n PiePlot piePlot = new PiePlot(null);\n this.pieChart = new JFreeChart(piePlot);\n this.pieChart.removeLegend();\n this.dataExtractOrder = TableOrder.BY_COLUMN;\n this.pieChart.setBackgroundPaint(null);\n TextTitle seriesTitle = new TextTitle(\"Series Title\",\n new Font(\"SansSerif\", Font.BOLD, 12));\n seriesTitle.setPosition(RectangleEdge.BOTTOM);\n this.pieChart.setTitle(seriesTitle);\n this.aggregatedItemsKey = \"Other\";\n this.aggregatedItemsPaint = Color.lightGray;\n this.sectionPaints = new HashMap();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public MultiplePiePlot(CategoryDataset dataset) {\n super();\n this.dataset = dataset;\n PiePlot piePlot = new PiePlot(null);\n this.pieChart = new JFreeChart(piePlot);\n this.pieChart.removeLegend();\n this.dataExtractOrder = TableOrder.BY_COLUMN;\n this.pieChart.setBackgroundPaint(null);\n TextTitle seriesTitle = new TextTitle(\"Series Title\",\n new Font(\"SansSerif\", Font.BOLD, 12));\n seriesTitle.setPosition(RectangleEdge.BOTTOM);\n this.pieChart.setTitle(seriesTitle);\n this.aggregatedItemsKey = \"Other\";\n this.aggregatedItemsPaint = Color.lightGray;\n this.sectionPaints = new HashMap();\n }\n"}, "reference": " public MultiplePiePlot(CategoryDataset dataset) {\n super();\n setDataset(dataset);\n PiePlot piePlot = new PiePlot(null);\n this.pieChart = new JFreeChart(piePlot);\n this.pieChart.removeLegend();\n this.dataExtractOrder = TableOrder.BY_COLUMN;\n this.pieChart.setBackgroundPaint(null);\n TextTitle seriesTitle = new TextTitle(\"Series Title\",\n new Font(\"SansSerif\", Font.BOLD, 12));\n seriesTitle.setPosition(RectangleEdge.BOTTOM);\n this.pieChart.setTitle(seriesTitle);\n this.aggregatedItemsKey = \"Other\";\n this.aggregatedItemsPaint = Color.lightGray;\n this.sectionPaints = new HashMap();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-12"}} {"sample_uid": "defects4j_function_repair::Closure-125", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void visitNew(NodeTraversal t, Node n) {\n Node constructor = n.getFirstChild();\n JSType type = getJSType(constructor).restrictByNotNullOrUndefined();\n if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {\n FunctionType fnType = type.toMaybeFunctionType();\n if (fnType != null) {\n visitParameterList(t, n, fnType);\n ensureTyped(t, n, fnType.getInstanceType());\n } else {\n ensureTyped(t, n);\n }\n } else {\n report(t, n, NOT_A_CONSTRUCTOR);\n ensureTyped(t, n);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void visitNew(NodeTraversal t, Node n) {\n Node constructor = n.getFirstChild();\n JSType type = getJSType(constructor).restrictByNotNullOrUndefined();\n if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {\n FunctionType fnType = type.toMaybeFunctionType();\n if (fnType != null) {\n visitParameterList(t, n, fnType);\n ensureTyped(t, n, fnType.getInstanceType());\n } else {\n ensureTyped(t, n);\n }\n } else {\n report(t, n, NOT_A_CONSTRUCTOR);\n ensureTyped(t, n);\n }\n }\n"}, "reference": " private void visitNew(NodeTraversal t, Node n) {\n Node constructor = n.getFirstChild();\n JSType type = getJSType(constructor).restrictByNotNullOrUndefined();\n if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {\n FunctionType fnType = type.toMaybeFunctionType();\n if (fnType != null && fnType.hasInstanceType()) {\n visitParameterList(t, n, fnType);\n ensureTyped(t, n, fnType.getInstanceType());\n } else {\n ensureTyped(t, n);\n }\n } else {\n report(t, n, NOT_A_CONSTRUCTOR);\n ensureTyped(t, n);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-125"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-125"}} {"sample_uid": "defects4j_function_repair::Lang-16", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos || expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n if (expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos || expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n if (expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n }\n }\n"}, "reference": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\") || str.startsWith(\"0X\") || str.startsWith(\"-0X\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos || expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n if (expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) { \n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) { \n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-16"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-16"}} {"sample_uid": "defects4j_function_repair::Codec-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Base64() {\n this(false);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Base64() {\n this(false);\n }\n"}, "reference": " public Base64() {\n this(0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-4"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.getCurrentToken() == JsonToken.START_OBJECT) {\n p.nextToken();\n return deserializeObject(p, ctxt, ctxt.getNodeFactory());\n }\n if (p.getCurrentToken() == JsonToken.FIELD_NAME) {\n return deserializeObject(p, ctxt, ctxt.getNodeFactory());\n }\n throw ctxt.mappingException(ObjectNode.class);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.getCurrentToken() == JsonToken.START_OBJECT) {\n p.nextToken();\n return deserializeObject(p, ctxt, ctxt.getNodeFactory());\n }\n if (p.getCurrentToken() == JsonToken.FIELD_NAME) {\n return deserializeObject(p, ctxt, ctxt.getNodeFactory());\n }\n throw ctxt.mappingException(ObjectNode.class);\n }\n"}, "reference": " public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.isExpectedStartObjectToken() || p.hasToken(JsonToken.FIELD_NAME)) {\n return deserializeObject(p, ctxt, ctxt.getNodeFactory());\n }\n if (p.hasToken(JsonToken.END_OBJECT)) {\n return ctxt.getNodeFactory().objectNode();\n }\n throw ctxt.mappingException(ObjectNode.class);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-28"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-16", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final boolean _add(Annotation ann) {\n if (_annotations == null) {\n _annotations = new HashMap,Annotation>();\n }\n Annotation previous = _annotations.put(ann.annotationType(), ann);\n return (previous != null) && previous.equals(ann);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final boolean _add(Annotation ann) {\n if (_annotations == null) {\n _annotations = new HashMap,Annotation>();\n }\n Annotation previous = _annotations.put(ann.annotationType(), ann);\n return (previous != null) && previous.equals(ann);\n }\n"}, "reference": " protected final boolean _add(Annotation ann) {\n if (_annotations == null) {\n _annotations = new HashMap,Annotation>();\n }\n Annotation previous = _annotations.put(ann.annotationType(), ann);\n return (previous == null) || !previous.equals(ann);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-16"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-16"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-88", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException\n {\n TypeFactory tf = ctxt.getTypeFactory();\n if (id.indexOf('<') > 0) {\n JavaType t = tf.constructFromCanonical(id);\n return t;\n }\n Class cls;\n try {\n cls = tf.findClass(id);\n } catch (ClassNotFoundException e) {\n if (ctxt instanceof DeserializationContext) {\n DeserializationContext dctxt = (DeserializationContext) ctxt;\n return dctxt.handleUnknownTypeId(_baseType, id, this, \"no such class found\");\n }\n return null;\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Invalid type id '\"+id+\"' (for id type 'Id.class'): \"+e.getMessage(), e);\n }\n return tf.constructSpecializedType(_baseType, cls);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException\n {\n TypeFactory tf = ctxt.getTypeFactory();\n if (id.indexOf('<') > 0) {\n JavaType t = tf.constructFromCanonical(id);\n return t;\n }\n Class cls;\n try {\n cls = tf.findClass(id);\n } catch (ClassNotFoundException e) {\n if (ctxt instanceof DeserializationContext) {\n DeserializationContext dctxt = (DeserializationContext) ctxt;\n return dctxt.handleUnknownTypeId(_baseType, id, this, \"no such class found\");\n }\n return null;\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Invalid type id '\"+id+\"' (for id type 'Id.class'): \"+e.getMessage(), e);\n }\n return tf.constructSpecializedType(_baseType, cls);\n }\n"}, "reference": " protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException\n {\n TypeFactory tf = ctxt.getTypeFactory();\n if (id.indexOf('<') > 0) {\n JavaType t = tf.constructFromCanonical(id);\n if (!t.isTypeOrSubTypeOf(_baseType.getRawClass())) {\n throw new IllegalArgumentException(String.format(\n \"Class %s not subtype of %s\", t.getRawClass().getName(), _baseType));\n }\n return t;\n }\n Class cls;\n try {\n cls = tf.findClass(id);\n } catch (ClassNotFoundException e) {\n if (ctxt instanceof DeserializationContext) {\n DeserializationContext dctxt = (DeserializationContext) ctxt;\n return dctxt.handleUnknownTypeId(_baseType, id, this, \"no such class found\");\n }\n return null;\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Invalid type id '\"+id+\"' (for id type 'Id.class'): \"+e.getMessage(), e);\n }\n return tf.constructSpecializedType(_baseType, cls);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-88"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-88"}} {"sample_uid": "defects4j_function_repair::Closure-35", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void inferPropertyTypesToMatchConstraint(\n JSType type, JSType constraint) {\n if (type == null || constraint == null) {\n return;\n }\n ObjectType constraintObj =\n ObjectType.cast(constraint.restrictByNotNullOrUndefined());\n if (constraintObj != null && constraintObj.isRecordType()) {\n ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined());\n if (objType != null) {\n for (String prop : constraintObj.getOwnPropertyNames()) {\n JSType propType = constraintObj.getPropertyType(prop);\n if (!objType.isPropertyTypeDeclared(prop)) {\n JSType typeToInfer = propType;\n if (!objType.hasProperty(prop)) {\n typeToInfer =\n getNativeType(VOID_TYPE).getLeastSupertype(propType);\n }\n objType.defineInferredProperty(prop, typeToInfer, null);\n }\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void inferPropertyTypesToMatchConstraint(\n JSType type, JSType constraint) {\n if (type == null || constraint == null) {\n return;\n }\n ObjectType constraintObj =\n ObjectType.cast(constraint.restrictByNotNullOrUndefined());\n if (constraintObj != null && constraintObj.isRecordType()) {\n ObjectType objType = ObjectType.cast(type.restrictByNotNullOrUndefined());\n if (objType != null) {\n for (String prop : constraintObj.getOwnPropertyNames()) {\n JSType propType = constraintObj.getPropertyType(prop);\n if (!objType.isPropertyTypeDeclared(prop)) {\n JSType typeToInfer = propType;\n if (!objType.hasProperty(prop)) {\n typeToInfer =\n getNativeType(VOID_TYPE).getLeastSupertype(propType);\n }\n objType.defineInferredProperty(prop, typeToInfer, null);\n }\n }\n }\n }\n }\n"}, "reference": " private void inferPropertyTypesToMatchConstraint(\n JSType type, JSType constraint) {\n if (type == null || constraint == null) {\n return;\n }\n ObjectType constraintObj =\n ObjectType.cast(constraint.restrictByNotNullOrUndefined());\n if (constraintObj != null) {\n type.matchConstraint(constraintObj);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-35"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-35"}} {"sample_uid": "defects4j_function_repair::Closure-19", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void declareNameInScope(FlowScope scope, Node node, JSType type) {\n switch (node.getType()) {\n case Token.NAME:\n scope.inferSlotType(node.getString(), type);\n break;\n case Token.GETPROP:\n String qualifiedName = node.getQualifiedName();\n Preconditions.checkNotNull(qualifiedName);\n JSType origType = node.getJSType();\n origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType;\n scope.inferQualifiedSlot(node, qualifiedName, origType, type);\n break;\n default:\n throw new IllegalArgumentException(\"Node cannot be refined. \\n\" +\n node.toStringTree());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void declareNameInScope(FlowScope scope, Node node, JSType type) {\n switch (node.getType()) {\n case Token.NAME:\n scope.inferSlotType(node.getString(), type);\n break;\n case Token.GETPROP:\n String qualifiedName = node.getQualifiedName();\n Preconditions.checkNotNull(qualifiedName);\n JSType origType = node.getJSType();\n origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType;\n scope.inferQualifiedSlot(node, qualifiedName, origType, type);\n break;\n default:\n throw new IllegalArgumentException(\"Node cannot be refined. \\n\" +\n node.toStringTree());\n }\n }\n"}, "reference": " protected void declareNameInScope(FlowScope scope, Node node, JSType type) {\n switch (node.getType()) {\n case Token.NAME:\n scope.inferSlotType(node.getString(), type);\n break;\n case Token.GETPROP:\n String qualifiedName = node.getQualifiedName();\n Preconditions.checkNotNull(qualifiedName);\n JSType origType = node.getJSType();\n origType = origType == null ? getNativeType(UNKNOWN_TYPE) : origType;\n scope.inferQualifiedSlot(node, qualifiedName, origType, type);\n break;\n case Token.THIS:\n break;\n default:\n throw new IllegalArgumentException(\"Node cannot be refined. \\n\" +\n node.toStringTree());\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-19"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-19"}} {"sample_uid": "defects4j_function_repair::Jsoup-76", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (tb.framesetOk() && isWhitespace(c)) { \n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.normalName();\n if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.processEndTag(\"a\");\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"span\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.processEndTag(\"li\");\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().get(0);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.remove(stack.size()-1);\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertForm(startTag, true);\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) {\n tb.processEndTag(el.nodeName());\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.processEndTag(\"button\");\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (StringUtil.inSorted(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.processEndTag(\"nobr\");\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n if (tb.getFromStack(\"svg\") == null)\n return tb.process(startTag.name(\"img\")); \n else\n tb.insert(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.processStartTag(\"form\");\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.processStartTag(\"hr\");\n tb.processStartTag(\"label\");\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character().data(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.processStartTag(\"input\", inputAttribs);\n tb.processEndTag(\"label\");\n tb.processStartTag(\"hr\");\n tb.processEndTag(\"form\");\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.processEndTag(\"option\");\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.normalName();\n if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) {\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n ArrayList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue;\n } else if (node == formatEl)\n break;\n Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"span\")) {\n return anyOtherEndTag(t, tb);\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.processEndTag(\"body\");\n if (notIgnored)\n return tb.process(endTag);\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.processStartTag(name); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.processStartTag(\"br\");\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (tb.framesetOk() && isWhitespace(c)) { \n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.normalName();\n if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.processEndTag(\"a\");\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"span\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.processEndTag(\"li\");\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().get(0);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.remove(stack.size()-1);\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertForm(startTag, true);\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) {\n tb.processEndTag(el.nodeName());\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.processEndTag(\"button\");\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (StringUtil.inSorted(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.processEndTag(\"nobr\");\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n if (tb.getFromStack(\"svg\") == null)\n return tb.process(startTag.name(\"img\")); \n else\n tb.insert(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.processStartTag(\"form\");\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.processStartTag(\"hr\");\n tb.processStartTag(\"label\");\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character().data(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.processStartTag(\"input\", inputAttribs);\n tb.processEndTag(\"label\");\n tb.processStartTag(\"hr\");\n tb.processEndTag(\"form\");\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.processEndTag(\"option\");\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.normalName();\n if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) {\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n ArrayList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue;\n } else if (node == formatEl)\n break;\n Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"span\")) {\n return anyOtherEndTag(t, tb);\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.processEndTag(\"body\");\n if (notIgnored)\n return tb.process(endTag);\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.processStartTag(name); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.processStartTag(\"br\");\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n"}, "reference": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (tb.framesetOk() && isWhitespace(c)) { \n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.normalName();\n if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.processEndTag(\"a\");\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"span\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.processEndTag(\"li\");\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().get(0);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n ArrayList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.remove(stack.size()-1);\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.reader.matchConsume(\"\\n\"); \n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertForm(startTag, true);\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n tb.framesetOk(false);\n ArrayList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) {\n tb.processEndTag(el.nodeName());\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.processEndTag(\"button\");\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (StringUtil.inSorted(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.processEndTag(\"nobr\");\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n if (tb.getFromStack(\"svg\") == null)\n return tb.process(startTag.name(\"img\")); \n else\n tb.insert(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.processStartTag(\"form\");\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.processStartTag(\"hr\");\n tb.processStartTag(\"label\");\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character().data(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.processStartTag(\"input\", inputAttribs);\n tb.processEndTag(\"label\");\n tb.processStartTag(\"hr\");\n tb.processEndTag(\"form\");\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.processEndTag(\"p\");\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.processEndTag(\"option\");\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.normalName();\n if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) {\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n ArrayList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue;\n } else if (node == formatEl)\n break;\n Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.inSorted(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"span\")) {\n return anyOtherEndTag(t, tb);\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.processEndTag(\"body\");\n if (notIgnored)\n return tb.process(endTag);\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.processStartTag(name); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.inSorted(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.processStartTag(\"br\");\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-76"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-76"}} {"sample_uid": "defects4j_function_repair::Jsoup-82", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException {\n if (input == null) \n return new Document(baseUri);\n input = ConstrainableInputStream.wrap(input, bufferSize, 0);\n Document doc = null;\n boolean fullyRead = false;\n input.mark(bufferSize);\n ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); \n fullyRead = input.read() == -1;\n input.reset();\n BomCharset bomCharset = detectCharsetFromBom(firstBytes);\n if (bomCharset != null)\n charsetName = bomCharset.charset;\n if (charsetName == null) { \n String docData = Charset.forName(defaultCharset).decode(firstBytes).toString();\n doc = parser.parseInput(docData, baseUri);\n Elements metaElements = doc.select(\"meta[http-equiv=content-type], meta[charset]\");\n String foundCharset = null; \n for (Element meta : metaElements) {\n if (meta.hasAttr(\"http-equiv\"))\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\"))\n foundCharset = meta.attr(\"charset\");\n if (foundCharset != null)\n break;\n }\n if (foundCharset == null && doc.childNodeSize() > 0) {\n Node first = doc.childNode(0);\n XmlDeclaration decl = null;\n if (first instanceof XmlDeclaration)\n decl = (XmlDeclaration) first;\n else if (first instanceof Comment) {\n Comment comment = (Comment) first;\n if (comment.isXmlDeclaration())\n decl = comment.asXmlDeclaration();\n }\n if (decl != null) {\n if (decl.name().equalsIgnoreCase(\"xml\"))\n foundCharset = decl.attr(\"encoding\");\n }\n }\n foundCharset = validateCharset(foundCharset);\n if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n doc = null;\n } else if (!fullyRead) {\n doc = null;\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n }\n if (doc == null) {\n if (charsetName == null)\n charsetName = defaultCharset;\n BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize);\n if (bomCharset != null && bomCharset.offset) \n reader.skip(1);\n try {\n doc = parser.parseInput(reader, baseUri);\n } catch (UncheckedIOException e) {\n throw e.ioException();\n }\n Charset charset = Charset.forName(charsetName);\n doc.outputSettings().charset(charset);\n }\n input.close();\n return doc;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException {\n if (input == null) \n return new Document(baseUri);\n input = ConstrainableInputStream.wrap(input, bufferSize, 0);\n Document doc = null;\n boolean fullyRead = false;\n input.mark(bufferSize);\n ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); \n fullyRead = input.read() == -1;\n input.reset();\n BomCharset bomCharset = detectCharsetFromBom(firstBytes);\n if (bomCharset != null)\n charsetName = bomCharset.charset;\n if (charsetName == null) { \n String docData = Charset.forName(defaultCharset).decode(firstBytes).toString();\n doc = parser.parseInput(docData, baseUri);\n Elements metaElements = doc.select(\"meta[http-equiv=content-type], meta[charset]\");\n String foundCharset = null; \n for (Element meta : metaElements) {\n if (meta.hasAttr(\"http-equiv\"))\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\"))\n foundCharset = meta.attr(\"charset\");\n if (foundCharset != null)\n break;\n }\n if (foundCharset == null && doc.childNodeSize() > 0) {\n Node first = doc.childNode(0);\n XmlDeclaration decl = null;\n if (first instanceof XmlDeclaration)\n decl = (XmlDeclaration) first;\n else if (first instanceof Comment) {\n Comment comment = (Comment) first;\n if (comment.isXmlDeclaration())\n decl = comment.asXmlDeclaration();\n }\n if (decl != null) {\n if (decl.name().equalsIgnoreCase(\"xml\"))\n foundCharset = decl.attr(\"encoding\");\n }\n }\n foundCharset = validateCharset(foundCharset);\n if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n doc = null;\n } else if (!fullyRead) {\n doc = null;\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n }\n if (doc == null) {\n if (charsetName == null)\n charsetName = defaultCharset;\n BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize);\n if (bomCharset != null && bomCharset.offset) \n reader.skip(1);\n try {\n doc = parser.parseInput(reader, baseUri);\n } catch (UncheckedIOException e) {\n throw e.ioException();\n }\n Charset charset = Charset.forName(charsetName);\n doc.outputSettings().charset(charset);\n }\n input.close();\n return doc;\n }\n"}, "reference": " static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException {\n if (input == null) \n return new Document(baseUri);\n input = ConstrainableInputStream.wrap(input, bufferSize, 0);\n Document doc = null;\n boolean fullyRead = false;\n input.mark(bufferSize);\n ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); \n fullyRead = input.read() == -1;\n input.reset();\n BomCharset bomCharset = detectCharsetFromBom(firstBytes);\n if (bomCharset != null)\n charsetName = bomCharset.charset;\n if (charsetName == null) { \n String docData = Charset.forName(defaultCharset).decode(firstBytes).toString();\n doc = parser.parseInput(docData, baseUri);\n Elements metaElements = doc.select(\"meta[http-equiv=content-type], meta[charset]\");\n String foundCharset = null; \n for (Element meta : metaElements) {\n if (meta.hasAttr(\"http-equiv\"))\n foundCharset = getCharsetFromContentType(meta.attr(\"content\"));\n if (foundCharset == null && meta.hasAttr(\"charset\"))\n foundCharset = meta.attr(\"charset\");\n if (foundCharset != null)\n break;\n }\n if (foundCharset == null && doc.childNodeSize() > 0) {\n Node first = doc.childNode(0);\n XmlDeclaration decl = null;\n if (first instanceof XmlDeclaration)\n decl = (XmlDeclaration) first;\n else if (first instanceof Comment) {\n Comment comment = (Comment) first;\n if (comment.isXmlDeclaration())\n decl = comment.asXmlDeclaration();\n }\n if (decl != null) {\n if (decl.name().equalsIgnoreCase(\"xml\"))\n foundCharset = decl.attr(\"encoding\");\n }\n }\n foundCharset = validateCharset(foundCharset);\n if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { \n foundCharset = foundCharset.trim().replaceAll(\"[\\\"']\", \"\");\n charsetName = foundCharset;\n doc = null;\n } else if (!fullyRead) {\n doc = null;\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n }\n if (doc == null) {\n if (charsetName == null)\n charsetName = defaultCharset;\n BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize);\n if (bomCharset != null && bomCharset.offset) \n reader.skip(1);\n try {\n doc = parser.parseInput(reader, baseUri);\n } catch (UncheckedIOException e) {\n throw e.ioException();\n }\n Charset charset = Charset.forName(charsetName);\n doc.outputSettings().charset(charset);\n if (!charset.canEncode()) {\n doc.charset(Charset.forName(defaultCharset));\n }\n }\n input.close();\n return doc;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-82"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-82"}} {"sample_uid": "defects4j_function_repair::Time-22", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected BasePeriod(long duration) {\n this(duration, null, null);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected BasePeriod(long duration) {\n this(duration, null, null);\n }\n"}, "reference": " protected BasePeriod(long duration) {\n super();\n iType = PeriodType.time();\n int[] values = ISOChronology.getInstanceUTC().get(this, duration);\n iType = PeriodType.standard();\n iValues = new int[8];\n System.arraycopy(values, 0, iValues, 4, 4);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-22"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-22"}} {"sample_uid": "defects4j_function_repair::Closure-164", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean isSubtype(JSType other) {\n if (!(other instanceof ArrowType)) {\n return false;\n }\n ArrowType that = (ArrowType) other;\n if (!this.returnType.isSubtype(that.returnType)) {\n return false;\n }\n Node thisParam = parameters.getFirstChild();\n Node thatParam = that.parameters.getFirstChild();\n while (thisParam != null && thatParam != null) {\n JSType thisParamType = thisParam.getJSType();\n JSType thatParamType = thatParam.getJSType();\n if (thisParamType != null) {\n if (thatParamType == null ||\n !thatParamType.isSubtype(thisParamType)) {\n return false;\n }\n }\n boolean thisIsVarArgs = thisParam.isVarArgs();\n boolean thatIsVarArgs = thatParam.isVarArgs();\n if (!thisIsVarArgs) {\n thisParam = thisParam.getNext();\n }\n if (!thatIsVarArgs) {\n thatParam = thatParam.getNext();\n }\n if (thisIsVarArgs && thatIsVarArgs) {\n thisParam = null;\n thatParam = null;\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean isSubtype(JSType other) {\n if (!(other instanceof ArrowType)) {\n return false;\n }\n ArrowType that = (ArrowType) other;\n if (!this.returnType.isSubtype(that.returnType)) {\n return false;\n }\n Node thisParam = parameters.getFirstChild();\n Node thatParam = that.parameters.getFirstChild();\n while (thisParam != null && thatParam != null) {\n JSType thisParamType = thisParam.getJSType();\n JSType thatParamType = thatParam.getJSType();\n if (thisParamType != null) {\n if (thatParamType == null ||\n !thatParamType.isSubtype(thisParamType)) {\n return false;\n }\n }\n boolean thisIsVarArgs = thisParam.isVarArgs();\n boolean thatIsVarArgs = thatParam.isVarArgs();\n if (!thisIsVarArgs) {\n thisParam = thisParam.getNext();\n }\n if (!thatIsVarArgs) {\n thatParam = thatParam.getNext();\n }\n if (thisIsVarArgs && thatIsVarArgs) {\n thisParam = null;\n thatParam = null;\n }\n }\n return true;\n }\n"}, "reference": " public boolean isSubtype(JSType other) {\n if (!(other instanceof ArrowType)) {\n return false;\n }\n ArrowType that = (ArrowType) other;\n if (!this.returnType.isSubtype(that.returnType)) {\n return false;\n }\n Node thisParam = parameters.getFirstChild();\n Node thatParam = that.parameters.getFirstChild();\n while (thisParam != null && thatParam != null) {\n JSType thisParamType = thisParam.getJSType();\n JSType thatParamType = thatParam.getJSType();\n if (thisParamType != null) {\n if (thatParamType == null ||\n !thatParamType.isSubtype(thisParamType)) {\n return false;\n }\n }\n boolean thisIsVarArgs = thisParam.isVarArgs();\n boolean thatIsVarArgs = thatParam.isVarArgs();\n boolean thisIsOptional = thisIsVarArgs || thisParam.isOptionalArg();\n boolean thatIsOptional = thatIsVarArgs || thatParam.isOptionalArg();\n if (!thisIsOptional && thatIsOptional) {\n boolean isTopFunction =\n thatIsVarArgs &&\n (thatParamType == null ||\n thatParamType.isUnknownType() ||\n thatParamType.isNoType());\n if (!isTopFunction) {\n return false;\n }\n }\n if (!thisIsVarArgs) {\n thisParam = thisParam.getNext();\n }\n if (!thatIsVarArgs) {\n thatParam = thatParam.getNext();\n }\n if (thisIsVarArgs && thatIsVarArgs) {\n thisParam = null;\n thatParam = null;\n }\n }\n if (thisParam != null\n && !thisParam.isOptionalArg() && !thisParam.isVarArgs()\n && thatParam == null) {\n return false;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-164"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-164"}} {"sample_uid": "defects4j_function_repair::Math-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double density(final double[] vals) throws DimensionMismatchException {\n final int dim = getDimension();\n if (vals.length != dim) {\n throw new DimensionMismatchException(vals.length, dim);\n }\n return FastMath.pow(2 * FastMath.PI, -dim / 2) *\n FastMath.pow(covarianceMatrixDeterminant, -0.5) *\n getExponentTerm(vals);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double density(final double[] vals) throws DimensionMismatchException {\n final int dim = getDimension();\n if (vals.length != dim) {\n throw new DimensionMismatchException(vals.length, dim);\n }\n return FastMath.pow(2 * FastMath.PI, -dim / 2) *\n FastMath.pow(covarianceMatrixDeterminant, -0.5) *\n getExponentTerm(vals);\n }\n"}, "reference": " public double density(final double[] vals) throws DimensionMismatchException {\n final int dim = getDimension();\n if (vals.length != dim) {\n throw new DimensionMismatchException(vals.length, dim);\n }\n return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *\n FastMath.pow(covarianceMatrixDeterminant, -0.5) *\n getExponentTerm(vals);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-11"}} {"sample_uid": "defects4j_function_repair::Closure-160", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn()) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n if (!options.checkSymbols &&\n (warningsGuard == null || !warningsGuard.disables(\n DiagnosticGroups.CHECK_VARIABLES))) {\n guards.add(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = new ComposeWarningsGuard(guards);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn()) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n if (!options.checkSymbols &&\n (warningsGuard == null || !warningsGuard.disables(\n DiagnosticGroups.CHECK_VARIABLES))) {\n guards.add(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = new ComposeWarningsGuard(guards);\n }\n"}, "reference": " public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn()) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards);\n if (!options.checkSymbols &&\n !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) {\n composedGuards.addGuard(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = composedGuards;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-160"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-160"}} {"sample_uid": "defects4j_function_repair::Closure-50", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryFoldArrayJoin(Node n) {\n Node callTarget = n.getFirstChild();\n if (callTarget == null || !NodeUtil.isGetProp(callTarget)) {\n return n;\n }\n Node right = callTarget.getNext();\n if (right != null) {\n if (!NodeUtil.isImmutableValue(right)) {\n return n;\n }\n }\n Node arrayNode = callTarget.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return n;\n }\n String joinString = (right == null) ? \",\" : NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = null;\n int foldedSize = 0;\n Node prev = null;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) {\n if (sb == null) {\n sb = new StringBuilder();\n } else {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getArrayElementStringValue(elem));\n } else {\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n sb = null;\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n prev = elem;\n elem = elem.getNext();\n }\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n n.getParent().replaceChild(n, emptyStringNode);\n reportCodeChange();\n return emptyStringNode;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\").copyInformationFrom(n),\n foldedStringNode);\n foldedStringNode = replacement;\n }\n n.getParent().replaceChild(n, foldedStringNode);\n reportCodeChange();\n return foldedStringNode;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return n;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0;\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n reportCodeChange();\n break;\n }\n return n;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryFoldArrayJoin(Node n) {\n Node callTarget = n.getFirstChild();\n if (callTarget == null || !NodeUtil.isGetProp(callTarget)) {\n return n;\n }\n Node right = callTarget.getNext();\n if (right != null) {\n if (!NodeUtil.isImmutableValue(right)) {\n return n;\n }\n }\n Node arrayNode = callTarget.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return n;\n }\n String joinString = (right == null) ? \",\" : NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = null;\n int foldedSize = 0;\n Node prev = null;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) {\n if (sb == null) {\n sb = new StringBuilder();\n } else {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getArrayElementStringValue(elem));\n } else {\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n sb = null;\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n prev = elem;\n elem = elem.getNext();\n }\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n n.getParent().replaceChild(n, emptyStringNode);\n reportCodeChange();\n return emptyStringNode;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\").copyInformationFrom(n),\n foldedStringNode);\n foldedStringNode = replacement;\n }\n n.getParent().replaceChild(n, foldedStringNode);\n reportCodeChange();\n return foldedStringNode;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return n;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0;\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n reportCodeChange();\n break;\n }\n return n;\n }\n"}, "reference": " private Node tryFoldArrayJoin(Node n) {\n Node callTarget = n.getFirstChild();\n if (callTarget == null || !NodeUtil.isGetProp(callTarget)) {\n return n;\n }\n Node right = callTarget.getNext();\n if (right != null) {\n if (right.getNext() != null || !NodeUtil.isImmutableValue(right)) {\n return n;\n }\n }\n Node arrayNode = callTarget.getFirstChild();\n Node functionName = arrayNode.getNext();\n if ((arrayNode.getType() != Token.ARRAYLIT) ||\n !functionName.getString().equals(\"join\")) {\n return n;\n }\n if (right != null && right.getType() == Token.STRING\n && \",\".equals(right.getString())) {\n n.removeChild(right);\n reportCodeChange();\n }\n String joinString = (right == null) ? \",\" : NodeUtil.getStringValue(right);\n List arrayFoldedChildren = Lists.newLinkedList();\n StringBuilder sb = null;\n int foldedSize = 0;\n Node prev = null;\n Node elem = arrayNode.getFirstChild();\n while (elem != null) {\n if (NodeUtil.isImmutableValue(elem) || elem.getType() == Token.EMPTY) {\n if (sb == null) {\n sb = new StringBuilder();\n } else {\n sb.append(joinString);\n }\n sb.append(NodeUtil.getArrayElementStringValue(elem));\n } else {\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n sb = null;\n }\n foldedSize += InlineCostEstimator.getCost(elem);\n arrayFoldedChildren.add(elem);\n }\n prev = elem;\n elem = elem.getNext();\n }\n if (sb != null) {\n Preconditions.checkNotNull(prev);\n foldedSize += sb.length() + 2;\n arrayFoldedChildren.add(\n Node.newString(sb.toString()).copyInformationFrom(prev));\n }\n foldedSize += arrayFoldedChildren.size() - 1;\n int originalSize = InlineCostEstimator.getCost(n);\n switch (arrayFoldedChildren.size()) {\n case 0:\n Node emptyStringNode = Node.newString(\"\");\n n.getParent().replaceChild(n, emptyStringNode);\n reportCodeChange();\n return emptyStringNode;\n case 1:\n Node foldedStringNode = arrayFoldedChildren.remove(0);\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n if (foldedStringNode.getType() != Token.STRING) {\n Node replacement = new Node(Token.ADD,\n Node.newString(\"\").copyInformationFrom(n),\n foldedStringNode);\n foldedStringNode = replacement;\n }\n n.getParent().replaceChild(n, foldedStringNode);\n reportCodeChange();\n return foldedStringNode;\n default:\n if (arrayFoldedChildren.size() == arrayNode.getChildCount()) {\n return n;\n }\n int kJoinOverhead = \"[].join()\".length();\n foldedSize += kJoinOverhead;\n foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0;\n if (foldedSize > originalSize) {\n return n;\n }\n arrayNode.detachChildren();\n for (Node node : arrayFoldedChildren) {\n arrayNode.addChildToBack(node);\n }\n reportCodeChange();\n break;\n }\n return n;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-50"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-50"}} {"sample_uid": "defects4j_function_repair::Time-19", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n } else if (offsetLocal > 0) {\n long prev = previousTransition(instantAdjusted);\n if (prev < instantAdjusted) {\n int offsetPrev = getOffset(prev);\n int diff = offsetPrev - offsetLocal;\n if (instantAdjusted - prev <= diff) {\n return offsetPrev;\n }\n }\n }\n return offsetAdjusted;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n } else if (offsetLocal > 0) {\n long prev = previousTransition(instantAdjusted);\n if (prev < instantAdjusted) {\n int offsetPrev = getOffset(prev);\n int diff = offsetPrev - offsetLocal;\n if (instantAdjusted - prev <= diff) {\n return offsetPrev;\n }\n }\n }\n return offsetAdjusted;\n }\n"}, "reference": " public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n } else if (offsetLocal >= 0) {\n long prev = previousTransition(instantAdjusted);\n if (prev < instantAdjusted) {\n int offsetPrev = getOffset(prev);\n int diff = offsetPrev - offsetLocal;\n if (instantAdjusted - prev <= diff) {\n return offsetPrev;\n }\n }\n }\n return offsetAdjusted;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-19"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-19"}} {"sample_uid": "defects4j_function_repair::Math-95", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected double getInitialDomain(double p) {\n double ret;\n double d = getDenominatorDegreesOfFreedom();\n ret = d / (d - 2.0);\n return ret;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected double getInitialDomain(double p) {\n double ret;\n double d = getDenominatorDegreesOfFreedom();\n ret = d / (d - 2.0);\n return ret;\n }\n"}, "reference": " protected double getInitialDomain(double p) {\n double ret = 1.0;\n double d = getDenominatorDegreesOfFreedom();\n if (d > 2.0) {\n ret = d / (d - 2.0);\n }\n return ret;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-95"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-95"}} {"sample_uid": "defects4j_function_repair::JacksonCore-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void _verifySharing()\n {\n if (_hashShared) {\n _hashArea = Arrays.copyOf(_hashArea, _hashArea.length);\n _names = Arrays.copyOf(_names, _names.length);\n _hashShared = false;\n }\n if (_needRehash) {\n rehash();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void _verifySharing()\n {\n if (_hashShared) {\n _hashArea = Arrays.copyOf(_hashArea, _hashArea.length);\n _names = Arrays.copyOf(_names, _names.length);\n _hashShared = false;\n }\n if (_needRehash) {\n rehash();\n }\n }\n"}, "reference": " private void _verifySharing()\n {\n if (_hashShared) {\n _hashArea = Arrays.copyOf(_hashArea, _hashArea.length);\n _names = Arrays.copyOf(_names, _names.length);\n _hashShared = false;\n _verifyNeedForRehash();\n }\n if (_needRehash) {\n rehash();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-11"}} {"sample_uid": "defects4j_function_repair::Math-91", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int compareTo(Fraction object) {\n double nOd = doubleValue();\n double dOn = object.doubleValue();\n return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int compareTo(Fraction object) {\n double nOd = doubleValue();\n double dOn = object.doubleValue();\n return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0);\n }\n"}, "reference": " public int compareTo(Fraction object) {\n long nOd = ((long) numerator) * object.denominator;\n long dOn = ((long) denominator) * object.numerator;\n return (nOd < dOn) ? -1 : ((nOd > dOn) ? +1 : 0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-91"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-91"}} {"sample_uid": "defects4j_function_repair::Math-73", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(yMin, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(yMax, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(yMin, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(yMax, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n"}, "reference": " public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(yMin, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(yMax, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n if (yMin * yMax > 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n NON_BRACKETING_MESSAGE, min, max, yMin, yMax);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-73"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-73"}} {"sample_uid": "defects4j_function_repair::Closure-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private JSType getDeclaredType(String sourceName, JSDocInfo info,\n Node lValue, @Nullable Node rValue) {\n if (info != null && info.hasType()) {\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n } else if (rValue != null && rValue.isFunction() &&\n shouldUseFunctionLiteralType(\n JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) {\n return rValue.getJSType();\n } else if (info != null) {\n if (info.hasEnumParameterType()) {\n if (rValue != null && rValue.isObjectLit()) {\n return rValue.getJSType();\n } else {\n return createEnumTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n }\n } else if (info.isConstructor() || info.isInterface()) {\n return createFunctionTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n } else {\n if (info.isConstant()) {\n JSType knownType = null;\n if (rValue != null) {\n if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) {\n return rValue.getJSType();\n } else if (rValue.isOr()) {\n Node firstClause = rValue.getFirstChild();\n Node secondClause = firstClause.getNext();\n boolean namesMatch = firstClause.isName()\n && lValue.isName()\n && firstClause.getString().equals(lValue.getString());\n if (namesMatch && secondClause.getJSType() != null\n && !secondClause.getJSType().isUnknownType()) {\n return secondClause.getJSType();\n }\n }\n }\n }\n }\n }\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private JSType getDeclaredType(String sourceName, JSDocInfo info,\n Node lValue, @Nullable Node rValue) {\n if (info != null && info.hasType()) {\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n } else if (rValue != null && rValue.isFunction() &&\n shouldUseFunctionLiteralType(\n JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) {\n return rValue.getJSType();\n } else if (info != null) {\n if (info.hasEnumParameterType()) {\n if (rValue != null && rValue.isObjectLit()) {\n return rValue.getJSType();\n } else {\n return createEnumTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n }\n } else if (info.isConstructor() || info.isInterface()) {\n return createFunctionTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n } else {\n if (info.isConstant()) {\n JSType knownType = null;\n if (rValue != null) {\n if (rValue.getJSType() != null && !rValue.getJSType().isUnknownType()) {\n return rValue.getJSType();\n } else if (rValue.isOr()) {\n Node firstClause = rValue.getFirstChild();\n Node secondClause = firstClause.getNext();\n boolean namesMatch = firstClause.isName()\n && lValue.isName()\n && firstClause.getString().equals(lValue.getString());\n if (namesMatch && secondClause.getJSType() != null\n && !secondClause.getJSType().isUnknownType()) {\n return secondClause.getJSType();\n }\n }\n }\n }\n }\n }\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n }\n"}, "reference": " private JSType getDeclaredType(String sourceName, JSDocInfo info,\n Node lValue, @Nullable Node rValue) {\n if (info != null && info.hasType()) {\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n } else if (rValue != null && rValue.isFunction() &&\n shouldUseFunctionLiteralType(\n JSType.toMaybeFunctionType(rValue.getJSType()), info, lValue)) {\n return rValue.getJSType();\n } else if (info != null) {\n if (info.hasEnumParameterType()) {\n if (rValue != null && rValue.isObjectLit()) {\n return rValue.getJSType();\n } else {\n return createEnumTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n }\n } else if (info.isConstructor() || info.isInterface()) {\n return createFunctionTypeFromNodes(\n rValue, lValue.getQualifiedName(), info, lValue);\n } else {\n if (info.isConstant()) {\n JSType knownType = null;\n if (rValue != null) {\n JSDocInfo rValueInfo = rValue.getJSDocInfo();\n if (rValueInfo != null && rValueInfo.hasType()) {\n return rValueInfo.getType().evaluate(scope, typeRegistry);\n } else if (rValue.getJSType() != null\n && !rValue.getJSType().isUnknownType()) {\n return rValue.getJSType();\n } else if (rValue.isOr()) {\n Node firstClause = rValue.getFirstChild();\n Node secondClause = firstClause.getNext();\n boolean namesMatch = firstClause.isName()\n && lValue.isName()\n && firstClause.getString().equals(lValue.getString());\n if (namesMatch && secondClause.getJSType() != null\n && !secondClause.getJSType().isUnknownType()) {\n return secondClause.getJSType();\n }\n }\n }\n }\n }\n }\n return getDeclaredTypeInAnnotation(sourceName, lValue, info);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-17"}} {"sample_uid": "defects4j_function_repair::Gson-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private ReflectiveTypeAdapterFactory.BoundField createBoundField(\n final Gson context, final Field field, final String name,\n final TypeToken fieldType, boolean serialize, boolean deserialize) {\n final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());\n JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);\n TypeAdapter mapped = null;\n if (annotation != null) {\n mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation);\n }\n final boolean jsonAdapterPresent = mapped != null;\n if (mapped == null) mapped = context.getAdapter(fieldType);\n final TypeAdapter typeAdapter = mapped;\n return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {\n @SuppressWarnings({\"unchecked\", \"rawtypes\"}) \n @Override void write(JsonWriter writer, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = field.get(value);\n TypeAdapter t =\n new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());\n t.write(writer, fieldValue);\n }\n @Override void read(JsonReader reader, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = typeAdapter.read(reader);\n if (fieldValue != null || !isPrimitive) {\n field.set(value, fieldValue);\n }\n }\n @Override public boolean writeField(Object value) throws IOException, IllegalAccessException {\n if (!serialized) return false;\n Object fieldValue = field.get(value);\n return fieldValue != value; \n }\n };\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private ReflectiveTypeAdapterFactory.BoundField createBoundField(\n final Gson context, final Field field, final String name,\n final TypeToken fieldType, boolean serialize, boolean deserialize) {\n final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());\n JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);\n TypeAdapter mapped = null;\n if (annotation != null) {\n mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation);\n }\n final boolean jsonAdapterPresent = mapped != null;\n if (mapped == null) mapped = context.getAdapter(fieldType);\n final TypeAdapter typeAdapter = mapped;\n return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {\n @SuppressWarnings({\"unchecked\", \"rawtypes\"}) \n @Override void write(JsonWriter writer, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = field.get(value);\n TypeAdapter t =\n new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());\n t.write(writer, fieldValue);\n }\n @Override void read(JsonReader reader, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = typeAdapter.read(reader);\n if (fieldValue != null || !isPrimitive) {\n field.set(value, fieldValue);\n }\n }\n @Override public boolean writeField(Object value) throws IOException, IllegalAccessException {\n if (!serialized) return false;\n Object fieldValue = field.get(value);\n return fieldValue != value; \n }\n };\n }\n"}, "reference": " private ReflectiveTypeAdapterFactory.BoundField createBoundField(\n final Gson context, final Field field, final String name,\n final TypeToken fieldType, boolean serialize, boolean deserialize) {\n final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType());\n JsonAdapter annotation = field.getAnnotation(JsonAdapter.class);\n TypeAdapter mapped = null;\n if (annotation != null) {\n mapped = getTypeAdapter(constructorConstructor, context, fieldType, annotation);\n }\n final boolean jsonAdapterPresent = mapped != null;\n if (mapped == null) mapped = context.getAdapter(fieldType);\n final TypeAdapter typeAdapter = mapped;\n return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) {\n @SuppressWarnings({\"unchecked\", \"rawtypes\"}) \n @Override void write(JsonWriter writer, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = field.get(value);\n TypeAdapter t = jsonAdapterPresent ? typeAdapter\n : new TypeAdapterRuntimeTypeWrapper(context, typeAdapter, fieldType.getType());\n t.write(writer, fieldValue);\n }\n @Override void read(JsonReader reader, Object value)\n throws IOException, IllegalAccessException {\n Object fieldValue = typeAdapter.read(reader);\n if (fieldValue != null || !isPrimitive) {\n field.set(value, fieldValue);\n }\n }\n @Override public boolean writeField(Object value) throws IOException, IllegalAccessException {\n if (!serialized) return false;\n Object fieldValue = field.get(value);\n return fieldValue != value; \n }\n };\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-10"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public PropertyName findNameForSerialization(Annotated a)\n {\n String name = null;\n JsonGetter jg = _findAnnotation(a, JsonGetter.class);\n if (jg != null) {\n name = jg.value();\n } else {\n JsonProperty pann = _findAnnotation(a, JsonProperty.class);\n if (pann != null) {\n name = pann.value();\n } else if (_hasAnnotation(a, JsonSerialize.class)\n || _hasAnnotation(a, JsonView.class)\n || _hasAnnotation(a, JsonRawValue.class)) {\n name = \"\";\n } else {\n return null;\n }\n }\n return PropertyName.construct(name);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public PropertyName findNameForSerialization(Annotated a)\n {\n String name = null;\n JsonGetter jg = _findAnnotation(a, JsonGetter.class);\n if (jg != null) {\n name = jg.value();\n } else {\n JsonProperty pann = _findAnnotation(a, JsonProperty.class);\n if (pann != null) {\n name = pann.value();\n } else if (_hasAnnotation(a, JsonSerialize.class)\n || _hasAnnotation(a, JsonView.class)\n || _hasAnnotation(a, JsonRawValue.class)) {\n name = \"\";\n } else {\n return null;\n }\n }\n return PropertyName.construct(name);\n }\n"}, "reference": " public PropertyName findNameForSerialization(Annotated a)\n {\n String name = null;\n JsonGetter jg = _findAnnotation(a, JsonGetter.class);\n if (jg != null) {\n name = jg.value();\n } else {\n JsonProperty pann = _findAnnotation(a, JsonProperty.class);\n if (pann != null) {\n name = pann.value();\n } else if (_hasAnnotation(a, JsonSerialize.class)\n || _hasAnnotation(a, JsonView.class)\n || _hasAnnotation(a, JsonRawValue.class)\n || _hasAnnotation(a, JsonUnwrapped.class)\n || _hasAnnotation(a, JsonBackReference.class)\n || _hasAnnotation(a, JsonManagedReference.class)) {\n name = \"\";\n } else {\n return null;\n }\n }\n return PropertyName.construct(name);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-33"}} {"sample_uid": "defects4j_function_repair::Closure-104", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n JSType meet(JSType that) {\n UnionTypeBuilder builder = new UnionTypeBuilder(registry);\n for (JSType alternate : alternates) {\n if (alternate.isSubtype(that)) {\n builder.addAlternate(alternate);\n }\n }\n if (that instanceof UnionType) {\n for (JSType otherAlternate : ((UnionType) that).alternates) {\n if (otherAlternate.isSubtype(this)) {\n builder.addAlternate(otherAlternate);\n }\n }\n } else if (that.isSubtype(this)) {\n builder.addAlternate(that);\n }\n JSType result = builder.build();\n if (result != null) {\n return result;\n } else if (this.isObject() && that.isObject()) {\n return getNativeType(JSTypeNative.NO_OBJECT_TYPE);\n } else {\n return getNativeType(JSTypeNative.NO_TYPE);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " JSType meet(JSType that) {\n UnionTypeBuilder builder = new UnionTypeBuilder(registry);\n for (JSType alternate : alternates) {\n if (alternate.isSubtype(that)) {\n builder.addAlternate(alternate);\n }\n }\n if (that instanceof UnionType) {\n for (JSType otherAlternate : ((UnionType) that).alternates) {\n if (otherAlternate.isSubtype(this)) {\n builder.addAlternate(otherAlternate);\n }\n }\n } else if (that.isSubtype(this)) {\n builder.addAlternate(that);\n }\n JSType result = builder.build();\n if (result != null) {\n return result;\n } else if (this.isObject() && that.isObject()) {\n return getNativeType(JSTypeNative.NO_OBJECT_TYPE);\n } else {\n return getNativeType(JSTypeNative.NO_TYPE);\n }\n }\n"}, "reference": " JSType meet(JSType that) {\n UnionTypeBuilder builder = new UnionTypeBuilder(registry);\n for (JSType alternate : alternates) {\n if (alternate.isSubtype(that)) {\n builder.addAlternate(alternate);\n }\n }\n if (that instanceof UnionType) {\n for (JSType otherAlternate : ((UnionType) that).alternates) {\n if (otherAlternate.isSubtype(this)) {\n builder.addAlternate(otherAlternate);\n }\n }\n } else if (that.isSubtype(this)) {\n builder.addAlternate(that);\n }\n JSType result = builder.build();\n if (!result.isNoType()) {\n return result;\n } else if (this.isObject() && that.isObject()) {\n return getNativeType(JSTypeNative.NO_OBJECT_TYPE);\n } else {\n return getNativeType(JSTypeNative.NO_TYPE);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-104"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-104"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-42", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Object _deserializeFromEmptyString() throws IOException {\n if (_kind == STD_URI) {\n return URI.create(\"\");\n }\n return super._deserializeFromEmptyString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Object _deserializeFromEmptyString() throws IOException {\n if (_kind == STD_URI) {\n return URI.create(\"\");\n }\n return super._deserializeFromEmptyString();\n }\n"}, "reference": " protected Object _deserializeFromEmptyString() throws IOException {\n if (_kind == STD_URI) {\n return URI.create(\"\");\n }\n if (_kind == STD_LOCALE) {\n return Locale.ROOT;\n }\n return super._deserializeFromEmptyString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-42"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-42"}} {"sample_uid": "defects4j_function_repair::Math-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Line revert() {\n final Line reverted = new Line(zero, zero.subtract(direction));\n return reverted;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Line revert() {\n final Line reverted = new Line(zero, zero.subtract(direction));\n return reverted;\n }\n"}, "reference": " public Line revert() {\n final Line reverted = new Line(this);\n reverted.direction = reverted.direction.negate();\n return reverted;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-9"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-96", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void _addExplicitAnyCreator(DeserializationContext ctxt,\n BeanDescription beanDesc, CreatorCollector creators,\n CreatorCandidate candidate)\n throws JsonMappingException\n {\n if (1 != candidate.paramCount()) {\n int oneNotInjected = candidate.findOnlyParamWithoutInjection();\n if (oneNotInjected >= 0) {\n if (candidate.paramName(oneNotInjected) == null) {\n _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n }\n _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n AnnotatedParameter param = candidate.parameter(0);\n JacksonInject.Value injectId = candidate.injection(0);\n PropertyName paramName = candidate.explicitParamName(0);\n BeanPropertyDefinition paramDef = candidate.propertyDef(0);\n boolean useProps = (paramName != null) || (injectId != null);\n if (!useProps && (paramDef != null)) {\n paramName = candidate.findImplicitParamName(0);\n useProps = (paramName != null) && paramDef.couldSerialize();\n }\n if (useProps) {\n SettableBeanProperty[] properties = new SettableBeanProperty[] {\n constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)\n };\n creators.addPropertyCreator(candidate.creator(), true, properties);\n return;\n }\n _handleSingleArgumentCreator(creators, candidate.creator(), true, true);\n if (paramDef != null) {\n ((POJOPropertyBuilder) paramDef).removeConstructors();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void _addExplicitAnyCreator(DeserializationContext ctxt,\n BeanDescription beanDesc, CreatorCollector creators,\n CreatorCandidate candidate)\n throws JsonMappingException\n {\n if (1 != candidate.paramCount()) {\n int oneNotInjected = candidate.findOnlyParamWithoutInjection();\n if (oneNotInjected >= 0) {\n if (candidate.paramName(oneNotInjected) == null) {\n _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n }\n _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n AnnotatedParameter param = candidate.parameter(0);\n JacksonInject.Value injectId = candidate.injection(0);\n PropertyName paramName = candidate.explicitParamName(0);\n BeanPropertyDefinition paramDef = candidate.propertyDef(0);\n boolean useProps = (paramName != null) || (injectId != null);\n if (!useProps && (paramDef != null)) {\n paramName = candidate.findImplicitParamName(0);\n useProps = (paramName != null) && paramDef.couldSerialize();\n }\n if (useProps) {\n SettableBeanProperty[] properties = new SettableBeanProperty[] {\n constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)\n };\n creators.addPropertyCreator(candidate.creator(), true, properties);\n return;\n }\n _handleSingleArgumentCreator(creators, candidate.creator(), true, true);\n if (paramDef != null) {\n ((POJOPropertyBuilder) paramDef).removeConstructors();\n }\n }\n"}, "reference": " protected void _addExplicitAnyCreator(DeserializationContext ctxt,\n BeanDescription beanDesc, CreatorCollector creators,\n CreatorCandidate candidate)\n throws JsonMappingException\n {\n if (1 != candidate.paramCount()) {\n int oneNotInjected = candidate.findOnlyParamWithoutInjection();\n if (oneNotInjected >= 0) {\n if (candidate.paramName(oneNotInjected) == null) {\n _addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n }\n _addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);\n return;\n }\n AnnotatedParameter param = candidate.parameter(0);\n JacksonInject.Value injectId = candidate.injection(0);\n PropertyName paramName = candidate.explicitParamName(0);\n BeanPropertyDefinition paramDef = candidate.propertyDef(0);\n boolean useProps = (paramName != null) || (injectId != null);\n if (!useProps && (paramDef != null)) {\n paramName = candidate.paramName(0);\n useProps = (paramName != null) && paramDef.couldSerialize();\n }\n if (useProps) {\n SettableBeanProperty[] properties = new SettableBeanProperty[] {\n constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)\n };\n creators.addPropertyCreator(candidate.creator(), true, properties);\n return;\n }\n _handleSingleArgumentCreator(creators, candidate.creator(), true, true);\n if (paramDef != null) {\n ((POJOPropertyBuilder) paramDef).removeConstructors();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-96"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-96"}} {"sample_uid": "defects4j_function_repair::Cli-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static void appendOption(final StringBuffer buff, \n final Option option, \n final boolean required)\n {\n if (!required)\n {\n buff.append(\"[\");\n }\n if (option.getOpt() != null)\n {\n buff.append(\"-\").append(option.getOpt());\n }\n else\n {\n buff.append(\"--\").append(option.getLongOpt());\n }\n if (option.hasArg() && (option.getArgName() != null))\n {\n buff.append(\" <\").append(option.getArgName()).append(\">\");\n }\n if (!required)\n {\n buff.append(\"]\");\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static void appendOption(final StringBuffer buff, \n final Option option, \n final boolean required)\n {\n if (!required)\n {\n buff.append(\"[\");\n }\n if (option.getOpt() != null)\n {\n buff.append(\"-\").append(option.getOpt());\n }\n else\n {\n buff.append(\"--\").append(option.getLongOpt());\n }\n if (option.hasArg() && (option.getArgName() != null))\n {\n buff.append(\" <\").append(option.getArgName()).append(\">\");\n }\n if (!required)\n {\n buff.append(\"]\");\n }\n }\n"}, "reference": " private static void appendOption(final StringBuffer buff, \n final Option option, \n final boolean required)\n {\n if (!required)\n {\n buff.append(\"[\");\n }\n if (option.getOpt() != null)\n {\n buff.append(\"-\").append(option.getOpt());\n }\n else\n {\n buff.append(\"--\").append(option.getLongOpt());\n }\n if (option.hasArg() && option.hasArgName())\n {\n buff.append(\" <\").append(option.getArgName()).append(\">\");\n }\n if (!required)\n {\n buff.append(\"]\");\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-11"}} {"sample_uid": "defects4j_function_repair::Closure-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void checkInterfaceConflictProperties(NodeTraversal t, Node n,\n String functionName, HashMap properties,\n HashMap currentProperties,\n ObjectType interfaceType) {\n ObjectType implicitProto = interfaceType.getImplicitPrototype();\n Set currentPropertyNames;\n currentPropertyNames = implicitProto.getOwnPropertyNames();\n for (String name : currentPropertyNames) {\n ObjectType oType = properties.get(name);\n if (oType != null) {\n if (!interfaceType.getPropertyType(name).isEquivalentTo(\n oType.getPropertyType(name))) {\n compiler.report(\n t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,\n functionName, name, oType.toString(),\n interfaceType.toString()));\n }\n }\n currentProperties.put(name, interfaceType);\n }\n for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) {\n checkInterfaceConflictProperties(t, n, functionName, properties,\n currentProperties, iType);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void checkInterfaceConflictProperties(NodeTraversal t, Node n,\n String functionName, HashMap properties,\n HashMap currentProperties,\n ObjectType interfaceType) {\n ObjectType implicitProto = interfaceType.getImplicitPrototype();\n Set currentPropertyNames;\n currentPropertyNames = implicitProto.getOwnPropertyNames();\n for (String name : currentPropertyNames) {\n ObjectType oType = properties.get(name);\n if (oType != null) {\n if (!interfaceType.getPropertyType(name).isEquivalentTo(\n oType.getPropertyType(name))) {\n compiler.report(\n t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,\n functionName, name, oType.toString(),\n interfaceType.toString()));\n }\n }\n currentProperties.put(name, interfaceType);\n }\n for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) {\n checkInterfaceConflictProperties(t, n, functionName, properties,\n currentProperties, iType);\n }\n }\n"}, "reference": " private void checkInterfaceConflictProperties(NodeTraversal t, Node n,\n String functionName, HashMap properties,\n HashMap currentProperties,\n ObjectType interfaceType) {\n ObjectType implicitProto = interfaceType.getImplicitPrototype();\n Set currentPropertyNames;\n if (implicitProto == null) {\n currentPropertyNames = ImmutableSet.of();\n } else {\n currentPropertyNames = implicitProto.getOwnPropertyNames();\n }\n for (String name : currentPropertyNames) {\n ObjectType oType = properties.get(name);\n if (oType != null) {\n if (!interfaceType.getPropertyType(name).isEquivalentTo(\n oType.getPropertyType(name))) {\n compiler.report(\n t.makeError(n, INCOMPATIBLE_EXTENDED_PROPERTY_TYPE,\n functionName, name, oType.toString(),\n interfaceType.toString()));\n }\n }\n currentProperties.put(name, interfaceType);\n }\n for (ObjectType iType : interfaceType.getCtorExtendedInterfaces()) {\n checkInterfaceConflictProperties(t, n, functionName, properties,\n currentProperties, iType);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-2"}} {"sample_uid": "defects4j_function_repair::Math-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public RectangularCholeskyDecomposition(RealMatrix matrix, double small)\n throws NonPositiveDefiniteMatrixException {\n final int order = matrix.getRowDimension();\n final double[][] c = matrix.getData();\n final double[][] b = new double[order][order];\n int[] swap = new int[order];\n int[] index = new int[order];\n for (int i = 0; i < order; ++i) {\n index[i] = i;\n }\n int r = 0;\n for (boolean loop = true; loop;) {\n swap[r] = r;\n for (int i = r + 1; i < order; ++i) {\n int ii = index[i];\n int isi = index[swap[i]];\n if (c[ii][ii] > c[isi][isi]) {\n swap[r] = i;\n }\n }\n if (swap[r] != r) {\n int tmp = index[r];\n index[r] = index[swap[r]];\n index[swap[r]] = tmp;\n }\n int ir = index[r];\n if (c[ir][ir] < small) {\n if (r == 0) {\n throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small);\n }\n for (int i = r; i < order; ++i) {\n if (c[index[i]][index[i]] < -small) {\n throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small);\n }\n }\n ++r;\n loop = false;\n } else {\n final double sqrt = FastMath.sqrt(c[ir][ir]);\n b[r][r] = sqrt;\n final double inverse = 1 / sqrt;\n for (int i = r + 1; i < order; ++i) {\n final int ii = index[i];\n final double e = inverse * c[ii][ir];\n b[i][r] = e;\n c[ii][ii] -= e * e;\n for (int j = r + 1; j < i; ++j) {\n final int ij = index[j];\n final double f = c[ii][ij] - e * b[j][r];\n c[ii][ij] = f;\n c[ij][ii] = f;\n }\n }\n loop = ++r < order;\n }\n }\n rank = r;\n root = MatrixUtils.createRealMatrix(order, r);\n for (int i = 0; i < order; ++i) {\n for (int j = 0; j < r; ++j) {\n root.setEntry(index[i], j, b[i][j]);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public RectangularCholeskyDecomposition(RealMatrix matrix, double small)\n throws NonPositiveDefiniteMatrixException {\n final int order = matrix.getRowDimension();\n final double[][] c = matrix.getData();\n final double[][] b = new double[order][order];\n int[] swap = new int[order];\n int[] index = new int[order];\n for (int i = 0; i < order; ++i) {\n index[i] = i;\n }\n int r = 0;\n for (boolean loop = true; loop;) {\n swap[r] = r;\n for (int i = r + 1; i < order; ++i) {\n int ii = index[i];\n int isi = index[swap[i]];\n if (c[ii][ii] > c[isi][isi]) {\n swap[r] = i;\n }\n }\n if (swap[r] != r) {\n int tmp = index[r];\n index[r] = index[swap[r]];\n index[swap[r]] = tmp;\n }\n int ir = index[r];\n if (c[ir][ir] < small) {\n if (r == 0) {\n throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small);\n }\n for (int i = r; i < order; ++i) {\n if (c[index[i]][index[i]] < -small) {\n throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small);\n }\n }\n ++r;\n loop = false;\n } else {\n final double sqrt = FastMath.sqrt(c[ir][ir]);\n b[r][r] = sqrt;\n final double inverse = 1 / sqrt;\n for (int i = r + 1; i < order; ++i) {\n final int ii = index[i];\n final double e = inverse * c[ii][ir];\n b[i][r] = e;\n c[ii][ii] -= e * e;\n for (int j = r + 1; j < i; ++j) {\n final int ij = index[j];\n final double f = c[ii][ij] - e * b[j][r];\n c[ii][ij] = f;\n c[ij][ii] = f;\n }\n }\n loop = ++r < order;\n }\n }\n rank = r;\n root = MatrixUtils.createRealMatrix(order, r);\n for (int i = 0; i < order; ++i) {\n for (int j = 0; j < r; ++j) {\n root.setEntry(index[i], j, b[i][j]);\n }\n }\n }\n"}, "reference": " public RectangularCholeskyDecomposition(RealMatrix matrix, double small)\n throws NonPositiveDefiniteMatrixException {\n final int order = matrix.getRowDimension();\n final double[][] c = matrix.getData();\n final double[][] b = new double[order][order];\n int[] index = new int[order];\n for (int i = 0; i < order; ++i) {\n index[i] = i;\n }\n int r = 0;\n for (boolean loop = true; loop;) {\n int swapR = r;\n for (int i = r + 1; i < order; ++i) {\n int ii = index[i];\n int isr = index[swapR];\n if (c[ii][ii] > c[isr][isr]) {\n swapR = i;\n }\n }\n if (swapR != r) {\n final int tmpIndex = index[r];\n index[r] = index[swapR];\n index[swapR] = tmpIndex;\n final double[] tmpRow = b[r];\n b[r] = b[swapR];\n b[swapR] = tmpRow;\n }\n int ir = index[r];\n if (c[ir][ir] < small) {\n if (r == 0) {\n throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small);\n }\n for (int i = r; i < order; ++i) {\n if (c[index[i]][index[i]] < -small) {\n throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small);\n }\n }\n ++r;\n loop = false;\n } else {\n final double sqrt = FastMath.sqrt(c[ir][ir]);\n b[r][r] = sqrt;\n final double inverse = 1 / sqrt;\n final double inverse2 = 1 / c[ir][ir];\n for (int i = r + 1; i < order; ++i) {\n final int ii = index[i];\n final double e = inverse * c[ii][ir];\n b[i][r] = e;\n c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2;\n for (int j = r + 1; j < i; ++j) {\n final int ij = index[j];\n final double f = c[ii][ij] - e * b[j][r];\n c[ii][ij] = f;\n c[ij][ii] = f;\n }\n }\n loop = ++r < order;\n }\n }\n rank = r;\n root = MatrixUtils.createRealMatrix(order, r);\n for (int i = 0; i < order; ++i) {\n for (int j = 0; j < r; ++j) {\n root.setEntry(index[i], j, b[i][j]);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-21"}} {"sample_uid": "defects4j_function_repair::Jsoup-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String absUrl(String attributeKey) {\n Validate.notEmpty(attributeKey);\n String relUrl = attr(attributeKey);\n if (!hasAttr(attributeKey)) {\n return \"\"; \n } else {\n URL base;\n try {\n try {\n base = new URL(baseUri);\n } catch (MalformedURLException e) {\n URL abs = new URL(relUrl);\n return abs.toExternalForm();\n }\n URL abs = new URL(base, relUrl);\n return abs.toExternalForm();\n } catch (MalformedURLException e) {\n return \"\";\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String absUrl(String attributeKey) {\n Validate.notEmpty(attributeKey);\n String relUrl = attr(attributeKey);\n if (!hasAttr(attributeKey)) {\n return \"\"; \n } else {\n URL base;\n try {\n try {\n base = new URL(baseUri);\n } catch (MalformedURLException e) {\n URL abs = new URL(relUrl);\n return abs.toExternalForm();\n }\n URL abs = new URL(base, relUrl);\n return abs.toExternalForm();\n } catch (MalformedURLException e) {\n return \"\";\n }\n }\n }\n"}, "reference": " public String absUrl(String attributeKey) {\n Validate.notEmpty(attributeKey);\n String relUrl = attr(attributeKey);\n if (!hasAttr(attributeKey)) {\n return \"\"; \n } else {\n URL base;\n try {\n try {\n base = new URL(baseUri);\n } catch (MalformedURLException e) {\n URL abs = new URL(relUrl);\n return abs.toExternalForm();\n }\n if (relUrl.startsWith(\"?\"))\n relUrl = base.getPath() + relUrl;\n URL abs = new URL(base, relUrl);\n return abs.toExternalForm();\n } catch (MalformedURLException e) {\n return \"\";\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-10"}} {"sample_uid": "defects4j_function_repair::Math-101", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Complex parse(String source, ParsePosition pos) {\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number re = parseNumber(source, getRealFormat(), pos);\n if (re == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n int sign = 0;\n switch (c) {\n case 0 :\n return new Complex(re.doubleValue(), 0.0);\n case '-' :\n sign = -1;\n break;\n case '+' :\n sign = 1;\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number im = parseNumber(source, getRealFormat(), pos);\n if (im == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int n = getImaginaryCharacter().length();\n startIndex = pos.getIndex();\n int endIndex = startIndex + n;\n if (\n source.substring(startIndex, endIndex).compareTo(\n getImaginaryCharacter()) != 0) {\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n pos.setIndex(endIndex);\n return new Complex(re.doubleValue(), im.doubleValue() * sign);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Complex parse(String source, ParsePosition pos) {\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number re = parseNumber(source, getRealFormat(), pos);\n if (re == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n int sign = 0;\n switch (c) {\n case 0 :\n return new Complex(re.doubleValue(), 0.0);\n case '-' :\n sign = -1;\n break;\n case '+' :\n sign = 1;\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number im = parseNumber(source, getRealFormat(), pos);\n if (im == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int n = getImaginaryCharacter().length();\n startIndex = pos.getIndex();\n int endIndex = startIndex + n;\n if (\n source.substring(startIndex, endIndex).compareTo(\n getImaginaryCharacter()) != 0) {\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n pos.setIndex(endIndex);\n return new Complex(re.doubleValue(), im.doubleValue() * sign);\n }\n"}, "reference": " public Complex parse(String source, ParsePosition pos) {\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number re = parseNumber(source, getRealFormat(), pos);\n if (re == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n int sign = 0;\n switch (c) {\n case 0 :\n return new Complex(re.doubleValue(), 0.0);\n case '-' :\n sign = -1;\n break;\n case '+' :\n sign = 1;\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number im = parseNumber(source, getRealFormat(), pos);\n if (im == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int n = getImaginaryCharacter().length();\n startIndex = pos.getIndex();\n int endIndex = startIndex + n;\n if ((startIndex >= source.length()) ||\n (endIndex > source.length()) ||\n source.substring(startIndex, endIndex).compareTo(\n getImaginaryCharacter()) != 0) {\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n pos.setIndex(endIndex);\n return new Complex(re.doubleValue(), im.doubleValue() * sign);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-101"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-101"}} {"sample_uid": "defects4j_function_repair::Codec-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String caverphone(String txt) {\n if( txt == null || txt.length() == 0 ) {\n return \"1111111111\";\n }\n txt = txt.toLowerCase(java.util.Locale.ENGLISH);\n txt = txt.replaceAll(\"[^a-z]\", \"\");\n txt = txt.replaceAll(\"e$\", \"\"); \n txt = txt.replaceAll(\"^cough\", \"cou2f\");\n txt = txt.replaceAll(\"^rough\", \"rou2f\");\n txt = txt.replaceAll(\"^tough\", \"tou2f\");\n txt = txt.replaceAll(\"^enough\", \"enou2f\"); \n txt = txt.replaceAll(\"^trough\", \"trou2f\"); \n txt = txt.replaceAll(\"^gn\", \"2n\");\n txt = txt.replaceAll(\"^mb\", \"m2\");\n txt = txt.replaceAll(\"cq\", \"2q\");\n txt = txt.replaceAll(\"ci\", \"si\");\n txt = txt.replaceAll(\"ce\", \"se\");\n txt = txt.replaceAll(\"cy\", \"sy\");\n txt = txt.replaceAll(\"tch\", \"2ch\");\n txt = txt.replaceAll(\"c\", \"k\");\n txt = txt.replaceAll(\"q\", \"k\");\n txt = txt.replaceAll(\"x\", \"k\");\n txt = txt.replaceAll(\"v\", \"f\");\n txt = txt.replaceAll(\"dg\", \"2g\");\n txt = txt.replaceAll(\"tio\", \"sio\");\n txt = txt.replaceAll(\"tia\", \"sia\");\n txt = txt.replaceAll(\"d\", \"t\");\n txt = txt.replaceAll(\"ph\", \"fh\");\n txt = txt.replaceAll(\"b\", \"p\");\n txt = txt.replaceAll(\"sh\", \"s2\");\n txt = txt.replaceAll(\"z\", \"s\");\n txt = txt.replaceAll(\"^[aeiou]\", \"A\");\n txt = txt.replaceAll(\"[aeiou]\", \"3\");\n txt = txt.replaceAll(\"j\", \"y\"); \n txt = txt.replaceAll(\"^y3\", \"Y3\"); \n txt = txt.replaceAll(\"^y\", \"A\"); \n txt = txt.replaceAll(\"y\", \"3\"); \n txt = txt.replaceAll(\"3gh3\", \"3kh3\");\n txt = txt.replaceAll(\"gh\", \"22\");\n txt = txt.replaceAll(\"g\", \"k\");\n txt = txt.replaceAll(\"s+\", \"S\");\n txt = txt.replaceAll(\"t+\", \"T\");\n txt = txt.replaceAll(\"p+\", \"P\");\n txt = txt.replaceAll(\"k+\", \"K\");\n txt = txt.replaceAll(\"f+\", \"F\");\n txt = txt.replaceAll(\"m+\", \"M\");\n txt = txt.replaceAll(\"n+\", \"N\");\n txt = txt.replaceAll(\"w3\", \"W3\");\n txt = txt.replaceAll(\"wh3\", \"Wh3\");\n txt = txt.replaceAll(\"w$\", \"3\"); \n txt = txt.replaceAll(\"w\", \"2\");\n txt = txt.replaceAll(\"^h\", \"A\");\n txt = txt.replaceAll(\"h\", \"2\");\n txt = txt.replaceAll(\"r3\", \"R3\");\n txt = txt.replaceAll(\"r$\", \"3\"); \n txt = txt.replaceAll(\"r\", \"2\");\n txt = txt.replaceAll(\"l3\", \"L3\");\n txt = txt.replaceAll(\"l$\", \"3\"); \n txt = txt.replaceAll(\"l\", \"2\");\n txt = txt.replaceAll(\"2\", \"\");\n txt = txt.replaceAll(\"3$\", \"A\"); \n txt = txt.replaceAll(\"3\", \"\");\n txt = txt + \"111111\" + \"1111\"; \n return txt.substring(0, 10); \n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String caverphone(String txt) {\n if( txt == null || txt.length() == 0 ) {\n return \"1111111111\";\n }\n txt = txt.toLowerCase(java.util.Locale.ENGLISH);\n txt = txt.replaceAll(\"[^a-z]\", \"\");\n txt = txt.replaceAll(\"e$\", \"\"); \n txt = txt.replaceAll(\"^cough\", \"cou2f\");\n txt = txt.replaceAll(\"^rough\", \"rou2f\");\n txt = txt.replaceAll(\"^tough\", \"tou2f\");\n txt = txt.replaceAll(\"^enough\", \"enou2f\"); \n txt = txt.replaceAll(\"^trough\", \"trou2f\"); \n txt = txt.replaceAll(\"^gn\", \"2n\");\n txt = txt.replaceAll(\"^mb\", \"m2\");\n txt = txt.replaceAll(\"cq\", \"2q\");\n txt = txt.replaceAll(\"ci\", \"si\");\n txt = txt.replaceAll(\"ce\", \"se\");\n txt = txt.replaceAll(\"cy\", \"sy\");\n txt = txt.replaceAll(\"tch\", \"2ch\");\n txt = txt.replaceAll(\"c\", \"k\");\n txt = txt.replaceAll(\"q\", \"k\");\n txt = txt.replaceAll(\"x\", \"k\");\n txt = txt.replaceAll(\"v\", \"f\");\n txt = txt.replaceAll(\"dg\", \"2g\");\n txt = txt.replaceAll(\"tio\", \"sio\");\n txt = txt.replaceAll(\"tia\", \"sia\");\n txt = txt.replaceAll(\"d\", \"t\");\n txt = txt.replaceAll(\"ph\", \"fh\");\n txt = txt.replaceAll(\"b\", \"p\");\n txt = txt.replaceAll(\"sh\", \"s2\");\n txt = txt.replaceAll(\"z\", \"s\");\n txt = txt.replaceAll(\"^[aeiou]\", \"A\");\n txt = txt.replaceAll(\"[aeiou]\", \"3\");\n txt = txt.replaceAll(\"j\", \"y\"); \n txt = txt.replaceAll(\"^y3\", \"Y3\"); \n txt = txt.replaceAll(\"^y\", \"A\"); \n txt = txt.replaceAll(\"y\", \"3\"); \n txt = txt.replaceAll(\"3gh3\", \"3kh3\");\n txt = txt.replaceAll(\"gh\", \"22\");\n txt = txt.replaceAll(\"g\", \"k\");\n txt = txt.replaceAll(\"s+\", \"S\");\n txt = txt.replaceAll(\"t+\", \"T\");\n txt = txt.replaceAll(\"p+\", \"P\");\n txt = txt.replaceAll(\"k+\", \"K\");\n txt = txt.replaceAll(\"f+\", \"F\");\n txt = txt.replaceAll(\"m+\", \"M\");\n txt = txt.replaceAll(\"n+\", \"N\");\n txt = txt.replaceAll(\"w3\", \"W3\");\n txt = txt.replaceAll(\"wh3\", \"Wh3\");\n txt = txt.replaceAll(\"w$\", \"3\"); \n txt = txt.replaceAll(\"w\", \"2\");\n txt = txt.replaceAll(\"^h\", \"A\");\n txt = txt.replaceAll(\"h\", \"2\");\n txt = txt.replaceAll(\"r3\", \"R3\");\n txt = txt.replaceAll(\"r$\", \"3\"); \n txt = txt.replaceAll(\"r\", \"2\");\n txt = txt.replaceAll(\"l3\", \"L3\");\n txt = txt.replaceAll(\"l$\", \"3\"); \n txt = txt.replaceAll(\"l\", \"2\");\n txt = txt.replaceAll(\"2\", \"\");\n txt = txt.replaceAll(\"3$\", \"A\"); \n txt = txt.replaceAll(\"3\", \"\");\n txt = txt + \"111111\" + \"1111\"; \n return txt.substring(0, 10); \n }\n"}, "reference": " public String caverphone(String txt) {\n if( txt == null || txt.length() == 0 ) {\n return \"1111111111\";\n }\n txt = txt.toLowerCase(java.util.Locale.ENGLISH);\n txt = txt.replaceAll(\"[^a-z]\", \"\");\n txt = txt.replaceAll(\"e$\", \"\"); \n txt = txt.replaceAll(\"^cough\", \"cou2f\");\n txt = txt.replaceAll(\"^rough\", \"rou2f\");\n txt = txt.replaceAll(\"^tough\", \"tou2f\");\n txt = txt.replaceAll(\"^enough\", \"enou2f\"); \n txt = txt.replaceAll(\"^trough\", \"trou2f\"); \n txt = txt.replaceAll(\"^gn\", \"2n\");\n txt = txt.replaceAll(\"mb$\", \"m2\");\n txt = txt.replaceAll(\"cq\", \"2q\");\n txt = txt.replaceAll(\"ci\", \"si\");\n txt = txt.replaceAll(\"ce\", \"se\");\n txt = txt.replaceAll(\"cy\", \"sy\");\n txt = txt.replaceAll(\"tch\", \"2ch\");\n txt = txt.replaceAll(\"c\", \"k\");\n txt = txt.replaceAll(\"q\", \"k\");\n txt = txt.replaceAll(\"x\", \"k\");\n txt = txt.replaceAll(\"v\", \"f\");\n txt = txt.replaceAll(\"dg\", \"2g\");\n txt = txt.replaceAll(\"tio\", \"sio\");\n txt = txt.replaceAll(\"tia\", \"sia\");\n txt = txt.replaceAll(\"d\", \"t\");\n txt = txt.replaceAll(\"ph\", \"fh\");\n txt = txt.replaceAll(\"b\", \"p\");\n txt = txt.replaceAll(\"sh\", \"s2\");\n txt = txt.replaceAll(\"z\", \"s\");\n txt = txt.replaceAll(\"^[aeiou]\", \"A\");\n txt = txt.replaceAll(\"[aeiou]\", \"3\");\n txt = txt.replaceAll(\"j\", \"y\"); \n txt = txt.replaceAll(\"^y3\", \"Y3\"); \n txt = txt.replaceAll(\"^y\", \"A\"); \n txt = txt.replaceAll(\"y\", \"3\"); \n txt = txt.replaceAll(\"3gh3\", \"3kh3\");\n txt = txt.replaceAll(\"gh\", \"22\");\n txt = txt.replaceAll(\"g\", \"k\");\n txt = txt.replaceAll(\"s+\", \"S\");\n txt = txt.replaceAll(\"t+\", \"T\");\n txt = txt.replaceAll(\"p+\", \"P\");\n txt = txt.replaceAll(\"k+\", \"K\");\n txt = txt.replaceAll(\"f+\", \"F\");\n txt = txt.replaceAll(\"m+\", \"M\");\n txt = txt.replaceAll(\"n+\", \"N\");\n txt = txt.replaceAll(\"w3\", \"W3\");\n txt = txt.replaceAll(\"wh3\", \"Wh3\");\n txt = txt.replaceAll(\"w$\", \"3\"); \n txt = txt.replaceAll(\"w\", \"2\");\n txt = txt.replaceAll(\"^h\", \"A\");\n txt = txt.replaceAll(\"h\", \"2\");\n txt = txt.replaceAll(\"r3\", \"R3\");\n txt = txt.replaceAll(\"r$\", \"3\"); \n txt = txt.replaceAll(\"r\", \"2\");\n txt = txt.replaceAll(\"l3\", \"L3\");\n txt = txt.replaceAll(\"l$\", \"3\"); \n txt = txt.replaceAll(\"l\", \"2\");\n txt = txt.replaceAll(\"2\", \"\");\n txt = txt.replaceAll(\"3$\", \"A\"); \n txt = txt.replaceAll(\"3\", \"\");\n txt = txt + \"111111\" + \"1111\"; \n return txt.substring(0, 10); \n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-10"}} {"sample_uid": "defects4j_function_repair::Compress-30", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int read(final byte[] dest, final int offs, final int len)\n throws IOException {\n if (offs < 0) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") < 0.\");\n }\n if (len < 0) {\n throw new IndexOutOfBoundsException(\"len(\" + len + \") < 0.\");\n }\n if (offs + len > dest.length) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") + len(\"\n + len + \") > dest.length(\" + dest.length + \").\");\n }\n if (this.in == null) {\n throw new IOException(\"stream closed\");\n }\n final int hi = offs + len;\n int destOffs = offs;\n int b;\n while (destOffs < hi && ((b = read0()) >= 0)) {\n dest[destOffs++] = (byte) b;\n count(1);\n }\n int c = (destOffs == offs) ? -1 : (destOffs - offs);\n return c;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int read(final byte[] dest, final int offs, final int len)\n throws IOException {\n if (offs < 0) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") < 0.\");\n }\n if (len < 0) {\n throw new IndexOutOfBoundsException(\"len(\" + len + \") < 0.\");\n }\n if (offs + len > dest.length) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") + len(\"\n + len + \") > dest.length(\" + dest.length + \").\");\n }\n if (this.in == null) {\n throw new IOException(\"stream closed\");\n }\n final int hi = offs + len;\n int destOffs = offs;\n int b;\n while (destOffs < hi && ((b = read0()) >= 0)) {\n dest[destOffs++] = (byte) b;\n count(1);\n }\n int c = (destOffs == offs) ? -1 : (destOffs - offs);\n return c;\n }\n"}, "reference": " public int read(final byte[] dest, final int offs, final int len)\n throws IOException {\n if (offs < 0) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") < 0.\");\n }\n if (len < 0) {\n throw new IndexOutOfBoundsException(\"len(\" + len + \") < 0.\");\n }\n if (offs + len > dest.length) {\n throw new IndexOutOfBoundsException(\"offs(\" + offs + \") + len(\"\n + len + \") > dest.length(\" + dest.length + \").\");\n }\n if (this.in == null) {\n throw new IOException(\"stream closed\");\n }\n if (len == 0) {\n return 0;\n }\n final int hi = offs + len;\n int destOffs = offs;\n int b;\n while (destOffs < hi && ((b = read0()) >= 0)) {\n dest[destOffs++] = (byte) b;\n count(1);\n }\n int c = (destOffs == offs) ? -1 : (destOffs - offs);\n return c;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-30"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-30"}} {"sample_uid": "defects4j_function_repair::Math-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Complex reciprocal() {\n if (isNaN) {\n return NaN;\n }\n if (real == 0.0 && imaginary == 0.0) {\n return NaN;\n }\n if (isInfinite) {\n return ZERO;\n }\n if (FastMath.abs(real) < FastMath.abs(imaginary)) {\n double q = real / imaginary;\n double scale = 1. / (real * q + imaginary);\n return createComplex(scale * q, -scale);\n } else {\n double q = imaginary / real;\n double scale = 1. / (imaginary * q + real);\n return createComplex(scale, -scale * q);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Complex reciprocal() {\n if (isNaN) {\n return NaN;\n }\n if (real == 0.0 && imaginary == 0.0) {\n return NaN;\n }\n if (isInfinite) {\n return ZERO;\n }\n if (FastMath.abs(real) < FastMath.abs(imaginary)) {\n double q = real / imaginary;\n double scale = 1. / (real * q + imaginary);\n return createComplex(scale * q, -scale);\n } else {\n double q = imaginary / real;\n double scale = 1. / (imaginary * q + real);\n return createComplex(scale, -scale * q);\n }\n }\n"}, "reference": " public Complex reciprocal() {\n if (isNaN) {\n return NaN;\n }\n if (real == 0.0 && imaginary == 0.0) {\n return INF;\n }\n if (isInfinite) {\n return ZERO;\n }\n if (FastMath.abs(real) < FastMath.abs(imaginary)) {\n double q = real / imaginary;\n double scale = 1. / (real * q + imaginary);\n return createComplex(scale * q, -scale);\n } else {\n double q = imaginary / real;\n double scale = 1. / (imaginary * q + real);\n return createComplex(scale, -scale * q);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-5"}} {"sample_uid": "defects4j_function_repair::Closure-55", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static boolean isReduceableFunctionExpression(Node n) {\n return NodeUtil.isFunctionExpression(n);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static boolean isReduceableFunctionExpression(Node n) {\n return NodeUtil.isFunctionExpression(n);\n }\n"}, "reference": " private static boolean isReduceableFunctionExpression(Node n) {\n return NodeUtil.isFunctionExpression(n)\n && !NodeUtil.isGetOrSetKey(n.getParent());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-55"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-55"}} {"sample_uid": "defects4j_function_repair::Closure-67", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isPrototypePropertyAssign(Node assign) {\n Node n = assign.getFirstChild();\n if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)\n && n.getType() == Token.GETPROP\n ) {\n boolean isChainedProperty =\n n.getFirstChild().getType() == Token.GETPROP;\n if (isChainedProperty) {\n Node child = n.getFirstChild().getFirstChild().getNext();\n if (child.getType() == Token.STRING &&\n child.getString().equals(\"prototype\")) {\n return true;\n }\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isPrototypePropertyAssign(Node assign) {\n Node n = assign.getFirstChild();\n if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)\n && n.getType() == Token.GETPROP\n ) {\n boolean isChainedProperty =\n n.getFirstChild().getType() == Token.GETPROP;\n if (isChainedProperty) {\n Node child = n.getFirstChild().getFirstChild().getNext();\n if (child.getType() == Token.STRING &&\n child.getString().equals(\"prototype\")) {\n return true;\n }\n }\n }\n return false;\n }\n"}, "reference": " private boolean isPrototypePropertyAssign(Node assign) {\n Node n = assign.getFirstChild();\n if (n != null && NodeUtil.isVarOrSimpleAssignLhs(n, assign)\n && n.getType() == Token.GETPROP\n && assign.getParent().getType() == Token.EXPR_RESULT) {\n boolean isChainedProperty =\n n.getFirstChild().getType() == Token.GETPROP;\n if (isChainedProperty) {\n Node child = n.getFirstChild().getFirstChild().getNext();\n if (child.getType() == Token.STRING &&\n child.getString().equals(\"prototype\")) {\n return true;\n }\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-67"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-67"}} {"sample_uid": "defects4j_function_repair::Closure-168", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n return;\n }\n if (n.isReturn() && n.getFirstChild() != null) {\n data.get(t.getScopeRoot()).recordNonEmptyReturn();\n }\n if (t.getScopeDepth() <= 2) {\n return;\n }\n if (n.isName() && NodeUtil.isLValue(n) &&\n !NodeUtil.isBleedingFunctionName(n)) {\n String name = n.getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordAssignedName(name);\n }\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordEscapedVarName(name);\n }\n }\n } else if (n.isGetProp() && n.isUnscopedQualifiedName() &&\n NodeUtil.isLValue(n)) {\n String name = NodeUtil.getRootOfQualifiedName(n).getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode())\n .recordEscapedQualifiedName(n.getQualifiedName());\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n return;\n }\n if (n.isReturn() && n.getFirstChild() != null) {\n data.get(t.getScopeRoot()).recordNonEmptyReturn();\n }\n if (t.getScopeDepth() <= 2) {\n return;\n }\n if (n.isName() && NodeUtil.isLValue(n) &&\n !NodeUtil.isBleedingFunctionName(n)) {\n String name = n.getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordAssignedName(name);\n }\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordEscapedVarName(name);\n }\n }\n } else if (n.isGetProp() && n.isUnscopedQualifiedName() &&\n NodeUtil.isLValue(n)) {\n String name = NodeUtil.getRootOfQualifiedName(n).getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode())\n .recordEscapedQualifiedName(n.getQualifiedName());\n }\n }\n }\n }\n"}, "reference": " @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (t.inGlobalScope()) {\n return;\n }\n if (n.isReturn() && n.getFirstChild() != null) {\n data.get(t.getScopeRoot()).recordNonEmptyReturn();\n }\n if (t.getScopeDepth() <= 1) {\n return;\n }\n if (n.isName() && NodeUtil.isLValue(n) &&\n !NodeUtil.isBleedingFunctionName(n)) {\n String name = n.getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordAssignedName(name);\n }\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode()).recordEscapedVarName(name);\n }\n }\n } else if (n.isGetProp() && n.isUnscopedQualifiedName() &&\n NodeUtil.isLValue(n)) {\n String name = NodeUtil.getRootOfQualifiedName(n).getString();\n Scope scope = t.getScope();\n Var var = scope.getVar(name);\n if (var != null) {\n Scope ownerScope = var.getScope();\n if (scope != ownerScope && ownerScope.isLocal()) {\n data.get(ownerScope.getRootNode())\n .recordEscapedQualifiedName(n.getQualifiedName());\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-168"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-168"}} {"sample_uid": "defects4j_function_repair::Closure-39", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n String toStringHelper(boolean forAnnotations) {\n if (hasReferenceName()) {\n return getReferenceName();\n } else if (prettyPrint) {\n prettyPrint = false;\n Set propertyNames = Sets.newTreeSet();\n for (ObjectType current = this;\n current != null && !current.isNativeObjectType() &&\n propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES;\n current = current.getImplicitPrototype()) {\n propertyNames.addAll(current.getOwnPropertyNames());\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\");\n int i = 0;\n for (String property : propertyNames) {\n if (i > 0) {\n sb.append(\", \");\n }\n sb.append(property);\n sb.append(\": \");\n sb.append(getPropertyType(property).toString());\n ++i;\n if (i == MAX_PRETTY_PRINTED_PROPERTIES) {\n sb.append(\", ...\");\n break;\n }\n }\n sb.append(\"}\");\n prettyPrint = true;\n return sb.toString();\n } else {\n return \"{...}\";\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " String toStringHelper(boolean forAnnotations) {\n if (hasReferenceName()) {\n return getReferenceName();\n } else if (prettyPrint) {\n prettyPrint = false;\n Set propertyNames = Sets.newTreeSet();\n for (ObjectType current = this;\n current != null && !current.isNativeObjectType() &&\n propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES;\n current = current.getImplicitPrototype()) {\n propertyNames.addAll(current.getOwnPropertyNames());\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\");\n int i = 0;\n for (String property : propertyNames) {\n if (i > 0) {\n sb.append(\", \");\n }\n sb.append(property);\n sb.append(\": \");\n sb.append(getPropertyType(property).toString());\n ++i;\n if (i == MAX_PRETTY_PRINTED_PROPERTIES) {\n sb.append(\", ...\");\n break;\n }\n }\n sb.append(\"}\");\n prettyPrint = true;\n return sb.toString();\n } else {\n return \"{...}\";\n }\n }\n"}, "reference": " String toStringHelper(boolean forAnnotations) {\n if (hasReferenceName()) {\n return getReferenceName();\n } else if (prettyPrint) {\n prettyPrint = false;\n Set propertyNames = Sets.newTreeSet();\n for (ObjectType current = this;\n current != null && !current.isNativeObjectType() &&\n propertyNames.size() <= MAX_PRETTY_PRINTED_PROPERTIES;\n current = current.getImplicitPrototype()) {\n propertyNames.addAll(current.getOwnPropertyNames());\n }\n StringBuilder sb = new StringBuilder();\n sb.append(\"{\");\n int i = 0;\n for (String property : propertyNames) {\n if (i > 0) {\n sb.append(\", \");\n }\n sb.append(property);\n sb.append(\": \");\n sb.append(getPropertyType(property).toStringHelper(forAnnotations));\n ++i;\n if (!forAnnotations && i == MAX_PRETTY_PRINTED_PROPERTIES) {\n sb.append(\", ...\");\n break;\n }\n }\n sb.append(\"}\");\n prettyPrint = true;\n return sb.toString();\n } else {\n return forAnnotations ? \"?\" : \"{...}\";\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-39"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-39"}} {"sample_uid": "defects4j_function_repair::Lang-53", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static void modify(Calendar val, int field, boolean round) {\n if (val.get(Calendar.YEAR) > 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n if (field == Calendar.MILLISECOND) {\n return;\n }\n Date date = val.getTime();\n long time = date.getTime();\n boolean done = false;\n int millisecs = val.get(Calendar.MILLISECOND);\n if (!round || millisecs < 500) {\n time = time - millisecs;\n if (field == Calendar.SECOND) {\n done = true;\n }\n }\n int seconds = val.get(Calendar.SECOND);\n if (!done && (!round || seconds < 30)) {\n time = time - (seconds * 1000L);\n if (field == Calendar.MINUTE) {\n done = true;\n }\n }\n int minutes = val.get(Calendar.MINUTE);\n if (!done && (!round || minutes < 30)) {\n time = time - (minutes * 60000L);\n }\n if (date.getTime() != time) {\n date.setTime(time);\n val.setTime(date);\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n if (offset != 0) {\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static void modify(Calendar val, int field, boolean round) {\n if (val.get(Calendar.YEAR) > 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n if (field == Calendar.MILLISECOND) {\n return;\n }\n Date date = val.getTime();\n long time = date.getTime();\n boolean done = false;\n int millisecs = val.get(Calendar.MILLISECOND);\n if (!round || millisecs < 500) {\n time = time - millisecs;\n if (field == Calendar.SECOND) {\n done = true;\n }\n }\n int seconds = val.get(Calendar.SECOND);\n if (!done && (!round || seconds < 30)) {\n time = time - (seconds * 1000L);\n if (field == Calendar.MINUTE) {\n done = true;\n }\n }\n int minutes = val.get(Calendar.MINUTE);\n if (!done && (!round || minutes < 30)) {\n time = time - (minutes * 60000L);\n }\n if (date.getTime() != time) {\n date.setTime(time);\n val.setTime(date);\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n if (offset != 0) {\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n"}, "reference": " private static void modify(Calendar val, int field, boolean round) {\n if (val.get(Calendar.YEAR) > 280000000) {\n throw new ArithmeticException(\"Calendar value too large for accurate calculations\");\n }\n if (field == Calendar.MILLISECOND) {\n return;\n }\n Date date = val.getTime();\n long time = date.getTime();\n boolean done = false;\n int millisecs = val.get(Calendar.MILLISECOND);\n if (!round || millisecs < 500) {\n time = time - millisecs;\n }\n if (field == Calendar.SECOND) {\n done = true;\n }\n int seconds = val.get(Calendar.SECOND);\n if (!done && (!round || seconds < 30)) {\n time = time - (seconds * 1000L);\n }\n if (field == Calendar.MINUTE) {\n done = true;\n }\n int minutes = val.get(Calendar.MINUTE);\n if (!done && (!round || minutes < 30)) {\n time = time - (minutes * 60000L);\n }\n if (date.getTime() != time) {\n date.setTime(time);\n val.setTime(date);\n }\n boolean roundUp = false;\n for (int i = 0; i < fields.length; i++) {\n for (int j = 0; j < fields[i].length; j++) {\n if (fields[i][j] == field) {\n if (round && roundUp) {\n if (field == DateUtils.SEMI_MONTH) {\n if (val.get(Calendar.DATE) == 1) {\n val.add(Calendar.DATE, 15);\n } else {\n val.add(Calendar.DATE, -15);\n val.add(Calendar.MONTH, 1);\n }\n } else {\n val.add(fields[i][0], 1);\n }\n }\n return;\n }\n }\n int offset = 0;\n boolean offsetSet = false;\n switch (field) {\n case DateUtils.SEMI_MONTH:\n if (fields[i][0] == Calendar.DATE) {\n offset = val.get(Calendar.DATE) - 1;\n if (offset >= 15) {\n offset -= 15;\n }\n roundUp = offset > 7;\n offsetSet = true;\n }\n break;\n case Calendar.AM_PM:\n if (fields[i][0] == Calendar.HOUR_OF_DAY) {\n offset = val.get(Calendar.HOUR_OF_DAY);\n if (offset >= 12) {\n offset -= 12;\n }\n roundUp = offset > 6;\n offsetSet = true;\n }\n break;\n }\n if (!offsetSet) {\n int min = val.getActualMinimum(fields[i][0]);\n int max = val.getActualMaximum(fields[i][0]);\n offset = val.get(fields[i][0]) - min;\n roundUp = offset > ((max - min) / 2);\n }\n if (offset != 0) {\n val.set(fields[i][0], val.get(fields[i][0]) - offset);\n }\n }\n throw new IllegalArgumentException(\"The field \" + field + \" is not supported\");\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-53"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-53"}} {"sample_uid": "defects4j_function_repair::Csv-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int read() throws IOException {\n int current = super.read();\n if (current == '\\n') {\n lineCounter++;\n }\n lastChar = current;\n return lastChar;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int read() throws IOException {\n int current = super.read();\n if (current == '\\n') {\n lineCounter++;\n }\n lastChar = current;\n return lastChar;\n }\n"}, "reference": " public int read() throws IOException {\n int current = super.read();\n if (current == '\\r' || (current == '\\n' && lastChar != '\\r')) {\n lineCounter++;\n }\n lastChar = current;\n return lastChar;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-1"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-35", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.canReadTypeId()) {\n Object typeId = p.getTypeId();\n if (typeId != null) {\n return _deserializeWithNativeTypeId(p, ctxt, typeId);\n }\n }\n if (p.getCurrentToken() != JsonToken.START_OBJECT) {\n throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,\n \"need JSON Object to contain As.WRAPPER_OBJECT type information for class \"+baseTypeName());\n }\n if (p.nextToken() != JsonToken.FIELD_NAME) {\n throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,\n \"need JSON String that contains type id (for subtype of \"+baseTypeName()+\")\");\n }\n final String typeId = p.getText();\n JsonDeserializer deser = _findDeserializer(ctxt, typeId);\n p.nextToken();\n if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {\n TokenBuffer tb = new TokenBuffer(null, false);\n tb.writeStartObject(); \n tb.writeFieldName(_typePropertyName);\n tb.writeString(typeId);\n p = JsonParserSequence.createFlattened(tb.asParser(p), p);\n p.nextToken();\n }\n Object value = deser.deserialize(p, ctxt);\n if (p.nextToken() != JsonToken.END_OBJECT) {\n throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,\n \"expected closing END_OBJECT after type information and deserialized value\");\n }\n return value;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.canReadTypeId()) {\n Object typeId = p.getTypeId();\n if (typeId != null) {\n return _deserializeWithNativeTypeId(p, ctxt, typeId);\n }\n }\n if (p.getCurrentToken() != JsonToken.START_OBJECT) {\n throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,\n \"need JSON Object to contain As.WRAPPER_OBJECT type information for class \"+baseTypeName());\n }\n if (p.nextToken() != JsonToken.FIELD_NAME) {\n throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,\n \"need JSON String that contains type id (for subtype of \"+baseTypeName()+\")\");\n }\n final String typeId = p.getText();\n JsonDeserializer deser = _findDeserializer(ctxt, typeId);\n p.nextToken();\n if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {\n TokenBuffer tb = new TokenBuffer(null, false);\n tb.writeStartObject(); \n tb.writeFieldName(_typePropertyName);\n tb.writeString(typeId);\n p = JsonParserSequence.createFlattened(tb.asParser(p), p);\n p.nextToken();\n }\n Object value = deser.deserialize(p, ctxt);\n if (p.nextToken() != JsonToken.END_OBJECT) {\n throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,\n \"expected closing END_OBJECT after type information and deserialized value\");\n }\n return value;\n }\n"}, "reference": " private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.canReadTypeId()) {\n Object typeId = p.getTypeId();\n if (typeId != null) {\n return _deserializeWithNativeTypeId(p, ctxt, typeId);\n }\n }\n JsonToken t = p.getCurrentToken();\n if (t == JsonToken.START_OBJECT) {\n if (p.nextToken() != JsonToken.FIELD_NAME) {\n throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,\n \"need JSON String that contains type id (for subtype of \"+baseTypeName()+\")\");\n }\n } else if (t != JsonToken.FIELD_NAME) {\n throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,\n \"need JSON Object to contain As.WRAPPER_OBJECT type information for class \"+baseTypeName());\n }\n final String typeId = p.getText();\n JsonDeserializer deser = _findDeserializer(ctxt, typeId);\n p.nextToken();\n if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {\n TokenBuffer tb = new TokenBuffer(null, false);\n tb.writeStartObject(); \n tb.writeFieldName(_typePropertyName);\n tb.writeString(typeId);\n p = JsonParserSequence.createFlattened(tb.asParser(p), p);\n p.nextToken();\n }\n Object value = deser.deserialize(p, ctxt);\n if (p.nextToken() != JsonToken.END_OBJECT) {\n throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,\n \"expected closing END_OBJECT after type information and deserialized value\");\n }\n return value;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-35"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-35"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-64", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType;\n try {\n serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n } catch (JsonMappingException e) {\n return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());\n }\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n prov.reportBadPropertyDefinition(_beanDesc, propDef,\n \"serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),\n _defaultInclusion);\n inclV = inclV.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n switch (inclusion) {\n case NON_DEFAULT:\n if (_useRealPropertyDefaults) {\n if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {\n am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);\n } else {\n valueToSuppress = getDefaultValue(actualType);\n suppressNulls = true;\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (actualType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (actualType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType;\n try {\n serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n } catch (JsonMappingException e) {\n return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());\n }\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n prov.reportBadPropertyDefinition(_beanDesc, propDef,\n \"serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),\n _defaultInclusion);\n inclV = inclV.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n switch (inclusion) {\n case NON_DEFAULT:\n if (_useRealPropertyDefaults) {\n if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {\n am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);\n } else {\n valueToSuppress = getDefaultValue(actualType);\n suppressNulls = true;\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (actualType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (actualType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n"}, "reference": " protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType;\n try {\n serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n } catch (JsonMappingException e) {\n return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());\n }\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n prov.reportBadPropertyDefinition(_beanDesc, propDef,\n \"serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),\n _defaultInclusion);\n inclV = inclV.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n switch (inclusion) {\n case NON_DEFAULT:\n Object defaultBean;\n if (_useRealPropertyDefaults && (defaultBean = getDefaultBean()) != null) {\n if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {\n am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n try {\n valueToSuppress = am.getValue(defaultBean);\n } catch (Exception e) {\n _throwWrapped(e, propDef.getName(), defaultBean);\n }\n } else {\n valueToSuppress = getDefaultValue(actualType);\n suppressNulls = true;\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (actualType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (actualType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-64"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-64"}} {"sample_uid": "defects4j_function_repair::Closure-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean apply(Node n) {\n if (n == null) {\n return false;\n }\n if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {\n return true;\n }\n if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {\n return true;\n }\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {\n return true;\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean apply(Node n) {\n if (n == null) {\n return false;\n }\n if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {\n return true;\n }\n if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {\n return true;\n }\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {\n return true;\n }\n }\n return false;\n }\n"}, "reference": " public boolean apply(Node n) {\n if (n == null) {\n return false;\n }\n if (n.isCall() && NodeUtil.functionCallHasSideEffects(n)) {\n return true;\n }\n if (n.isNew() && NodeUtil.constructorCallHasSideEffects(n)) {\n return true;\n }\n if (n.isDelProp()) {\n return true;\n }\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(c) && apply(c)) {\n return true;\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-15"}} {"sample_uid": "defects4j_function_repair::Math-75", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double getPct(Object v) {\n return getCumPct((Comparable) v);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double getPct(Object v) {\n return getCumPct((Comparable) v);\n }\n"}, "reference": " public double getPct(Object v) {\n return getPct((Comparable) v);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-75"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-75"}} {"sample_uid": "defects4j_function_repair::Jsoup-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Element insert(Token.StartTag startTag) {\n if (startTag.isSelfClosing()) {\n Element el = insertEmpty(startTag);\n stack.add(el);\n tokeniser.emit(new Token.EndTag(el.tagName())); \n return el;\n }\n Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);\n insert(el);\n return el;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Element insert(Token.StartTag startTag) {\n if (startTag.isSelfClosing()) {\n Element el = insertEmpty(startTag);\n stack.add(el);\n tokeniser.emit(new Token.EndTag(el.tagName())); \n return el;\n }\n Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);\n insert(el);\n return el;\n }\n"}, "reference": " Element insert(Token.StartTag startTag) {\n if (startTag.isSelfClosing()) {\n Element el = insertEmpty(startTag);\n stack.add(el);\n tokeniser.transition(TokeniserState.Data); \n tokeniser.emit(new Token.EndTag(el.tagName())); \n return el;\n }\n Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);\n insert(el);\n return el;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-33"}} {"sample_uid": "defects4j_function_repair::Mockito-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Object answer(InvocationOnMock invocation) {\n if (methodsGuru.isToString(invocation.getMethod())) {\n Object mock = invocation.getMock();\n MockName name = mockUtil.getMockName(mock);\n if (name.isDefault()) {\n return \"Mock for \" + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + \", hashCode: \" + mock.hashCode();\n } else {\n return name.toString();\n }\n } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {\n return 1;\n }\n Class returnType = invocation.getMethod().getReturnType();\n return returnValueFor(returnType);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Object answer(InvocationOnMock invocation) {\n if (methodsGuru.isToString(invocation.getMethod())) {\n Object mock = invocation.getMock();\n MockName name = mockUtil.getMockName(mock);\n if (name.isDefault()) {\n return \"Mock for \" + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + \", hashCode: \" + mock.hashCode();\n } else {\n return name.toString();\n }\n } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {\n return 1;\n }\n Class returnType = invocation.getMethod().getReturnType();\n return returnValueFor(returnType);\n }\n"}, "reference": " public Object answer(InvocationOnMock invocation) {\n if (methodsGuru.isToString(invocation.getMethod())) {\n Object mock = invocation.getMock();\n MockName name = mockUtil.getMockName(mock);\n if (name.isDefault()) {\n return \"Mock for \" + mockUtil.getMockSettings(mock).getTypeToMock().getSimpleName() + \", hashCode: \" + mock.hashCode();\n } else {\n return name.toString();\n }\n } else if (methodsGuru.isCompareToMethod(invocation.getMethod())) {\n return invocation.getMock() == invocation.getArguments()[0] ? 0 : 1;\n }\n Class returnType = invocation.getMethod().getReturnType();\n return returnValueFor(returnType);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-24"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected JavaType _fromVariable(TypeVariable type, TypeBindings context)\n {\n final String name = type.getName();\n if (context == null) {\n return _unknownType();\n } else {\n JavaType actualType = context.findType(name);\n if (actualType != null) {\n return actualType;\n }\n }\n Type[] bounds = type.getBounds();\n context._addPlaceholder(name);\n return _constructType(bounds[0], context);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected JavaType _fromVariable(TypeVariable type, TypeBindings context)\n {\n final String name = type.getName();\n if (context == null) {\n return _unknownType();\n } else {\n JavaType actualType = context.findType(name);\n if (actualType != null) {\n return actualType;\n }\n }\n Type[] bounds = type.getBounds();\n context._addPlaceholder(name);\n return _constructType(bounds[0], context);\n }\n"}, "reference": " protected JavaType _fromVariable(TypeVariable type, TypeBindings context)\n {\n final String name = type.getName();\n if (context == null) {\n context = new TypeBindings(this, (Class) null);\n } else {\n JavaType actualType = context.findType(name, false);\n if (actualType != null) {\n return actualType;\n }\n }\n Type[] bounds = type.getBounds();\n context._addPlaceholder(name);\n return _constructType(bounds[0], context);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-11"}} {"sample_uid": "defects4j_function_repair::Closure-94", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean isValidDefineValue(Node val, Set defines) {\n switch (val.getType()) {\n case Token.STRING:\n case Token.NUMBER:\n case Token.TRUE:\n case Token.FALSE:\n return true;\n case Token.BITAND:\n case Token.BITNOT:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.NOT:\n case Token.NEG:\n return isValidDefineValue(val.getFirstChild(), defines);\n case Token.NAME:\n case Token.GETPROP:\n if (val.isQualifiedName()) {\n return defines.contains(val.getQualifiedName());\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean isValidDefineValue(Node val, Set defines) {\n switch (val.getType()) {\n case Token.STRING:\n case Token.NUMBER:\n case Token.TRUE:\n case Token.FALSE:\n return true;\n case Token.BITAND:\n case Token.BITNOT:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.NOT:\n case Token.NEG:\n return isValidDefineValue(val.getFirstChild(), defines);\n case Token.NAME:\n case Token.GETPROP:\n if (val.isQualifiedName()) {\n return defines.contains(val.getQualifiedName());\n }\n }\n return false;\n }\n"}, "reference": " static boolean isValidDefineValue(Node val, Set defines) {\n switch (val.getType()) {\n case Token.STRING:\n case Token.NUMBER:\n case Token.TRUE:\n case Token.FALSE:\n return true;\n case Token.ADD:\n case Token.BITAND:\n case Token.BITNOT:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.DIV:\n case Token.EQ:\n case Token.GE:\n case Token.GT:\n case Token.LE:\n case Token.LSH:\n case Token.LT:\n case Token.MOD:\n case Token.MUL:\n case Token.NE:\n case Token.RSH:\n case Token.SHEQ:\n case Token.SHNE:\n case Token.SUB:\n case Token.URSH:\n return isValidDefineValue(val.getFirstChild(), defines)\n && isValidDefineValue(val.getLastChild(), defines);\n case Token.NOT:\n case Token.NEG:\n case Token.POS:\n return isValidDefineValue(val.getFirstChild(), defines);\n case Token.NAME:\n case Token.GETPROP:\n if (val.isQualifiedName()) {\n return defines.contains(val.getQualifiedName());\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-94"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-94"}} {"sample_uid": "defects4j_function_repair::Jsoup-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = meta.hasAttr(\"http-equiv\") ? getCharsetFromContentType(meta.attr(\"content\")) : meta.attr(\"charset\");\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = meta.hasAttr(\"http-equiv\") ? getCharsetFromContentType(meta.attr(\"content\")) : meta.attr(\"charset\");\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (doc == null) {\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n"}, "reference": " static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {\n String docData;\n Document doc = null;\n if (charsetName == null) { \n docData = Charset.forName(defaultCharset).decode(byteData).toString();\n doc = parser.parseInput(docData, baseUri);\n Element meta = doc.select(\"meta[http-equiv=content-type], meta[charset]\").first();\n if (meta != null) { \n String foundCharset = meta.hasAttr(\"http-equiv\") ? getCharsetFromContentType(meta.attr(\"content\")) : meta.attr(\"charset\");\n if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { \n charsetName = foundCharset;\n byteData.rewind();\n docData = Charset.forName(foundCharset).decode(byteData).toString();\n doc = null;\n }\n }\n } else { \n Validate.notEmpty(charsetName, \"Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML\");\n docData = Charset.forName(charsetName).decode(byteData).toString();\n }\n if (doc == null) {\n if (docData.charAt(0) == 65279)\n docData = docData.substring(1);\n doc = parser.parseInput(docData, baseUri);\n doc.outputSettings().charset(charsetName);\n }\n return doc;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-20"}} {"sample_uid": "defects4j_function_repair::Cli-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void checkRequiredOptions()\n throws MissingOptionException\n {\n if (getRequiredOptions().size() > 0)\n {\n Iterator iter = getRequiredOptions().iterator();\n StringBuffer buff = new StringBuffer(\"Missing required option\");\n buff.append(getRequiredOptions().size() == 1 ? \"\" : \"s\");\n buff.append(\": \");\n while (iter.hasNext())\n {\n buff.append(iter.next());\n }\n throw new MissingOptionException(buff.toString());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void checkRequiredOptions()\n throws MissingOptionException\n {\n if (getRequiredOptions().size() > 0)\n {\n Iterator iter = getRequiredOptions().iterator();\n StringBuffer buff = new StringBuffer(\"Missing required option\");\n buff.append(getRequiredOptions().size() == 1 ? \"\" : \"s\");\n buff.append(\": \");\n while (iter.hasNext())\n {\n buff.append(iter.next());\n }\n throw new MissingOptionException(buff.toString());\n }\n }\n"}, "reference": " protected void checkRequiredOptions()\n throws MissingOptionException\n {\n if (getRequiredOptions().size() > 0)\n {\n Iterator iter = getRequiredOptions().iterator();\n StringBuffer buff = new StringBuffer(\"Missing required option\");\n buff.append(getRequiredOptions().size() == 1 ? \"\" : \"s\");\n buff.append(\": \");\n while (iter.hasNext())\n {\n buff.append(iter.next());\n buff.append(\", \");\n }\n throw new MissingOptionException(buff.substring(0, buff.length() - 2));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-9"}} {"sample_uid": "defects4j_function_repair::Time-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n }\n return offsetAdjusted;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n }\n return offsetAdjusted;\n }\n"}, "reference": " public int getOffsetFromLocal(long instantLocal) {\n final int offsetLocal = getOffset(instantLocal);\n final long instantAdjusted = instantLocal - offsetLocal;\n final int offsetAdjusted = getOffset(instantAdjusted);\n if (offsetLocal != offsetAdjusted) {\n if ((offsetLocal - offsetAdjusted) < 0) {\n long nextLocal = nextTransition(instantAdjusted);\n long nextAdjusted = nextTransition(instantLocal - offsetAdjusted);\n if (nextLocal != nextAdjusted) {\n return offsetLocal;\n }\n }\n } else if (offsetLocal > 0) {\n long prev = previousTransition(instantAdjusted);\n if (prev < instantAdjusted) {\n int offsetPrev = getOffset(prev);\n int diff = offsetPrev - offsetLocal;\n if (instantAdjusted - prev <= diff) {\n return offsetPrev;\n }\n }\n }\n return offsetAdjusted;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-25"}} {"sample_uid": "defects4j_function_repair::Math-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void guessAOmega() {\n double sx2 = 0;\n double sy2 = 0;\n double sxy = 0;\n double sxz = 0;\n double syz = 0;\n double currentX = observations[0].getX();\n double currentY = observations[0].getY();\n double f2Integral = 0;\n double fPrime2Integral = 0;\n final double startX = currentX;\n for (int i = 1; i < observations.length; ++i) {\n final double previousX = currentX;\n final double previousY = currentY;\n currentX = observations[i].getX();\n currentY = observations[i].getY();\n final double dx = currentX - previousX;\n final double dy = currentY - previousY;\n final double f2StepIntegral =\n dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;\n final double fPrime2StepIntegral = dy * dy / dx;\n final double x = currentX - startX;\n f2Integral += f2StepIntegral;\n fPrime2Integral += fPrime2StepIntegral;\n sx2 += x * x;\n sy2 += f2Integral * f2Integral;\n sxy += x * f2Integral;\n sxz += x * fPrime2Integral;\n syz += f2Integral * fPrime2Integral;\n }\n double c1 = sy2 * sxz - sxy * syz;\n double c2 = sxy * sxz - sx2 * syz;\n double c3 = sx2 * sy2 - sxy * sxy;\n if ((c1 / c2 < 0) || (c2 / c3 < 0)) {\n final int last = observations.length - 1;\n final double xRange = observations[last].getX() - observations[0].getX();\n if (xRange == 0) {\n throw new ZeroException();\n }\n omega = 2 * Math.PI / xRange;\n double yMin = Double.POSITIVE_INFINITY;\n double yMax = Double.NEGATIVE_INFINITY;\n for (int i = 1; i < observations.length; ++i) {\n final double y = observations[i].getY();\n if (y < yMin) {\n yMin = y;\n }\n if (y > yMax) {\n yMax = y;\n }\n }\n a = 0.5 * (yMax - yMin);\n } else {\n a = FastMath.sqrt(c1 / c2);\n omega = FastMath.sqrt(c2 / c3);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void guessAOmega() {\n double sx2 = 0;\n double sy2 = 0;\n double sxy = 0;\n double sxz = 0;\n double syz = 0;\n double currentX = observations[0].getX();\n double currentY = observations[0].getY();\n double f2Integral = 0;\n double fPrime2Integral = 0;\n final double startX = currentX;\n for (int i = 1; i < observations.length; ++i) {\n final double previousX = currentX;\n final double previousY = currentY;\n currentX = observations[i].getX();\n currentY = observations[i].getY();\n final double dx = currentX - previousX;\n final double dy = currentY - previousY;\n final double f2StepIntegral =\n dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;\n final double fPrime2StepIntegral = dy * dy / dx;\n final double x = currentX - startX;\n f2Integral += f2StepIntegral;\n fPrime2Integral += fPrime2StepIntegral;\n sx2 += x * x;\n sy2 += f2Integral * f2Integral;\n sxy += x * f2Integral;\n sxz += x * fPrime2Integral;\n syz += f2Integral * fPrime2Integral;\n }\n double c1 = sy2 * sxz - sxy * syz;\n double c2 = sxy * sxz - sx2 * syz;\n double c3 = sx2 * sy2 - sxy * sxy;\n if ((c1 / c2 < 0) || (c2 / c3 < 0)) {\n final int last = observations.length - 1;\n final double xRange = observations[last].getX() - observations[0].getX();\n if (xRange == 0) {\n throw new ZeroException();\n }\n omega = 2 * Math.PI / xRange;\n double yMin = Double.POSITIVE_INFINITY;\n double yMax = Double.NEGATIVE_INFINITY;\n for (int i = 1; i < observations.length; ++i) {\n final double y = observations[i].getY();\n if (y < yMin) {\n yMin = y;\n }\n if (y > yMax) {\n yMax = y;\n }\n }\n a = 0.5 * (yMax - yMin);\n } else {\n a = FastMath.sqrt(c1 / c2);\n omega = FastMath.sqrt(c2 / c3);\n }\n }\n"}, "reference": " private void guessAOmega() {\n double sx2 = 0;\n double sy2 = 0;\n double sxy = 0;\n double sxz = 0;\n double syz = 0;\n double currentX = observations[0].getX();\n double currentY = observations[0].getY();\n double f2Integral = 0;\n double fPrime2Integral = 0;\n final double startX = currentX;\n for (int i = 1; i < observations.length; ++i) {\n final double previousX = currentX;\n final double previousY = currentY;\n currentX = observations[i].getX();\n currentY = observations[i].getY();\n final double dx = currentX - previousX;\n final double dy = currentY - previousY;\n final double f2StepIntegral =\n dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3;\n final double fPrime2StepIntegral = dy * dy / dx;\n final double x = currentX - startX;\n f2Integral += f2StepIntegral;\n fPrime2Integral += fPrime2StepIntegral;\n sx2 += x * x;\n sy2 += f2Integral * f2Integral;\n sxy += x * f2Integral;\n sxz += x * fPrime2Integral;\n syz += f2Integral * fPrime2Integral;\n }\n double c1 = sy2 * sxz - sxy * syz;\n double c2 = sxy * sxz - sx2 * syz;\n double c3 = sx2 * sy2 - sxy * sxy;\n if ((c1 / c2 < 0) || (c2 / c3 < 0)) {\n final int last = observations.length - 1;\n final double xRange = observations[last].getX() - observations[0].getX();\n if (xRange == 0) {\n throw new ZeroException();\n }\n omega = 2 * Math.PI / xRange;\n double yMin = Double.POSITIVE_INFINITY;\n double yMax = Double.NEGATIVE_INFINITY;\n for (int i = 1; i < observations.length; ++i) {\n final double y = observations[i].getY();\n if (y < yMin) {\n yMin = y;\n }\n if (y > yMax) {\n yMax = y;\n }\n }\n a = 0.5 * (yMax - yMin);\n } else {\n if (c2 == 0) {\n throw new MathIllegalStateException(LocalizedFormats.ZERO_DENOMINATOR);\n }\n a = FastMath.sqrt(c1 / c2);\n omega = FastMath.sqrt(c2 / c3);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-25"}} {"sample_uid": "defects4j_function_repair::Mockito-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void resetMock(T mock) {\n MockHandlerInterface oldMockHandler = getMockHandler(mock);\n MockHandler newMockHandler = new MockHandler(oldMockHandler);\n MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) org.mockito.Mockito.withSettings().defaultAnswer(org.mockito.Mockito.RETURNS_DEFAULTS));\n ((Factory) mock).setCallback(0, newFilter);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void resetMock(T mock) {\n MockHandlerInterface oldMockHandler = getMockHandler(mock);\n MockHandler newMockHandler = new MockHandler(oldMockHandler);\n MethodInterceptorFilter newFilter = new MethodInterceptorFilter(newMockHandler, (MockSettingsImpl) org.mockito.Mockito.withSettings().defaultAnswer(org.mockito.Mockito.RETURNS_DEFAULTS));\n ((Factory) mock).setCallback(0, newFilter);\n }\n"}, "reference": " public void resetMock(T mock) {\n MockHandlerInterface oldMockHandler = getMockHandler(mock);\n MethodInterceptorFilter newFilter = newMethodInterceptorFilter(oldMockHandler.getMockSettings());\n ((Factory) mock).setCallback(0, newFilter);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-27"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException\n {\n copyCurrentStructure(jp);\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException\n {\n copyCurrentStructure(jp);\n return this;\n }\n"}, "reference": " public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException\n {\n if (jp.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) {\n copyCurrentStructure(jp);\n return this;\n }\n JsonToken t;\n writeStartObject();\n do {\n copyCurrentStructure(jp);\n } while ((t = jp.nextToken()) == JsonToken.FIELD_NAME);\n if (t != JsonToken.END_OBJECT) {\n throw ctxt.mappingException(\"Expected END_OBJECT after copying contents of a JsonParser into TokenBuffer, got \"+t);\n }\n writeEndObject();\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-7"}} {"sample_uid": "defects4j_function_repair::Jsoup-57", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void removeIgnoreCase(String key) {\n Validate.notEmpty(key);\n if (attributes == null)\n return;\n for (Iterator it = attributes.keySet().iterator(); it.hasNext(); ) {\n String attrKey = it.next();\n if (attrKey.equalsIgnoreCase(key))\n attributes.remove(attrKey);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void removeIgnoreCase(String key) {\n Validate.notEmpty(key);\n if (attributes == null)\n return;\n for (Iterator it = attributes.keySet().iterator(); it.hasNext(); ) {\n String attrKey = it.next();\n if (attrKey.equalsIgnoreCase(key))\n attributes.remove(attrKey);\n }\n }\n"}, "reference": " public void removeIgnoreCase(String key) {\n Validate.notEmpty(key);\n if (attributes == null)\n return;\n for (Iterator it = attributes.keySet().iterator(); it.hasNext(); ) {\n String attrKey = it.next();\n if (attrKey.equalsIgnoreCase(key))\n it.remove();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-57"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-57"}} {"sample_uid": "defects4j_function_repair::Lang-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n"}, "reference": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos || expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n if (expPos > str.length()) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-27"}} {"sample_uid": "defects4j_function_repair::Lang-22", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static int greatestCommonDivisor(int u, int v) {\n if (Math.abs(u) <= 1 || Math.abs(v) <= 1) {\n return 1;\n }\n if (u>0) { u=-u; } \n if (v>0) { v=-v; } \n int k=0;\n while ((u&1)==0 && (v&1)==0 && k<31) { \n u/=2; v/=2; k++; \n }\n if (k==31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u&1)==1) ? v : -(u/2);\n do {\n while ((t&1)==0) { \n t/=2; \n }\n if (t>0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u)/2;\n } while (t!=0);\n return -u*(1<0) { u=-u; } \n if (v>0) { v=-v; } \n int k=0;\n while ((u&1)==0 && (v&1)==0 && k<31) { \n u/=2; v/=2; k++; \n }\n if (k==31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u&1)==1) ? v : -(u/2);\n do {\n while ((t&1)==0) { \n t/=2; \n }\n if (t>0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u)/2;\n } while (t!=0);\n return -u*(1<0) { u=-u; } \n if (v>0) { v=-v; } \n int k=0;\n while ((u&1)==0 && (v&1)==0 && k<31) { \n u/=2; v/=2; k++; \n }\n if (k==31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u&1)==1) ? v : -(u/2);\n do {\n while ((t&1)==0) { \n t/=2; \n }\n if (t>0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u)/2;\n } while (t!=0);\n return -u*(1< b.length || offset + len > b.length) {\n throw new IndexOutOfBoundsException();\n } else if (len == 0) {\n return 0;\n } else {\n if (!base64.hasData()) {\n byte[] buf = new byte[doEncode ? 4096 : 8192];\n int c = in.read(buf);\n if (c > 0 && b.length == len) {\n base64.setInitialBuffer(b, offset, len);\n }\n if (doEncode) {\n base64.encode(buf, 0, c);\n } else {\n base64.decode(buf, 0, c);\n }\n }\n return base64.readResults(b, offset, len);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int read(byte b[], int offset, int len) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n } else if (offset < 0 || len < 0) {\n throw new IndexOutOfBoundsException();\n } else if (offset > b.length || offset + len > b.length) {\n throw new IndexOutOfBoundsException();\n } else if (len == 0) {\n return 0;\n } else {\n if (!base64.hasData()) {\n byte[] buf = new byte[doEncode ? 4096 : 8192];\n int c = in.read(buf);\n if (c > 0 && b.length == len) {\n base64.setInitialBuffer(b, offset, len);\n }\n if (doEncode) {\n base64.encode(buf, 0, c);\n } else {\n base64.decode(buf, 0, c);\n }\n }\n return base64.readResults(b, offset, len);\n }\n }\n"}, "reference": " public int read(byte b[], int offset, int len) throws IOException {\n if (b == null) {\n throw new NullPointerException();\n } else if (offset < 0 || len < 0) {\n throw new IndexOutOfBoundsException();\n } else if (offset > b.length || offset + len > b.length) {\n throw new IndexOutOfBoundsException();\n } else if (len == 0) {\n return 0;\n } else {\n int readLen = 0;\n while (readLen == 0) {\n if (!base64.hasData()) {\n byte[] buf = new byte[doEncode ? 4096 : 8192];\n int c = in.read(buf);\n if (c > 0 && b.length == len) {\n base64.setInitialBuffer(b, offset, len);\n }\n if (doEncode) {\n base64.encode(buf, 0, c);\n } else {\n base64.decode(buf, 0, c);\n }\n }\n readLen = base64.readResults(b, offset, len);\n }\n return readLen;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-6"}} {"sample_uid": "defects4j_function_repair::Math-50", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n if (x == x1) {\n x0 = 0.5 * (x0 + x1 - FastMath.max(rtol * FastMath.abs(x1), atol));\n f0 = computeObjectiveValue(x0);\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n if (x == x1) {\n x0 = 0.5 * (x0 + x1 - FastMath.max(rtol * FastMath.abs(x1), atol));\n f0 = computeObjectiveValue(x0);\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n"}, "reference": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-50"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-50"}} {"sample_uid": "defects4j_function_repair::Math-39", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void integrate(final ExpandableStatefulODE equations, final double t)\n throws MathIllegalStateException, MathIllegalArgumentException {\n sanityChecks(equations, t);\n setEquations(equations);\n final boolean forward = t > equations.getTime();\n final double[] y0 = equations.getCompleteState();\n final double[] y = y0.clone();\n final int stages = c.length + 1;\n final double[][] yDotK = new double[stages][y.length];\n final double[] yTmp = y0.clone();\n final double[] yDotTmp = new double[y.length];\n final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy();\n interpolator.reinitialize(this, yTmp, yDotK, forward,\n equations.getPrimaryMapper(), equations.getSecondaryMappers());\n interpolator.storeTime(equations.getTime());\n stepStart = equations.getTime();\n double hNew = 0;\n boolean firstTime = true;\n initIntegration(equations.getTime(), y0, t);\n isLastStep = false;\n do {\n interpolator.shift();\n double error = 10;\n while (error >= 1.0) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale = new double[mainSetDimension];\n if (vecAbsoluteTolerance == null) {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]);\n }\n } else {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]);\n }\n }\n hNew = initializeStep(forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error >= 1.0) {\n final double factor =\n FastMath.min(maxGrowth,\n FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n interpolator.storeTime(stepStart + stepSize);\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length);\n stepStart = acceptStep(interpolator, y, yDotTmp, t);\n System.arraycopy(y, 0, yTmp, 0, y.length);\n if (!isLastStep) {\n interpolator.storeTime(stepStart);\n if (fsal) {\n System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length);\n }\n final double factor =\n FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n final double filteredNextT = stepStart + hNew;\n final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);\n if (filteredNextIsLast) {\n hNew = t - stepStart;\n }\n }\n } while (!isLastStep);\n equations.setTime(stepStart);\n equations.setCompleteState(y);\n resetInternalState();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void integrate(final ExpandableStatefulODE equations, final double t)\n throws MathIllegalStateException, MathIllegalArgumentException {\n sanityChecks(equations, t);\n setEquations(equations);\n final boolean forward = t > equations.getTime();\n final double[] y0 = equations.getCompleteState();\n final double[] y = y0.clone();\n final int stages = c.length + 1;\n final double[][] yDotK = new double[stages][y.length];\n final double[] yTmp = y0.clone();\n final double[] yDotTmp = new double[y.length];\n final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy();\n interpolator.reinitialize(this, yTmp, yDotK, forward,\n equations.getPrimaryMapper(), equations.getSecondaryMappers());\n interpolator.storeTime(equations.getTime());\n stepStart = equations.getTime();\n double hNew = 0;\n boolean firstTime = true;\n initIntegration(equations.getTime(), y0, t);\n isLastStep = false;\n do {\n interpolator.shift();\n double error = 10;\n while (error >= 1.0) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale = new double[mainSetDimension];\n if (vecAbsoluteTolerance == null) {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]);\n }\n } else {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]);\n }\n }\n hNew = initializeStep(forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error >= 1.0) {\n final double factor =\n FastMath.min(maxGrowth,\n FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n interpolator.storeTime(stepStart + stepSize);\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length);\n stepStart = acceptStep(interpolator, y, yDotTmp, t);\n System.arraycopy(y, 0, yTmp, 0, y.length);\n if (!isLastStep) {\n interpolator.storeTime(stepStart);\n if (fsal) {\n System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length);\n }\n final double factor =\n FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n final double filteredNextT = stepStart + hNew;\n final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);\n if (filteredNextIsLast) {\n hNew = t - stepStart;\n }\n }\n } while (!isLastStep);\n equations.setTime(stepStart);\n equations.setCompleteState(y);\n resetInternalState();\n }\n"}, "reference": " public void integrate(final ExpandableStatefulODE equations, final double t)\n throws MathIllegalStateException, MathIllegalArgumentException {\n sanityChecks(equations, t);\n setEquations(equations);\n final boolean forward = t > equations.getTime();\n final double[] y0 = equations.getCompleteState();\n final double[] y = y0.clone();\n final int stages = c.length + 1;\n final double[][] yDotK = new double[stages][y.length];\n final double[] yTmp = y0.clone();\n final double[] yDotTmp = new double[y.length];\n final RungeKuttaStepInterpolator interpolator = (RungeKuttaStepInterpolator) prototype.copy();\n interpolator.reinitialize(this, yTmp, yDotK, forward,\n equations.getPrimaryMapper(), equations.getSecondaryMappers());\n interpolator.storeTime(equations.getTime());\n stepStart = equations.getTime();\n double hNew = 0;\n boolean firstTime = true;\n initIntegration(equations.getTime(), y0, t);\n isLastStep = false;\n do {\n interpolator.shift();\n double error = 10;\n while (error >= 1.0) {\n if (firstTime || !fsal) {\n computeDerivatives(stepStart, y, yDotK[0]);\n }\n if (firstTime) {\n final double[] scale = new double[mainSetDimension];\n if (vecAbsoluteTolerance == null) {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = scalAbsoluteTolerance + scalRelativeTolerance * FastMath.abs(y[i]);\n }\n } else {\n for (int i = 0; i < scale.length; ++i) {\n scale[i] = vecAbsoluteTolerance[i] + vecRelativeTolerance[i] * FastMath.abs(y[i]);\n }\n }\n hNew = initializeStep(forward, getOrder(), scale,\n stepStart, y, yDotK[0], yTmp, yDotK[1]);\n firstTime = false;\n }\n stepSize = hNew;\n if (forward) {\n if (stepStart + stepSize >= t) {\n stepSize = t - stepStart;\n }\n } else {\n if (stepStart + stepSize <= t) {\n stepSize = t - stepStart;\n }\n }\n for (int k = 1; k < stages; ++k) {\n for (int j = 0; j < y0.length; ++j) {\n double sum = a[k-1][0] * yDotK[0][j];\n for (int l = 1; l < k; ++l) {\n sum += a[k-1][l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n computeDerivatives(stepStart + c[k-1] * stepSize, yTmp, yDotK[k]);\n }\n for (int j = 0; j < y0.length; ++j) {\n double sum = b[0] * yDotK[0][j];\n for (int l = 1; l < stages; ++l) {\n sum += b[l] * yDotK[l][j];\n }\n yTmp[j] = y[j] + stepSize * sum;\n }\n error = estimateError(yDotK, y, yTmp, stepSize);\n if (error >= 1.0) {\n final double factor =\n FastMath.min(maxGrowth,\n FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n hNew = filterStep(stepSize * factor, forward, false);\n }\n }\n interpolator.storeTime(stepStart + stepSize);\n System.arraycopy(yTmp, 0, y, 0, y0.length);\n System.arraycopy(yDotK[stages - 1], 0, yDotTmp, 0, y0.length);\n stepStart = acceptStep(interpolator, y, yDotTmp, t);\n System.arraycopy(y, 0, yTmp, 0, y.length);\n if (!isLastStep) {\n interpolator.storeTime(stepStart);\n if (fsal) {\n System.arraycopy(yDotTmp, 0, yDotK[0], 0, y0.length);\n }\n final double factor =\n FastMath.min(maxGrowth, FastMath.max(minReduction, safety * FastMath.pow(error, exp)));\n final double scaledH = stepSize * factor;\n final double nextT = stepStart + scaledH;\n final boolean nextIsLast = forward ? (nextT >= t) : (nextT <= t);\n hNew = filterStep(scaledH, forward, nextIsLast);\n final double filteredNextT = stepStart + hNew;\n final boolean filteredNextIsLast = forward ? (filteredNextT >= t) : (filteredNextT <= t);\n if (filteredNextIsLast) {\n hNew = t - stepStart;\n }\n }\n } while (!isLastStep);\n equations.setTime(stepStart);\n equations.setCompleteState(y);\n resetInternalState();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-39"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-39"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void _addMethodMixIns(Class targetClass, AnnotatedMethodMap methods,\n Class mixInCls, AnnotatedMethodMap mixIns)\n {\n List> parents = new ArrayList>();\n parents.add(mixInCls);\n ClassUtil.findSuperTypes(mixInCls, targetClass, parents);\n for (Class mixin : parents) {\n for (Method m : mixin.getDeclaredMethods()) {\n if (!_isIncludableMemberMethod(m)) {\n continue;\n }\n AnnotatedMethod am = methods.find(m);\n if (am != null) {\n _addMixUnders(m, am);\n } else {\n mixIns.add(_constructMethod(m));\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void _addMethodMixIns(Class targetClass, AnnotatedMethodMap methods,\n Class mixInCls, AnnotatedMethodMap mixIns)\n {\n List> parents = new ArrayList>();\n parents.add(mixInCls);\n ClassUtil.findSuperTypes(mixInCls, targetClass, parents);\n for (Class mixin : parents) {\n for (Method m : mixin.getDeclaredMethods()) {\n if (!_isIncludableMemberMethod(m)) {\n continue;\n }\n AnnotatedMethod am = methods.find(m);\n if (am != null) {\n _addMixUnders(m, am);\n } else {\n mixIns.add(_constructMethod(m));\n }\n }\n }\n }\n"}, "reference": " protected void _addMethodMixIns(Class targetClass, AnnotatedMethodMap methods,\n Class mixInCls, AnnotatedMethodMap mixIns)\n {\n List> parents = new ArrayList>();\n parents.add(mixInCls);\n ClassUtil.findSuperTypes(mixInCls, targetClass, parents);\n for (Class mixin : parents) {\n for (Method m : mixin.getDeclaredMethods()) {\n if (!_isIncludableMemberMethod(m)) {\n continue;\n }\n AnnotatedMethod am = methods.find(m);\n if (am != null) {\n _addMixUnders(m, am);\n } else {\n am = mixIns.find(m);\n if (am != null) {\n _addMixUnders(m, am);\n } else {\n mixIns.add(_constructMethod(m));\n }\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-5"}} {"sample_uid": "defects4j_function_repair::Closure-69", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void visitCall(NodeTraversal t, Node n) {\n Node child = n.getFirstChild();\n JSType childType = getJSType(child).restrictByNotNullOrUndefined();\n if (!childType.canBeCalled()) {\n report(t, n, NOT_CALLABLE, childType.toString());\n ensureTyped(t, n);\n return;\n }\n if (childType instanceof FunctionType) {\n FunctionType functionType = (FunctionType) childType;\n boolean isExtern = false;\n JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();\n if(functionJSDocInfo != null) {\n String sourceName = functionJSDocInfo.getSourceName();\n CompilerInput functionSource = compiler.getInput(sourceName);\n isExtern = functionSource.isExtern();\n }\n if (functionType.isConstructor() &&\n !functionType.isNativeObjectType() &&\n (functionType.getReturnType().isUnknownType() ||\n functionType.getReturnType().isVoidType() ||\n !isExtern)) {\n report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());\n }\n visitParameterList(t, n, functionType);\n ensureTyped(t, n, functionType.getReturnType());\n } else {\n ensureTyped(t, n);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void visitCall(NodeTraversal t, Node n) {\n Node child = n.getFirstChild();\n JSType childType = getJSType(child).restrictByNotNullOrUndefined();\n if (!childType.canBeCalled()) {\n report(t, n, NOT_CALLABLE, childType.toString());\n ensureTyped(t, n);\n return;\n }\n if (childType instanceof FunctionType) {\n FunctionType functionType = (FunctionType) childType;\n boolean isExtern = false;\n JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();\n if(functionJSDocInfo != null) {\n String sourceName = functionJSDocInfo.getSourceName();\n CompilerInput functionSource = compiler.getInput(sourceName);\n isExtern = functionSource.isExtern();\n }\n if (functionType.isConstructor() &&\n !functionType.isNativeObjectType() &&\n (functionType.getReturnType().isUnknownType() ||\n functionType.getReturnType().isVoidType() ||\n !isExtern)) {\n report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());\n }\n visitParameterList(t, n, functionType);\n ensureTyped(t, n, functionType.getReturnType());\n } else {\n ensureTyped(t, n);\n }\n }\n"}, "reference": " private void visitCall(NodeTraversal t, Node n) {\n Node child = n.getFirstChild();\n JSType childType = getJSType(child).restrictByNotNullOrUndefined();\n if (!childType.canBeCalled()) {\n report(t, n, NOT_CALLABLE, childType.toString());\n ensureTyped(t, n);\n return;\n }\n if (childType instanceof FunctionType) {\n FunctionType functionType = (FunctionType) childType;\n boolean isExtern = false;\n JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();\n if(functionJSDocInfo != null) {\n String sourceName = functionJSDocInfo.getSourceName();\n CompilerInput functionSource = compiler.getInput(sourceName);\n isExtern = functionSource.isExtern();\n }\n if (functionType.isConstructor() &&\n !functionType.isNativeObjectType() &&\n (functionType.getReturnType().isUnknownType() ||\n functionType.getReturnType().isVoidType() ||\n !isExtern)) {\n report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());\n }\n if (functionType.isOrdinaryFunction() &&\n !functionType.getTypeOfThis().isUnknownType() &&\n !functionType.getTypeOfThis().isNativeObjectType() &&\n !(child.getType() == Token.GETELEM ||\n child.getType() == Token.GETPROP)) {\n report(t, n, EXPECTED_THIS_TYPE, functionType.toString());\n }\n visitParameterList(t, n, functionType);\n ensureTyped(t, n, functionType.getReturnType());\n } else {\n ensureTyped(t, n);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-69"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-69"}} {"sample_uid": "defects4j_function_repair::Jsoup-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static String getCharsetFromContentType(String contentType) {\n if (contentType == null) return null;\n Matcher m = charsetPattern.matcher(contentType);\n if (m.find()) {\n String charset = m.group(1).trim();\n charset = charset.toUpperCase(Locale.ENGLISH);\n return charset;\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static String getCharsetFromContentType(String contentType) {\n if (contentType == null) return null;\n Matcher m = charsetPattern.matcher(contentType);\n if (m.find()) {\n String charset = m.group(1).trim();\n charset = charset.toUpperCase(Locale.ENGLISH);\n return charset;\n }\n return null;\n }\n"}, "reference": " static String getCharsetFromContentType(String contentType) {\n if (contentType == null) return null;\n Matcher m = charsetPattern.matcher(contentType);\n if (m.find()) {\n String charset = m.group(1).trim();\n if (Charset.isSupported(charset)) return charset;\n charset = charset.toUpperCase(Locale.ENGLISH);\n if (Charset.isSupported(charset)) return charset;\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-27"}} {"sample_uid": "defects4j_function_repair::Gson-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static TypeAdapter getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,\n TypeToken fieldType, JsonAdapter annotation) {\n Class value = annotation.value();\n TypeAdapter typeAdapter;\n if (TypeAdapter.class.isAssignableFrom(value)) {\n Class> typeAdapterClass = (Class>) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();\n } else if (TypeAdapterFactory.class.isAssignableFrom(value)) {\n Class typeAdapterFactory = (Class) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))\n .construct()\n .create(gson, fieldType);\n } else {\n throw new IllegalArgumentException(\n \"@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.\");\n }\n typeAdapter = typeAdapter.nullSafe();\n return typeAdapter;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static TypeAdapter getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,\n TypeToken fieldType, JsonAdapter annotation) {\n Class value = annotation.value();\n TypeAdapter typeAdapter;\n if (TypeAdapter.class.isAssignableFrom(value)) {\n Class> typeAdapterClass = (Class>) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();\n } else if (TypeAdapterFactory.class.isAssignableFrom(value)) {\n Class typeAdapterFactory = (Class) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))\n .construct()\n .create(gson, fieldType);\n } else {\n throw new IllegalArgumentException(\n \"@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.\");\n }\n typeAdapter = typeAdapter.nullSafe();\n return typeAdapter;\n }\n"}, "reference": " static TypeAdapter getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,\n TypeToken fieldType, JsonAdapter annotation) {\n Class value = annotation.value();\n TypeAdapter typeAdapter;\n if (TypeAdapter.class.isAssignableFrom(value)) {\n Class> typeAdapterClass = (Class>) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();\n } else if (TypeAdapterFactory.class.isAssignableFrom(value)) {\n Class typeAdapterFactory = (Class) value;\n typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))\n .construct()\n .create(gson, fieldType);\n } else {\n throw new IllegalArgumentException(\n \"@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.\");\n }\n if (typeAdapter != null) {\n typeAdapter = typeAdapter.nullSafe();\n }\n return typeAdapter;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-6"}} {"sample_uid": "defects4j_function_repair::Lang-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public StringBuffer format(Calendar calendar, StringBuffer buf) {\n if (mTimeZoneForced) {\n calendar = (Calendar) calendar.clone();\n calendar.setTimeZone(mTimeZone);\n }\n return applyRules(calendar, buf);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public StringBuffer format(Calendar calendar, StringBuffer buf) {\n if (mTimeZoneForced) {\n calendar = (Calendar) calendar.clone();\n calendar.setTimeZone(mTimeZone);\n }\n return applyRules(calendar, buf);\n }\n"}, "reference": " public StringBuffer format(Calendar calendar, StringBuffer buf) {\n if (mTimeZoneForced) {\n calendar.getTime(); \n calendar = (Calendar) calendar.clone();\n calendar.setTimeZone(mTimeZone);\n }\n return applyRules(calendar, buf);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-38"}} {"sample_uid": "defects4j_function_repair::Mockito-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean toStringEquals(Matcher m, Object arg) {\n return StringDescription.toString(m).equals(arg.toString());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean toStringEquals(Matcher m, Object arg) {\n return StringDescription.toString(m).equals(arg.toString());\n }\n"}, "reference": " private boolean toStringEquals(Matcher m, Object arg) {\n return StringDescription.toString(m).equals(arg == null? \"null\" : arg.toString());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-38"}} {"sample_uid": "defects4j_function_repair::JacksonXml-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void _serializeXmlNull(JsonGenerator jgen) throws IOException\n {\n if (jgen instanceof ToXmlGenerator) {\n _initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);\n }\n super.serializeValue(jgen, null);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void _serializeXmlNull(JsonGenerator jgen) throws IOException\n {\n if (jgen instanceof ToXmlGenerator) {\n _initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);\n }\n super.serializeValue(jgen, null);\n }\n"}, "reference": " protected void _serializeXmlNull(JsonGenerator jgen) throws IOException\n {\n QName rootName = _rootNameFromConfig();\n if (rootName == null) {\n rootName = ROOT_NAME_FOR_NULL;\n }\n if (jgen instanceof ToXmlGenerator) {\n _initWithRootName((ToXmlGenerator) jgen, rootName);\n }\n super.serializeValue(jgen, null);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonXml-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonXml-4"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-67", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,\n JavaType type)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n KeyDeserializer deser = null;\n if (_factoryConfig.hasKeyDeserializers()) {\n BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());\n for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {\n deser = d.findKeyDeserializer(type, config, beanDesc);\n if (deser != null) {\n break;\n }\n }\n }\n if (deser == null) {\n if (type.isEnumType()) {\n return _createEnumKeyDeserializer(ctxt, type);\n }\n deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);\n }\n if (deser != null) {\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deser = mod.modifyKeyDeserializer(config, type, deser);\n }\n }\n }\n return deser;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,\n JavaType type)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n KeyDeserializer deser = null;\n if (_factoryConfig.hasKeyDeserializers()) {\n BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());\n for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {\n deser = d.findKeyDeserializer(type, config, beanDesc);\n if (deser != null) {\n break;\n }\n }\n }\n if (deser == null) {\n if (type.isEnumType()) {\n return _createEnumKeyDeserializer(ctxt, type);\n }\n deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);\n }\n if (deser != null) {\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deser = mod.modifyKeyDeserializer(config, type, deser);\n }\n }\n }\n return deser;\n }\n"}, "reference": " public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,\n JavaType type)\n throws JsonMappingException\n {\n final DeserializationConfig config = ctxt.getConfig();\n KeyDeserializer deser = null;\n if (_factoryConfig.hasKeyDeserializers()) {\n BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());\n for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {\n deser = d.findKeyDeserializer(type, config, beanDesc);\n if (deser != null) {\n break;\n }\n }\n }\n if (deser == null) {\n if (type.isEnumType()) {\n deser = _createEnumKeyDeserializer(ctxt, type);\n } else {\n deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);\n }\n }\n if (deser != null) {\n if (_factoryConfig.hasDeserializerModifiers()) {\n for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {\n deser = mod.modifyKeyDeserializer(config, type, deser);\n }\n }\n }\n return deser;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-67"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-67"}} {"sample_uid": "defects4j_function_repair::Closure-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void traverse(Node node) {\n if (!shouldVisit(node)) {\n return;\n }\n int visits = 0;\n do {\n Node c = node.getFirstChild();\n while(c != null) {\n traverse(c);\n Node next = c.getNext();\n c = next;\n }\n visit(node);\n visits++;\n Preconditions.checkState(visits < 10000, \"too many interations\");\n } while (shouldRetraverse(node));\n exitNode(node);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void traverse(Node node) {\n if (!shouldVisit(node)) {\n return;\n }\n int visits = 0;\n do {\n Node c = node.getFirstChild();\n while(c != null) {\n traverse(c);\n Node next = c.getNext();\n c = next;\n }\n visit(node);\n visits++;\n Preconditions.checkState(visits < 10000, \"too many interations\");\n } while (shouldRetraverse(node));\n exitNode(node);\n }\n"}, "reference": " private void traverse(Node node) {\n if (!shouldVisit(node)) {\n return;\n }\n int visits = 0;\n do {\n Node c = node.getFirstChild();\n while(c != null) {\n Node next = c.getNext();\n traverse(c);\n c = next;\n }\n visit(node);\n visits++;\n Preconditions.checkState(visits < 10000, \"too many interations\");\n } while (shouldRetraverse(node));\n exitNode(node);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-13"}} {"sample_uid": "defects4j_function_repair::Csv-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void println() throws IOException {\n final String recordSeparator = format.getRecordSeparator();\n out.append(recordSeparator);\n newRecord = true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void println() throws IOException {\n final String recordSeparator = format.getRecordSeparator();\n out.append(recordSeparator);\n newRecord = true;\n }\n"}, "reference": " public void println() throws IOException {\n final String recordSeparator = format.getRecordSeparator();\n if (recordSeparator != null) {\n out.append(recordSeparator);\n }\n newRecord = true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-5"}} {"sample_uid": "defects4j_function_repair::Csv-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n > M putIn(final M map) {\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n map.put(entry.getKey(), values[col]);\n }\n return map;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " > M putIn(final M map) {\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n map.put(entry.getKey(), values[col]);\n }\n return map;\n }\n"}, "reference": " > M putIn(final M map) {\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n if (col < values.length) {\n map.put(entry.getKey(), values[col]);\n }\n }\n return map;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-6"}} {"sample_uid": "defects4j_function_repair::Chart-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public LegendItemCollection getLegendItems() {\n LegendItemCollection result = new LegendItemCollection();\n if (this.plot == null) {\n return result;\n }\n int index = this.plot.getIndexOf(this);\n CategoryDataset dataset = this.plot.getDataset(index);\n if (dataset != null) {\n return result;\n }\n int seriesCount = dataset.getRowCount();\n if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) {\n for (int i = 0; i < seriesCount; i++) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n else {\n for (int i = seriesCount - 1; i >= 0; i--) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public LegendItemCollection getLegendItems() {\n LegendItemCollection result = new LegendItemCollection();\n if (this.plot == null) {\n return result;\n }\n int index = this.plot.getIndexOf(this);\n CategoryDataset dataset = this.plot.getDataset(index);\n if (dataset != null) {\n return result;\n }\n int seriesCount = dataset.getRowCount();\n if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) {\n for (int i = 0; i < seriesCount; i++) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n else {\n for (int i = seriesCount - 1; i >= 0; i--) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n return result;\n }\n"}, "reference": " public LegendItemCollection getLegendItems() {\n LegendItemCollection result = new LegendItemCollection();\n if (this.plot == null) {\n return result;\n }\n int index = this.plot.getIndexOf(this);\n CategoryDataset dataset = this.plot.getDataset(index);\n if (dataset == null) {\n return result;\n }\n int seriesCount = dataset.getRowCount();\n if (plot.getRowRenderingOrder().equals(SortOrder.ASCENDING)) {\n for (int i = 0; i < seriesCount; i++) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n else {\n for (int i = seriesCount - 1; i >= 0; i--) {\n if (isSeriesVisibleInLegend(i)) {\n LegendItem item = getLegendItem(index, i);\n if (item != null) {\n result.add(item);\n }\n }\n }\n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-1"}} {"sample_uid": "defects4j_function_repair::Math-97", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double solve(double min, double max) throws MaxIterationsExceededException, \n FunctionEvaluationException {\n clearResult();\n verifyInterval(min, max);\n double ret = Double.NaN;\n double yMin = f.value(min);\n double yMax = f.value(max);\n double sign = yMin * yMax;\n if (sign >= 0) {\n throw new IllegalArgumentException\n (\"Function values at endpoints do not have different signs.\" +\n \" Endpoints: [\" + min + \",\" + max + \"]\" + \n \" Values: [\" + yMin + \",\" + yMax + \"]\");\n } else {\n ret = solve(min, yMin, max, yMax, min, yMin);\n }\n return ret;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double solve(double min, double max) throws MaxIterationsExceededException, \n FunctionEvaluationException {\n clearResult();\n verifyInterval(min, max);\n double ret = Double.NaN;\n double yMin = f.value(min);\n double yMax = f.value(max);\n double sign = yMin * yMax;\n if (sign >= 0) {\n throw new IllegalArgumentException\n (\"Function values at endpoints do not have different signs.\" +\n \" Endpoints: [\" + min + \",\" + max + \"]\" + \n \" Values: [\" + yMin + \",\" + yMax + \"]\");\n } else {\n ret = solve(min, yMin, max, yMax, min, yMin);\n }\n return ret;\n }\n"}, "reference": " public double solve(double min, double max) throws MaxIterationsExceededException, \n FunctionEvaluationException {\n clearResult();\n verifyInterval(min, max);\n double ret = Double.NaN;\n double yMin = f.value(min);\n double yMax = f.value(max);\n double sign = yMin * yMax;\n if (sign > 0) {\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(min, 0);\n ret = min;\n } else if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(max, 0);\n ret = max;\n } else {\n throw new IllegalArgumentException\n (\"Function values at endpoints do not have different signs.\" +\n \" Endpoints: [\" + min + \",\" + max + \"]\" + \n \" Values: [\" + yMin + \",\" + yMax + \"]\");\n }\n } else if (sign < 0){\n ret = solve(min, yMin, max, yMax, min, yMin);\n } else {\n if (yMin == 0.0) {\n ret = min;\n } else {\n ret = max;\n }\n }\n return ret;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-97"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-97"}} {"sample_uid": "defects4j_function_repair::Math-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void atan2(final double[] y, final int yOffset,\n final double[] x, final int xOffset,\n final double[] result, final int resultOffset) {\n double[] tmp1 = new double[getSize()];\n multiply(x, xOffset, x, xOffset, tmp1, 0); \n double[] tmp2 = new double[getSize()];\n multiply(y, yOffset, y, yOffset, tmp2, 0); \n add(tmp1, 0, tmp2, 0, tmp2, 0); \n rootN(tmp2, 0, 2, tmp1, 0); \n if (x[xOffset] >= 0) {\n add(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n for (int i = 0; i < tmp2.length; ++i) {\n result[resultOffset + i] = 2 * tmp2[i]; \n }\n } else {\n subtract(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n result[resultOffset] =\n ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; \n for (int i = 1; i < tmp2.length; ++i) {\n result[resultOffset + i] = -2 * tmp2[i]; \n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void atan2(final double[] y, final int yOffset,\n final double[] x, final int xOffset,\n final double[] result, final int resultOffset) {\n double[] tmp1 = new double[getSize()];\n multiply(x, xOffset, x, xOffset, tmp1, 0); \n double[] tmp2 = new double[getSize()];\n multiply(y, yOffset, y, yOffset, tmp2, 0); \n add(tmp1, 0, tmp2, 0, tmp2, 0); \n rootN(tmp2, 0, 2, tmp1, 0); \n if (x[xOffset] >= 0) {\n add(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n for (int i = 0; i < tmp2.length; ++i) {\n result[resultOffset + i] = 2 * tmp2[i]; \n }\n } else {\n subtract(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n result[resultOffset] =\n ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; \n for (int i = 1; i < tmp2.length; ++i) {\n result[resultOffset + i] = -2 * tmp2[i]; \n }\n }\n }\n"}, "reference": " public void atan2(final double[] y, final int yOffset,\n final double[] x, final int xOffset,\n final double[] result, final int resultOffset) {\n double[] tmp1 = new double[getSize()];\n multiply(x, xOffset, x, xOffset, tmp1, 0); \n double[] tmp2 = new double[getSize()];\n multiply(y, yOffset, y, yOffset, tmp2, 0); \n add(tmp1, 0, tmp2, 0, tmp2, 0); \n rootN(tmp2, 0, 2, tmp1, 0); \n if (x[xOffset] >= 0) {\n add(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n for (int i = 0; i < tmp2.length; ++i) {\n result[resultOffset + i] = 2 * tmp2[i]; \n }\n } else {\n subtract(tmp1, 0, x, xOffset, tmp2, 0); \n divide(y, yOffset, tmp2, 0, tmp1, 0); \n atan(tmp1, 0, tmp2, 0); \n result[resultOffset] =\n ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; \n for (int i = 1; i < tmp2.length; ++i) {\n result[resultOffset + i] = -2 * tmp2[i]; \n }\n }\n result[resultOffset] = FastMath.atan2(y[yOffset], x[xOffset]);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-10"}} {"sample_uid": "defects4j_function_repair::Cli-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void validate(final WriteableCommandLine commandLine)\n throws OptionException {\n int present = 0;\n Option unexpected = null;\n for (final Iterator i = options.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n boolean validate = option.isRequired() || option instanceof Group;\n if (validate) {\n option.validate(commandLine);\n }\n if (commandLine.hasOption(option)) {\n if (++present > maximum) {\n unexpected = option;\n break;\n }\n option.validate(commandLine);\n }\n }\n if (unexpected != null) {\n throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN,\n unexpected.getPreferredName());\n }\n if (present < minimum) {\n throw new OptionException(this, ResourceConstants.MISSING_OPTION);\n }\n for (final Iterator i = anonymous.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n option.validate(commandLine);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void validate(final WriteableCommandLine commandLine)\n throws OptionException {\n int present = 0;\n Option unexpected = null;\n for (final Iterator i = options.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n boolean validate = option.isRequired() || option instanceof Group;\n if (validate) {\n option.validate(commandLine);\n }\n if (commandLine.hasOption(option)) {\n if (++present > maximum) {\n unexpected = option;\n break;\n }\n option.validate(commandLine);\n }\n }\n if (unexpected != null) {\n throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN,\n unexpected.getPreferredName());\n }\n if (present < minimum) {\n throw new OptionException(this, ResourceConstants.MISSING_OPTION);\n }\n for (final Iterator i = anonymous.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n option.validate(commandLine);\n }\n }\n"}, "reference": " public void validate(final WriteableCommandLine commandLine)\n throws OptionException {\n int present = 0;\n Option unexpected = null;\n for (final Iterator i = options.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n boolean validate = option.isRequired() || option instanceof Group;\n if (commandLine.hasOption(option)) {\n if (++present > maximum) {\n unexpected = option;\n break;\n }\n validate = true;\n }\n if (validate) {\n option.validate(commandLine);\n }\n }\n if (unexpected != null) {\n throw new OptionException(this, ResourceConstants.UNEXPECTED_TOKEN,\n unexpected.getPreferredName());\n }\n if (present < minimum) {\n throw new OptionException(this, ResourceConstants.MISSING_OPTION);\n }\n for (final Iterator i = anonymous.iterator(); i.hasNext();) {\n final Option option = (Option) i.next();\n option.validate(commandLine);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-14"}} {"sample_uid": "defects4j_function_repair::JxPath-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int getLength() {\n return ValueUtils.getLength(getBaseValue());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int getLength() {\n return ValueUtils.getLength(getBaseValue());\n }\n"}, "reference": " public int getLength() {\n Object baseValue = getBaseValue();\n return baseValue == null ? 1 : ValueUtils.getLength(baseValue);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JxPath-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JxPath-21"}} {"sample_uid": "defects4j_function_repair::Jsoup-72", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {\n if (count > maxStringCacheLen)\n return new String(charBuf, start, count);\n int hash = 0;\n int offset = start;\n for (int i = 0; i < count; i++) {\n hash = 31 * hash + charBuf[offset++];\n }\n final int index = hash & stringCache.length - 1;\n String cached = stringCache[index];\n if (cached == null) { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached;\n } else { \n if (rangeEquals(charBuf, start, count, cached)) { \n return cached;\n } else { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached; \n }\n }\n return cached;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {\n if (count > maxStringCacheLen)\n return new String(charBuf, start, count);\n int hash = 0;\n int offset = start;\n for (int i = 0; i < count; i++) {\n hash = 31 * hash + charBuf[offset++];\n }\n final int index = hash & stringCache.length - 1;\n String cached = stringCache[index];\n if (cached == null) { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached;\n } else { \n if (rangeEquals(charBuf, start, count, cached)) { \n return cached;\n } else { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached; \n }\n }\n return cached;\n }\n"}, "reference": " private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {\n if (count > maxStringCacheLen)\n return new String(charBuf, start, count);\n if (count < 1)\n return \"\";\n int hash = 0;\n int offset = start;\n for (int i = 0; i < count; i++) {\n hash = 31 * hash + charBuf[offset++];\n }\n final int index = hash & stringCache.length - 1;\n String cached = stringCache[index];\n if (cached == null) { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached;\n } else { \n if (rangeEquals(charBuf, start, count, cached)) { \n return cached;\n } else { \n cached = new String(charBuf, start, count);\n stringCache[index] = cached; \n }\n }\n return cached;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-72"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-72"}} {"sample_uid": "defects4j_function_repair::Closure-48", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info,\n Node n, Node parent, Node rhsValue) {\n Node ownerNode = n.getFirstChild();\n String ownerName = ownerNode.getQualifiedName();\n String qName = n.getQualifiedName();\n String propName = n.getLastChild().getString();\n Preconditions.checkArgument(qName != null && ownerName != null);\n JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue);\n if (valueType == null && rhsValue != null) {\n valueType = rhsValue.getJSType();\n }\n if (\"prototype\".equals(propName)) {\n Var qVar = scope.getVar(qName);\n if (qVar != null) {\n ObjectType qVarType = ObjectType.cast(qVar.getType());\n if (qVarType != null &&\n rhsValue != null &&\n rhsValue.isObjectLit()) {\n typeRegistry.resetImplicitPrototype(\n rhsValue.getJSType(), qVarType.getImplicitPrototype());\n } else if (!qVar.isTypeInferred()) {\n return;\n }\n if (qVar.getScope() == scope) {\n scope.undeclare(qVar);\n }\n }\n }\n if (valueType == null) {\n if (parent.isExprResult()) {\n stubDeclarations.add(new StubDeclaration(\n n,\n t.getInput() != null && t.getInput().isExtern(),\n ownerName));\n }\n return;\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (info.isConstant() && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred) {\n inferred = !(rhsValue != null &&\n rhsValue.isFunction() &&\n (info != null || !scope.isDeclared(qName, false)));\n }\n if (!inferred) {\n ObjectType ownerType = getObjectSlot(ownerName);\n if (ownerType != null) {\n boolean isExtern = t.getInput() != null && t.getInput().isExtern();\n if ((!ownerType.hasOwnProperty(propName) ||\n ownerType.isPropertyTypeInferred(propName)) &&\n ((isExtern && !ownerType.isNativeObjectType()) ||\n !ownerType.isInstanceType())) {\n ownerType.defineDeclaredProperty(propName, valueType, n);\n }\n }\n defineSlot(n, parent, valueType, inferred);\n } else if (rhsValue != null && rhsValue.isTrue()) {\n FunctionType ownerType =\n JSType.toMaybeFunctionType(getObjectSlot(ownerName));\n if (ownerType != null) {\n JSType ownerTypeOfThis = ownerType.getTypeOfThis();\n String delegateName = codingConvention.getDelegateSuperclassName();\n JSType delegateType = delegateName == null ?\n null : typeRegistry.getType(delegateName);\n if (delegateType != null &&\n ownerTypeOfThis.isSubtype(delegateType)) {\n defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true);\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info,\n Node n, Node parent, Node rhsValue) {\n Node ownerNode = n.getFirstChild();\n String ownerName = ownerNode.getQualifiedName();\n String qName = n.getQualifiedName();\n String propName = n.getLastChild().getString();\n Preconditions.checkArgument(qName != null && ownerName != null);\n JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue);\n if (valueType == null && rhsValue != null) {\n valueType = rhsValue.getJSType();\n }\n if (\"prototype\".equals(propName)) {\n Var qVar = scope.getVar(qName);\n if (qVar != null) {\n ObjectType qVarType = ObjectType.cast(qVar.getType());\n if (qVarType != null &&\n rhsValue != null &&\n rhsValue.isObjectLit()) {\n typeRegistry.resetImplicitPrototype(\n rhsValue.getJSType(), qVarType.getImplicitPrototype());\n } else if (!qVar.isTypeInferred()) {\n return;\n }\n if (qVar.getScope() == scope) {\n scope.undeclare(qVar);\n }\n }\n }\n if (valueType == null) {\n if (parent.isExprResult()) {\n stubDeclarations.add(new StubDeclaration(\n n,\n t.getInput() != null && t.getInput().isExtern(),\n ownerName));\n }\n return;\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (info.isConstant() && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred) {\n inferred = !(rhsValue != null &&\n rhsValue.isFunction() &&\n (info != null || !scope.isDeclared(qName, false)));\n }\n if (!inferred) {\n ObjectType ownerType = getObjectSlot(ownerName);\n if (ownerType != null) {\n boolean isExtern = t.getInput() != null && t.getInput().isExtern();\n if ((!ownerType.hasOwnProperty(propName) ||\n ownerType.isPropertyTypeInferred(propName)) &&\n ((isExtern && !ownerType.isNativeObjectType()) ||\n !ownerType.isInstanceType())) {\n ownerType.defineDeclaredProperty(propName, valueType, n);\n }\n }\n defineSlot(n, parent, valueType, inferred);\n } else if (rhsValue != null && rhsValue.isTrue()) {\n FunctionType ownerType =\n JSType.toMaybeFunctionType(getObjectSlot(ownerName));\n if (ownerType != null) {\n JSType ownerTypeOfThis = ownerType.getTypeOfThis();\n String delegateName = codingConvention.getDelegateSuperclassName();\n JSType delegateType = delegateName == null ?\n null : typeRegistry.getType(delegateName);\n if (delegateType != null &&\n ownerTypeOfThis.isSubtype(delegateType)) {\n defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true);\n }\n }\n }\n }\n"}, "reference": " void maybeDeclareQualifiedName(NodeTraversal t, JSDocInfo info,\n Node n, Node parent, Node rhsValue) {\n Node ownerNode = n.getFirstChild();\n String ownerName = ownerNode.getQualifiedName();\n String qName = n.getQualifiedName();\n String propName = n.getLastChild().getString();\n Preconditions.checkArgument(qName != null && ownerName != null);\n JSType valueType = getDeclaredType(t.getSourceName(), info, n, rhsValue);\n if (valueType == null && rhsValue != null) {\n valueType = rhsValue.getJSType();\n }\n if (\"prototype\".equals(propName)) {\n Var qVar = scope.getVar(qName);\n if (qVar != null) {\n ObjectType qVarType = ObjectType.cast(qVar.getType());\n if (qVarType != null &&\n rhsValue != null &&\n rhsValue.isObjectLit()) {\n typeRegistry.resetImplicitPrototype(\n rhsValue.getJSType(), qVarType.getImplicitPrototype());\n } else if (!qVar.isTypeInferred()) {\n return;\n }\n if (qVar.getScope() == scope) {\n scope.undeclare(qVar);\n }\n }\n }\n if (valueType == null) {\n if (parent.isExprResult()) {\n stubDeclarations.add(new StubDeclaration(\n n,\n t.getInput() != null && t.getInput().isExtern(),\n ownerName));\n }\n return;\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (info.isConstant() && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred && rhsValue != null && rhsValue.isFunction()) {\n if (info != null) {\n inferred = false;\n } else if (!scope.isDeclared(qName, false) &&\n n.isUnscopedQualifiedName()) {\n inferred = false;\n }\n }\n if (!inferred) {\n ObjectType ownerType = getObjectSlot(ownerName);\n if (ownerType != null) {\n boolean isExtern = t.getInput() != null && t.getInput().isExtern();\n if ((!ownerType.hasOwnProperty(propName) ||\n ownerType.isPropertyTypeInferred(propName)) &&\n ((isExtern && !ownerType.isNativeObjectType()) ||\n !ownerType.isInstanceType())) {\n ownerType.defineDeclaredProperty(propName, valueType, n);\n }\n }\n defineSlot(n, parent, valueType, inferred);\n } else if (rhsValue != null && rhsValue.isTrue()) {\n FunctionType ownerType =\n JSType.toMaybeFunctionType(getObjectSlot(ownerName));\n if (ownerType != null) {\n JSType ownerTypeOfThis = ownerType.getTypeOfThis();\n String delegateName = codingConvention.getDelegateSuperclassName();\n JSType delegateType = delegateName == null ?\n null : typeRegistry.getType(delegateName);\n if (delegateType != null &&\n ownerTypeOfThis.isSubtype(delegateType)) {\n defineSlot(n, parent, getNativeType(BOOLEAN_TYPE), true);\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-48"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-48"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-54", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n throw new IllegalStateException(\"Problem trying to create BeanPropertyWriter for property '\"\n +propDef.getName()+\"' (of type \"+_beanDesc.getType()+\"); serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n switch (inclusion) {\n case NON_DEFAULT:\n if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {\n valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);\n } else {\n valueToSuppress = getDefaultValue(actualType);\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (declaredType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (declaredType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n throw new IllegalStateException(\"Problem trying to create BeanPropertyWriter for property '\"\n +propDef.getName()+\"' (of type \"+_beanDesc.getType()+\"); serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n switch (inclusion) {\n case NON_DEFAULT:\n if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {\n valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);\n } else {\n valueToSuppress = getDefaultValue(actualType);\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (declaredType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (declaredType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n"}, "reference": " protected BeanPropertyWriter buildWriter(SerializerProvider prov,\n BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer ser,\n TypeSerializer typeSer, TypeSerializer contentTypeSer,\n AnnotatedMember am, boolean defaultUseStaticTyping)\n throws JsonMappingException\n {\n JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);\n if (contentTypeSer != null) {\n if (serializationType == null) {\n serializationType = declaredType;\n }\n JavaType ct = serializationType.getContentType();\n if (ct == null) {\n throw new IllegalStateException(\"Problem trying to create BeanPropertyWriter for property '\"\n +propDef.getName()+\"' (of type \"+_beanDesc.getType()+\"); serialization type \"+serializationType+\" has no content\");\n }\n serializationType = serializationType.withContentTypeHandler(contentTypeSer);\n ct = serializationType.getContentType();\n }\n Object valueToSuppress = null;\n boolean suppressNulls = false;\n JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());\n JsonInclude.Include inclusion = inclV.getValueInclusion();\n if (inclusion == JsonInclude.Include.USE_DEFAULTS) { \n inclusion = JsonInclude.Include.ALWAYS;\n }\n JavaType actualType = (serializationType == null) ? declaredType : serializationType;\n switch (inclusion) {\n case NON_DEFAULT:\n if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {\n valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);\n } else {\n valueToSuppress = getDefaultValue(actualType);\n }\n if (valueToSuppress == null) {\n suppressNulls = true;\n } else {\n if (valueToSuppress.getClass().isArray()) {\n valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);\n }\n }\n break;\n case NON_ABSENT: \n suppressNulls = true;\n if (actualType.isReferenceType()) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n case NON_EMPTY:\n suppressNulls = true;\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n break;\n case NON_NULL:\n suppressNulls = true;\n case ALWAYS: \n default:\n if (actualType.isContainerType()\n && !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {\n valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;\n }\n break;\n }\n BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,\n am, _beanDesc.getClassAnnotations(), declaredType,\n ser, typeSer, serializationType, suppressNulls, valueToSuppress);\n Object serDef = _annotationIntrospector.findNullSerializer(am);\n if (serDef != null) {\n bpw.assignNullSerializer(prov.serializerInstance(am, serDef));\n }\n NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);\n if (unwrapper != null) {\n bpw = bpw.unwrappingWriter(unwrapper);\n }\n return bpw;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-54"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-54"}} {"sample_uid": "defects4j_function_repair::Lang-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void init() {\n thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);\n nameValues= new ConcurrentHashMap();\n StringBuilder regex= new StringBuilder();\n List collector = new ArrayList();\n Matcher patternMatcher= formatPattern.matcher(pattern);\n if(!patternMatcher.lookingAt()) {\n throw new IllegalArgumentException(\"Invalid pattern\");\n }\n currentFormatField= patternMatcher.group();\n Strategy currentStrategy= getStrategy(currentFormatField);\n for(;;) {\n patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());\n if(!patternMatcher.lookingAt()) {\n nextStrategy = null;\n break;\n }\n String nextFormatField= patternMatcher.group();\n nextStrategy = getStrategy(nextFormatField);\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= nextFormatField;\n currentStrategy= nextStrategy;\n }\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= null;\n strategies= collector.toArray(new Strategy[collector.size()]);\n parsePattern= Pattern.compile(regex.toString());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void init() {\n thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);\n nameValues= new ConcurrentHashMap();\n StringBuilder regex= new StringBuilder();\n List collector = new ArrayList();\n Matcher patternMatcher= formatPattern.matcher(pattern);\n if(!patternMatcher.lookingAt()) {\n throw new IllegalArgumentException(\"Invalid pattern\");\n }\n currentFormatField= patternMatcher.group();\n Strategy currentStrategy= getStrategy(currentFormatField);\n for(;;) {\n patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());\n if(!patternMatcher.lookingAt()) {\n nextStrategy = null;\n break;\n }\n String nextFormatField= patternMatcher.group();\n nextStrategy = getStrategy(nextFormatField);\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= nextFormatField;\n currentStrategy= nextStrategy;\n }\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= null;\n strategies= collector.toArray(new Strategy[collector.size()]);\n parsePattern= Pattern.compile(regex.toString());\n }\n"}, "reference": " private void init() {\n thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);\n nameValues= new ConcurrentHashMap();\n StringBuilder regex= new StringBuilder();\n List collector = new ArrayList();\n Matcher patternMatcher= formatPattern.matcher(pattern);\n if(!patternMatcher.lookingAt()) {\n throw new IllegalArgumentException(\"Invalid pattern\");\n }\n currentFormatField= patternMatcher.group();\n Strategy currentStrategy= getStrategy(currentFormatField);\n for(;;) {\n patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());\n if(!patternMatcher.lookingAt()) {\n nextStrategy = null;\n break;\n }\n String nextFormatField= patternMatcher.group();\n nextStrategy = getStrategy(nextFormatField);\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= nextFormatField;\n currentStrategy= nextStrategy;\n }\n if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {\n throw new IllegalArgumentException(\"Failed to parse \\\"\"+pattern+\"\\\" ; gave up at index \"+patternMatcher.regionStart());\n }\n if(currentStrategy.addRegex(this, regex)) {\n collector.add(currentStrategy);\n }\n currentFormatField= null;\n strategies= collector.toArray(new Strategy[collector.size()]);\n parsePattern= Pattern.compile(regex.toString());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-9"}} {"sample_uid": "defects4j_function_repair::Lang-54", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Locale toLocale(String str) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len != 2 && len != 5 && len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str, \"\");\n } else {\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch3 = str.charAt(3);\n char ch4 = str.charAt(4);\n if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n } else {\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Locale toLocale(String str) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len != 2 && len != 5 && len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str, \"\");\n } else {\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch3 = str.charAt(3);\n char ch4 = str.charAt(4);\n if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n } else {\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n }\n }\n"}, "reference": " public static Locale toLocale(String str) {\n if (str == null) {\n return null;\n }\n int len = str.length();\n if (len != 2 && len != 5 && len < 7) {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 2) {\n return new Locale(str, \"\");\n } else {\n if (str.charAt(2) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n char ch3 = str.charAt(3);\n if (ch3 == '_') {\n return new Locale(str.substring(0, 2), \"\", str.substring(4));\n }\n char ch4 = str.charAt(4);\n if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n if (len == 5) {\n return new Locale(str.substring(0, 2), str.substring(3, 5));\n } else {\n if (str.charAt(5) != '_') {\n throw new IllegalArgumentException(\"Invalid locale format: \" + str);\n }\n return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-54"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-54"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {\n String str;\n if (value instanceof Date) {\n provider.defaultSerializeDateKey((Date) value, jgen);\n return;\n } else {\n str = value.toString();\n }\n jgen.writeFieldName(str);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {\n String str;\n if (value instanceof Date) {\n provider.defaultSerializeDateKey((Date) value, jgen);\n return;\n } else {\n str = value.toString();\n }\n jgen.writeFieldName(str);\n }\n"}, "reference": " public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {\n String str;\n Class cls = value.getClass();\n if (cls == String.class) {\n str = (String) value;\n } else if (Date.class.isAssignableFrom(cls)) {\n provider.defaultSerializeDateKey((Date) value, jgen);\n return;\n } else if (cls == Class.class) {\n str = ((Class) value).getName();\n } else {\n str = value.toString();\n }\n jgen.writeFieldName(str);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-9"}} {"sample_uid": "defects4j_function_repair::Closure-107", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n if (flags.processJqueryPrimitives) {\n options.setCodingConvention(new JqueryCodingConvention());\n } else {\n options.setCodingConvention(new ClosureCodingConvention());\n }\n options.setExtraAnnotationNames(flags.extraAnnotationName);\n CompilationLevel level = flags.compilationLevel;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n if (flags.useTypesForOptimization) {\n level.setTypeBasedOptimizationOptions(options);\n }\n if (flags.generateExports) {\n options.setGenerateExports(flags.generateExports);\n }\n WarningLevel wLevel = flags.warningLevel;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n options.closurePass = flags.processClosurePrimitives;\n options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level &&\n flags.processJqueryPrimitives;\n options.angularPass = flags.angularPass;\n if (!flags.translationsFile.isEmpty()) {\n try {\n options.messageBundle = new XtbMessageBundle(\n new FileInputStream(flags.translationsFile),\n flags.translationsProject);\n } catch (IOException e) {\n throw new RuntimeException(\"Reading XTB file\", e);\n }\n } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {\n options.messageBundle = new EmptyMessageBundle();\n }\n return options;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n if (flags.processJqueryPrimitives) {\n options.setCodingConvention(new JqueryCodingConvention());\n } else {\n options.setCodingConvention(new ClosureCodingConvention());\n }\n options.setExtraAnnotationNames(flags.extraAnnotationName);\n CompilationLevel level = flags.compilationLevel;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n if (flags.useTypesForOptimization) {\n level.setTypeBasedOptimizationOptions(options);\n }\n if (flags.generateExports) {\n options.setGenerateExports(flags.generateExports);\n }\n WarningLevel wLevel = flags.warningLevel;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n options.closurePass = flags.processClosurePrimitives;\n options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level &&\n flags.processJqueryPrimitives;\n options.angularPass = flags.angularPass;\n if (!flags.translationsFile.isEmpty()) {\n try {\n options.messageBundle = new XtbMessageBundle(\n new FileInputStream(flags.translationsFile),\n flags.translationsProject);\n } catch (IOException e) {\n throw new RuntimeException(\"Reading XTB file\", e);\n }\n } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {\n options.messageBundle = new EmptyMessageBundle();\n }\n return options;\n }\n"}, "reference": " protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n if (flags.processJqueryPrimitives) {\n options.setCodingConvention(new JqueryCodingConvention());\n } else {\n options.setCodingConvention(new ClosureCodingConvention());\n }\n options.setExtraAnnotationNames(flags.extraAnnotationName);\n CompilationLevel level = flags.compilationLevel;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n if (flags.useTypesForOptimization) {\n level.setTypeBasedOptimizationOptions(options);\n }\n if (flags.generateExports) {\n options.setGenerateExports(flags.generateExports);\n }\n WarningLevel wLevel = flags.warningLevel;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n options.closurePass = flags.processClosurePrimitives;\n options.jqueryPass = CompilationLevel.ADVANCED_OPTIMIZATIONS == level &&\n flags.processJqueryPrimitives;\n options.angularPass = flags.angularPass;\n if (!flags.translationsFile.isEmpty()) {\n try {\n options.messageBundle = new XtbMessageBundle(\n new FileInputStream(flags.translationsFile),\n flags.translationsProject);\n } catch (IOException e) {\n throw new RuntimeException(\"Reading XTB file\", e);\n }\n } else if (CompilationLevel.ADVANCED_OPTIMIZATIONS == level) {\n options.messageBundle = new EmptyMessageBundle();\n options.setWarningLevel(JsMessageVisitor.MSG_CONVENTIONS, CheckLevel.OFF);\n }\n return options;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-107"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-107"}} {"sample_uid": "defects4j_function_repair::Closure-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void removeUnreferencedFunctionArgs(Scope fnScope) {\n Node function = fnScope.getRootNode();\n Preconditions.checkState(function.isFunction());\n if (NodeUtil.isGetOrSetKey(function.getParent())) {\n return;\n }\n Node argList = getFunctionArgList(function);\n boolean modifyCallers = modifyCallSites\n && callSiteOptimizer.canModifyCallers(function);\n if (!modifyCallers) {\n Node lastArg;\n while ((lastArg = argList.getLastChild()) != null) {\n Var var = fnScope.getVar(lastArg.getString());\n if (!referenced.contains(var)) {\n argList.removeChild(lastArg);\n compiler.reportCodeChange();\n } else {\n break;\n }\n }\n } else {\n callSiteOptimizer.optimize(fnScope, referenced);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void removeUnreferencedFunctionArgs(Scope fnScope) {\n Node function = fnScope.getRootNode();\n Preconditions.checkState(function.isFunction());\n if (NodeUtil.isGetOrSetKey(function.getParent())) {\n return;\n }\n Node argList = getFunctionArgList(function);\n boolean modifyCallers = modifyCallSites\n && callSiteOptimizer.canModifyCallers(function);\n if (!modifyCallers) {\n Node lastArg;\n while ((lastArg = argList.getLastChild()) != null) {\n Var var = fnScope.getVar(lastArg.getString());\n if (!referenced.contains(var)) {\n argList.removeChild(lastArg);\n compiler.reportCodeChange();\n } else {\n break;\n }\n }\n } else {\n callSiteOptimizer.optimize(fnScope, referenced);\n }\n }\n"}, "reference": " private void removeUnreferencedFunctionArgs(Scope fnScope) {\n if (!removeGlobals) {\n return;\n }\n Node function = fnScope.getRootNode();\n Preconditions.checkState(function.isFunction());\n if (NodeUtil.isGetOrSetKey(function.getParent())) {\n return;\n }\n Node argList = getFunctionArgList(function);\n boolean modifyCallers = modifyCallSites\n && callSiteOptimizer.canModifyCallers(function);\n if (!modifyCallers) {\n Node lastArg;\n while ((lastArg = argList.getLastChild()) != null) {\n Var var = fnScope.getVar(lastArg.getString());\n if (!referenced.contains(var)) {\n argList.removeChild(lastArg);\n compiler.reportCodeChange();\n } else {\n break;\n }\n }\n } else {\n callSiteOptimizer.optimize(fnScope, referenced);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-1"}} {"sample_uid": "defects4j_function_repair::Closure-120", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean isAssignedOnceInLifetime() {\n Reference ref = getOneAndOnlyAssignment();\n if (ref == null) {\n return false;\n }\n for (BasicBlock block = ref.getBasicBlock();\n block != null; block = block.getParent()) {\n if (block.isFunction) {\n break;\n } else if (block.isLoop) {\n return false;\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean isAssignedOnceInLifetime() {\n Reference ref = getOneAndOnlyAssignment();\n if (ref == null) {\n return false;\n }\n for (BasicBlock block = ref.getBasicBlock();\n block != null; block = block.getParent()) {\n if (block.isFunction) {\n break;\n } else if (block.isLoop) {\n return false;\n }\n }\n return true;\n }\n"}, "reference": " boolean isAssignedOnceInLifetime() {\n Reference ref = getOneAndOnlyAssignment();\n if (ref == null) {\n return false;\n }\n for (BasicBlock block = ref.getBasicBlock();\n block != null; block = block.getParent()) {\n if (block.isFunction) {\n if (ref.getSymbol().getScope() != ref.scope) {\n return false;\n }\n break;\n } else if (block.isLoop) {\n return false;\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-120"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-120"}} {"sample_uid": "defects4j_function_repair::Compress-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int read(byte[] buf, int offset, int numToRead) throws IOException {\n \tint totalRead = 0;\n if (hasHitEOF || entryOffset >= entrySize) {\n return -1;\n }\n if (currEntry == null) {\n throw new IllegalStateException(\"No current tar entry\");\n }\n numToRead = Math.min(numToRead, available());\n totalRead = is.read(buf, offset, numToRead);\n count(totalRead);\n if (totalRead == -1) {\n hasHitEOF = true;\n } else {\n entryOffset += totalRead;\n }\n return totalRead;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int read(byte[] buf, int offset, int numToRead) throws IOException {\n \tint totalRead = 0;\n if (hasHitEOF || entryOffset >= entrySize) {\n return -1;\n }\n if (currEntry == null) {\n throw new IllegalStateException(\"No current tar entry\");\n }\n numToRead = Math.min(numToRead, available());\n totalRead = is.read(buf, offset, numToRead);\n count(totalRead);\n if (totalRead == -1) {\n hasHitEOF = true;\n } else {\n entryOffset += totalRead;\n }\n return totalRead;\n }\n"}, "reference": " public int read(byte[] buf, int offset, int numToRead) throws IOException {\n \tint totalRead = 0;\n if (hasHitEOF || entryOffset >= entrySize) {\n return -1;\n }\n if (currEntry == null) {\n throw new IllegalStateException(\"No current tar entry\");\n }\n numToRead = Math.min(numToRead, available());\n totalRead = is.read(buf, offset, numToRead);\n if (totalRead == -1) {\n if (numToRead > 0) {\n throw new IOException(\"Truncated TAR archive\");\n }\n hasHitEOF = true;\n } else {\n count(totalRead);\n entryOffset += totalRead;\n }\n return totalRead;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-28"}} {"sample_uid": "defects4j_function_repair::Math-102", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double chiSquare(double[] expected, long[] observed)\n throws IllegalArgumentException {\n if ((expected.length < 2) || (expected.length != observed.length)) {\n throw new IllegalArgumentException(\n \"observed, expected array lengths incorrect\");\n }\n if (!isPositive(expected) || !isNonNegative(observed)) {\n throw new IllegalArgumentException(\n \"observed counts must be non-negative and expected counts must be postive\");\n }\n double sumSq = 0.0d;\n double dev = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n dev = ((double) observed[i] - expected[i]);\n sumSq += dev * dev / expected[i];\n }\n return sumSq;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double chiSquare(double[] expected, long[] observed)\n throws IllegalArgumentException {\n if ((expected.length < 2) || (expected.length != observed.length)) {\n throw new IllegalArgumentException(\n \"observed, expected array lengths incorrect\");\n }\n if (!isPositive(expected) || !isNonNegative(observed)) {\n throw new IllegalArgumentException(\n \"observed counts must be non-negative and expected counts must be postive\");\n }\n double sumSq = 0.0d;\n double dev = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n dev = ((double) observed[i] - expected[i]);\n sumSq += dev * dev / expected[i];\n }\n return sumSq;\n }\n"}, "reference": " public double chiSquare(double[] expected, long[] observed)\n throws IllegalArgumentException {\n if ((expected.length < 2) || (expected.length != observed.length)) {\n throw new IllegalArgumentException(\n \"observed, expected array lengths incorrect\");\n }\n if (!isPositive(expected) || !isNonNegative(observed)) {\n throw new IllegalArgumentException(\n \"observed counts must be non-negative and expected counts must be postive\");\n }\n double sumExpected = 0d;\n double sumObserved = 0d;\n for (int i = 0; i < observed.length; i++) {\n sumExpected += expected[i];\n sumObserved += observed[i];\n }\n double ratio = 1.0d;\n boolean rescale = false;\n if (Math.abs(sumExpected - sumObserved) > 10E-6) {\n ratio = sumObserved / sumExpected;\n rescale = true;\n }\n double sumSq = 0.0d;\n double dev = 0.0d;\n for (int i = 0; i < observed.length; i++) {\n if (rescale) {\n dev = ((double) observed[i] - ratio * expected[i]);\n sumSq += dev * dev / (ratio * expected[i]);\n } else {\n dev = ((double) observed[i] - expected[i]);\n sumSq += dev * dev / expected[i];\n }\n }\n return sumSq;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-102"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-102"}} {"sample_uid": "defects4j_function_repair::Closure-82", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public final boolean isEmptyType() {\n return isNoType() || isNoObjectType() || isNoResolvedType();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public final boolean isEmptyType() {\n return isNoType() || isNoObjectType() || isNoResolvedType();\n }\n"}, "reference": " public final boolean isEmptyType() {\n return isNoType() || isNoObjectType() || isNoResolvedType() ||\n (registry.getNativeFunctionType(\n JSTypeNative.LEAST_FUNCTION_TYPE) == this);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-82"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-82"}} {"sample_uid": "defects4j_function_repair::Lang-42", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void escape(Writer writer, String str) throws IOException {\n int len = str.length();\n for (int i = 0; i < len; i++) {\n char c = str.charAt(i);\n String entityName = this.entityName(c);\n if (entityName == null) {\n if (c > 0x7F) {\n writer.write(\"&#\");\n writer.write(Integer.toString(c, 10));\n writer.write(';');\n } else {\n writer.write(c);\n }\n } else {\n writer.write('&');\n writer.write(entityName);\n writer.write(';');\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void escape(Writer writer, String str) throws IOException {\n int len = str.length();\n for (int i = 0; i < len; i++) {\n char c = str.charAt(i);\n String entityName = this.entityName(c);\n if (entityName == null) {\n if (c > 0x7F) {\n writer.write(\"&#\");\n writer.write(Integer.toString(c, 10));\n writer.write(';');\n } else {\n writer.write(c);\n }\n } else {\n writer.write('&');\n writer.write(entityName);\n writer.write(';');\n }\n }\n }\n"}, "reference": " public void escape(Writer writer, String str) throws IOException {\n int len = str.length();\n for (int i = 0; i < len; i++) {\n int c = Character.codePointAt(str, i); \n String entityName = this.entityName(c);\n if (entityName == null) {\n if (c >= 0x010000 && i < len - 1) {\n writer.write(\"&#\");\n writer.write(Integer.toString(c, 10));\n writer.write(';');\n i++;\n } else if (c > 0x7F) { \n writer.write(\"&#\");\n writer.write(Integer.toString(c, 10));\n writer.write(';');\n } else {\n writer.write(c);\n }\n } else {\n writer.write('&');\n writer.write(entityName);\n writer.write(';');\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-42"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-42"}} {"sample_uid": "defects4j_function_repair::Lang-61", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int indexOf(String str, int startIndex) {\n startIndex = (startIndex < 0 ? 0 : startIndex);\n if (str == null || startIndex >= size) {\n return -1;\n }\n int strLen = str.length();\n if (strLen == 1) {\n return indexOf(str.charAt(0), startIndex);\n }\n if (strLen == 0) {\n return startIndex;\n }\n if (strLen > size) {\n return -1;\n }\n char[] thisBuf = buffer;\n int len = thisBuf.length - strLen;\n outer:\n for (int i = startIndex; i < len; i++) {\n for (int j = 0; j < strLen; j++) {\n if (str.charAt(j) != thisBuf[i + j]) {\n continue outer;\n }\n }\n return i;\n }\n return -1;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int indexOf(String str, int startIndex) {\n startIndex = (startIndex < 0 ? 0 : startIndex);\n if (str == null || startIndex >= size) {\n return -1;\n }\n int strLen = str.length();\n if (strLen == 1) {\n return indexOf(str.charAt(0), startIndex);\n }\n if (strLen == 0) {\n return startIndex;\n }\n if (strLen > size) {\n return -1;\n }\n char[] thisBuf = buffer;\n int len = thisBuf.length - strLen;\n outer:\n for (int i = startIndex; i < len; i++) {\n for (int j = 0; j < strLen; j++) {\n if (str.charAt(j) != thisBuf[i + j]) {\n continue outer;\n }\n }\n return i;\n }\n return -1;\n }\n"}, "reference": " public int indexOf(String str, int startIndex) {\n startIndex = (startIndex < 0 ? 0 : startIndex);\n if (str == null || startIndex >= size) {\n return -1;\n }\n int strLen = str.length();\n if (strLen == 1) {\n return indexOf(str.charAt(0), startIndex);\n }\n if (strLen == 0) {\n return startIndex;\n }\n if (strLen > size) {\n return -1;\n }\n char[] thisBuf = buffer;\n int len = size - strLen + 1;\n outer:\n for (int i = startIndex; i < len; i++) {\n for (int j = 0; j < strLen; j++) {\n if (str.charAt(j) != thisBuf[i + j]) {\n continue outer;\n }\n }\n return i;\n }\n return -1;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-61"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-61"}} {"sample_uid": "defects4j_function_repair::Closure-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void matchConstraint(ObjectType constraintObj) {\n if (constraintObj.isRecordType()) {\n for (String prop : constraintObj.getOwnPropertyNames()) {\n JSType propType = constraintObj.getPropertyType(prop);\n if (!isPropertyTypeDeclared(prop)) {\n JSType typeToInfer = propType;\n if (!hasProperty(prop)) {\n typeToInfer = getNativeType(JSTypeNative.VOID_TYPE)\n .getLeastSupertype(propType);\n }\n defineInferredProperty(prop, typeToInfer, null);\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void matchConstraint(ObjectType constraintObj) {\n if (constraintObj.isRecordType()) {\n for (String prop : constraintObj.getOwnPropertyNames()) {\n JSType propType = constraintObj.getPropertyType(prop);\n if (!isPropertyTypeDeclared(prop)) {\n JSType typeToInfer = propType;\n if (!hasProperty(prop)) {\n typeToInfer = getNativeType(JSTypeNative.VOID_TYPE)\n .getLeastSupertype(propType);\n }\n defineInferredProperty(prop, typeToInfer, null);\n }\n }\n }\n }\n"}, "reference": " public void matchConstraint(ObjectType constraintObj) {\n if (hasReferenceName()) {\n return;\n }\n if (constraintObj.isRecordType()) {\n for (String prop : constraintObj.getOwnPropertyNames()) {\n JSType propType = constraintObj.getPropertyType(prop);\n if (!isPropertyTypeDeclared(prop)) {\n JSType typeToInfer = propType;\n if (!hasProperty(prop)) {\n typeToInfer = getNativeType(JSTypeNative.VOID_TYPE)\n .getLeastSupertype(propType);\n }\n defineInferredProperty(prop, typeToInfer, null);\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-33"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-102", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property == null) {\n return this;\n }\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.hasPattern()) {\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);\n TimeZone tz = format.hasTimeZone() ? format.getTimeZone()\n : serializers.getTimeZone();\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n final boolean hasLocale = format.hasLocale();\n final boolean hasTZ = format.hasTimeZone();\n final boolean asString = (shape == JsonFormat.Shape.STRING);\n if (!hasLocale && !hasTZ && !asString) {\n return this;\n }\n DateFormat df0 = serializers.getConfig().getDateFormat();\n if (df0 instanceof StdDateFormat) {\n StdDateFormat std = (StdDateFormat) df0;\n if (format.hasLocale()) {\n std = std.withLocale(format.getLocale());\n }\n if (format.hasTimeZone()) {\n std = std.withTimeZone(format.getTimeZone());\n }\n return withFormat(Boolean.FALSE, std);\n }\n if (!(df0 instanceof SimpleDateFormat)) {\n serializers.reportBadDefinition(handledType(), String.format(\n\"Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`\",\ndf0.getClass().getName()));\n }\n SimpleDateFormat df = (SimpleDateFormat) df0;\n if (hasLocale) {\n df = new SimpleDateFormat(df.toPattern(), format.getLocale());\n } else {\n df = (SimpleDateFormat) df.clone();\n }\n TimeZone newTz = format.getTimeZone();\n boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());\n if (changeTZ) {\n df.setTimeZone(newTz);\n }\n return withFormat(Boolean.FALSE, df);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property == null) {\n return this;\n }\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.hasPattern()) {\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);\n TimeZone tz = format.hasTimeZone() ? format.getTimeZone()\n : serializers.getTimeZone();\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n final boolean hasLocale = format.hasLocale();\n final boolean hasTZ = format.hasTimeZone();\n final boolean asString = (shape == JsonFormat.Shape.STRING);\n if (!hasLocale && !hasTZ && !asString) {\n return this;\n }\n DateFormat df0 = serializers.getConfig().getDateFormat();\n if (df0 instanceof StdDateFormat) {\n StdDateFormat std = (StdDateFormat) df0;\n if (format.hasLocale()) {\n std = std.withLocale(format.getLocale());\n }\n if (format.hasTimeZone()) {\n std = std.withTimeZone(format.getTimeZone());\n }\n return withFormat(Boolean.FALSE, std);\n }\n if (!(df0 instanceof SimpleDateFormat)) {\n serializers.reportBadDefinition(handledType(), String.format(\n\"Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`\",\ndf0.getClass().getName()));\n }\n SimpleDateFormat df = (SimpleDateFormat) df0;\n if (hasLocale) {\n df = new SimpleDateFormat(df.toPattern(), format.getLocale());\n } else {\n df = (SimpleDateFormat) df.clone();\n }\n TimeZone newTz = format.getTimeZone();\n boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());\n if (changeTZ) {\n df.setTimeZone(newTz);\n }\n return withFormat(Boolean.FALSE, df);\n }\n"}, "reference": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.hasPattern()) {\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);\n TimeZone tz = format.hasTimeZone() ? format.getTimeZone()\n : serializers.getTimeZone();\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n final boolean hasLocale = format.hasLocale();\n final boolean hasTZ = format.hasTimeZone();\n final boolean asString = (shape == JsonFormat.Shape.STRING);\n if (!hasLocale && !hasTZ && !asString) {\n return this;\n }\n DateFormat df0 = serializers.getConfig().getDateFormat();\n if (df0 instanceof StdDateFormat) {\n StdDateFormat std = (StdDateFormat) df0;\n if (format.hasLocale()) {\n std = std.withLocale(format.getLocale());\n }\n if (format.hasTimeZone()) {\n std = std.withTimeZone(format.getTimeZone());\n }\n return withFormat(Boolean.FALSE, std);\n }\n if (!(df0 instanceof SimpleDateFormat)) {\n serializers.reportBadDefinition(handledType(), String.format(\n\"Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`\",\ndf0.getClass().getName()));\n }\n SimpleDateFormat df = (SimpleDateFormat) df0;\n if (hasLocale) {\n df = new SimpleDateFormat(df.toPattern(), format.getLocale());\n } else {\n df = (SimpleDateFormat) df.clone();\n }\n TimeZone newTz = format.getTimeZone();\n boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());\n if (changeTZ) {\n df.setTimeZone(newTz);\n }\n return withFormat(Boolean.FALSE, df);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-102"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-102"}} {"sample_uid": "defects4j_function_repair::Compress-36", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private InputStream getCurrentStream() throws IOException {\n if (deferredBlockStreams.isEmpty()) {\n throw new IllegalStateException(\"No current 7z entry (call getNextEntry() first).\");\n }\n while (deferredBlockStreams.size() > 1) {\n final InputStream stream = deferredBlockStreams.remove(0);\n IOUtils.skip(stream, Long.MAX_VALUE);\n stream.close();\n }\n return deferredBlockStreams.get(0);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private InputStream getCurrentStream() throws IOException {\n if (deferredBlockStreams.isEmpty()) {\n throw new IllegalStateException(\"No current 7z entry (call getNextEntry() first).\");\n }\n while (deferredBlockStreams.size() > 1) {\n final InputStream stream = deferredBlockStreams.remove(0);\n IOUtils.skip(stream, Long.MAX_VALUE);\n stream.close();\n }\n return deferredBlockStreams.get(0);\n }\n"}, "reference": " private InputStream getCurrentStream() throws IOException {\n if (archive.files[currentEntryIndex].getSize() == 0) {\n return new ByteArrayInputStream(new byte[0]);\n }\n if (deferredBlockStreams.isEmpty()) {\n throw new IllegalStateException(\"No current 7z entry (call getNextEntry() first).\");\n }\n while (deferredBlockStreams.size() > 1) {\n final InputStream stream = deferredBlockStreams.remove(0);\n IOUtils.skip(stream, Long.MAX_VALUE);\n stream.close();\n }\n return deferredBlockStreams.get(0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-36"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-36"}} {"sample_uid": "defects4j_function_repair::Chart-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public TimeSeries createCopy(int start, int end)\n throws CloneNotSupportedException {\n if (start < 0) {\n throw new IllegalArgumentException(\"Requires start >= 0.\");\n }\n if (end < start) {\n throw new IllegalArgumentException(\"Requires start <= end.\");\n }\n TimeSeries copy = (TimeSeries) super.clone();\n copy.data = new java.util.ArrayList();\n if (this.data.size() > 0) {\n for (int index = start; index <= end; index++) {\n TimeSeriesDataItem item\n = (TimeSeriesDataItem) this.data.get(index);\n TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone();\n try {\n copy.add(clone);\n }\n catch (SeriesException e) {\n e.printStackTrace();\n }\n }\n }\n return copy;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public TimeSeries createCopy(int start, int end)\n throws CloneNotSupportedException {\n if (start < 0) {\n throw new IllegalArgumentException(\"Requires start >= 0.\");\n }\n if (end < start) {\n throw new IllegalArgumentException(\"Requires start <= end.\");\n }\n TimeSeries copy = (TimeSeries) super.clone();\n copy.data = new java.util.ArrayList();\n if (this.data.size() > 0) {\n for (int index = start; index <= end; index++) {\n TimeSeriesDataItem item\n = (TimeSeriesDataItem) this.data.get(index);\n TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone();\n try {\n copy.add(clone);\n }\n catch (SeriesException e) {\n e.printStackTrace();\n }\n }\n }\n return copy;\n }\n"}, "reference": " public TimeSeries createCopy(int start, int end)\n throws CloneNotSupportedException {\n if (start < 0) {\n throw new IllegalArgumentException(\"Requires start >= 0.\");\n }\n if (end < start) {\n throw new IllegalArgumentException(\"Requires start <= end.\");\n }\n TimeSeries copy = (TimeSeries) super.clone();\n copy.minY = Double.NaN;\n copy.maxY = Double.NaN;\n copy.data = new java.util.ArrayList();\n if (this.data.size() > 0) {\n for (int index = start; index <= end; index++) {\n TimeSeriesDataItem item\n = (TimeSeriesDataItem) this.data.get(index);\n TimeSeriesDataItem clone = (TimeSeriesDataItem) item.clone();\n try {\n copy.add(clone);\n }\n catch (SeriesException e) {\n e.printStackTrace();\n }\n }\n }\n return copy;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-3"}} {"sample_uid": "defects4j_function_repair::Cli-37", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isShortOption(String token)\n {\n return token.startsWith(\"-\") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isShortOption(String token)\n {\n return token.startsWith(\"-\") && token.length() >= 2 && options.hasShortOption(token.substring(1, 2));\n }\n"}, "reference": " private boolean isShortOption(String token)\n {\n if (!token.startsWith(\"-\") || token.length() == 1)\n {\n return false;\n }\n int pos = token.indexOf(\"=\");\n String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);\n return options.hasShortOption(optName);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-37"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-37"}} {"sample_uid": "defects4j_function_repair::Math-44", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MathIllegalStateException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n resetOccurred = false;\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState();\n currentEvent.stepAccepted(eventT, eventY);\n isLastStep = currentEvent.stop();\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n return eventT;\n }\n if (currentEvent.reset(eventT, eventY)) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MathIllegalStateException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n resetOccurred = false;\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState();\n currentEvent.stepAccepted(eventT, eventY);\n isLastStep = currentEvent.stop();\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n return eventT;\n }\n if (currentEvent.reset(eventT, eventY)) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n"}, "reference": " protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MathIllegalStateException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState();\n currentEvent.stepAccepted(eventT, eventY);\n isLastStep = currentEvent.stop();\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n if (currentEvent.reset(eventT, eventY)) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-44"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-44"}} {"sample_uid": "defects4j_function_repair::Csv-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n > M putIn(final M map) {\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n if (col < values.length) {\n map.put(entry.getKey(), values[col]);\n }\n }\n return map;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " > M putIn(final M map) {\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n if (col < values.length) {\n map.put(entry.getKey(), values[col]);\n }\n }\n return map;\n }\n"}, "reference": " > M putIn(final M map) {\n if (mapping == null) {\n return map;\n }\n for (final Entry entry : mapping.entrySet()) {\n final int col = entry.getValue().intValue();\n if (col < values.length) {\n map.put(entry.getKey(), values[col]);\n }\n }\n return map;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-9"}} {"sample_uid": "defects4j_function_repair::Closure-170", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void getNumUseInUseCfgNode(final Node cfgNode) {\n numUsesWithinCfgNode = 0;\n AbstractCfgNodeTraversalCallback gatherCb =\n new AbstractCfgNodeTraversalCallback() {\n @Override\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isName() && n.getString().equals(varName) &&\n !(parent.isAssign() &&\n (parent.getFirstChild() == n))) {\n numUsesWithinCfgNode++;\n }\n }\n };\n NodeTraversal.traverse(compiler, cfgNode, gatherCb);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void getNumUseInUseCfgNode(final Node cfgNode) {\n numUsesWithinCfgNode = 0;\n AbstractCfgNodeTraversalCallback gatherCb =\n new AbstractCfgNodeTraversalCallback() {\n @Override\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isName() && n.getString().equals(varName) &&\n !(parent.isAssign() &&\n (parent.getFirstChild() == n))) {\n numUsesWithinCfgNode++;\n }\n }\n };\n NodeTraversal.traverse(compiler, cfgNode, gatherCb);\n }\n"}, "reference": " private void getNumUseInUseCfgNode(final Node cfgNode) {\n numUsesWithinCfgNode = 0;\n AbstractCfgNodeTraversalCallback gatherCb =\n new AbstractCfgNodeTraversalCallback() {\n @Override\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isName() && n.getString().equals(varName)) {\n if (parent.isAssign() && (parent.getFirstChild() == n)\n && isAssignChain(parent, cfgNode)) {\n return;\n } else {\n numUsesWithinCfgNode++;\n }\n }\n }\n private boolean isAssignChain(Node child, Node ancestor) {\n for (Node n = child; n != ancestor; n = n.getParent()) {\n if (!n.isAssign()) {\n return false;\n }\n }\n return true;\n }\n };\n NodeTraversal.traverse(compiler, cfgNode, gatherCb);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-170"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-170"}} {"sample_uid": "defects4j_function_repair::Lang-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected List parsePattern() {\n DateFormatSymbols symbols = new DateFormatSymbols(mLocale);\n List rules = new ArrayList();\n String[] ERAs = symbols.getEras();\n String[] months = symbols.getMonths();\n String[] shortMonths = symbols.getShortMonths();\n String[] weekdays = symbols.getWeekdays();\n String[] shortWeekdays = symbols.getShortWeekdays();\n String[] AmPmStrings = symbols.getAmPmStrings();\n int length = mPattern.length();\n int[] indexRef = new int[1];\n for (int i = 0; i < length; i++) {\n indexRef[0] = i;\n String token = parseToken(mPattern, indexRef);\n i = indexRef[0];\n int tokenLen = token.length();\n if (tokenLen == 0) {\n break;\n }\n Rule rule;\n char c = token.charAt(0);\n switch (c) {\n case 'G': \n rule = new TextField(Calendar.ERA, ERAs);\n break;\n case 'y': \n if (tokenLen >= 4) {\n rule = selectNumberRule(Calendar.YEAR, tokenLen);\n } else {\n rule = TwoDigitYearField.INSTANCE;\n }\n break;\n case 'M': \n if (tokenLen >= 4) {\n rule = new TextField(Calendar.MONTH, months);\n } else if (tokenLen == 3) {\n rule = new TextField(Calendar.MONTH, shortMonths);\n } else if (tokenLen == 2) {\n rule = TwoDigitMonthField.INSTANCE;\n } else {\n rule = UnpaddedMonthField.INSTANCE;\n }\n break;\n case 'd': \n rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);\n break;\n case 'h': \n rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));\n break;\n case 'H': \n rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);\n break;\n case 'm': \n rule = selectNumberRule(Calendar.MINUTE, tokenLen);\n break;\n case 's': \n rule = selectNumberRule(Calendar.SECOND, tokenLen);\n break;\n case 'S': \n rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);\n break;\n case 'E': \n rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);\n break;\n case 'D': \n rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);\n break;\n case 'F': \n rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);\n break;\n case 'w': \n rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);\n break;\n case 'W': \n rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);\n break;\n case 'a': \n rule = new TextField(Calendar.AM_PM, AmPmStrings);\n break;\n case 'k': \n rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));\n break;\n case 'K': \n rule = selectNumberRule(Calendar.HOUR, tokenLen);\n break;\n case 'z': \n if (tokenLen >= 4) {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);\n } else {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);\n }\n break;\n case 'Z': \n if (tokenLen == 1) {\n rule = TimeZoneNumberRule.INSTANCE_NO_COLON;\n } else {\n rule = TimeZoneNumberRule.INSTANCE_COLON;\n }\n break;\n case '\\'': \n String sub = token.substring(1);\n if (sub.length() == 1) {\n rule = new CharacterLiteral(sub.charAt(0));\n } else {\n rule = new StringLiteral(sub);\n }\n break;\n default:\n throw new IllegalArgumentException(\"Illegal pattern component: \" + token);\n }\n rules.add(rule);\n }\n return rules;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected List parsePattern() {\n DateFormatSymbols symbols = new DateFormatSymbols(mLocale);\n List rules = new ArrayList();\n String[] ERAs = symbols.getEras();\n String[] months = symbols.getMonths();\n String[] shortMonths = symbols.getShortMonths();\n String[] weekdays = symbols.getWeekdays();\n String[] shortWeekdays = symbols.getShortWeekdays();\n String[] AmPmStrings = symbols.getAmPmStrings();\n int length = mPattern.length();\n int[] indexRef = new int[1];\n for (int i = 0; i < length; i++) {\n indexRef[0] = i;\n String token = parseToken(mPattern, indexRef);\n i = indexRef[0];\n int tokenLen = token.length();\n if (tokenLen == 0) {\n break;\n }\n Rule rule;\n char c = token.charAt(0);\n switch (c) {\n case 'G': \n rule = new TextField(Calendar.ERA, ERAs);\n break;\n case 'y': \n if (tokenLen >= 4) {\n rule = selectNumberRule(Calendar.YEAR, tokenLen);\n } else {\n rule = TwoDigitYearField.INSTANCE;\n }\n break;\n case 'M': \n if (tokenLen >= 4) {\n rule = new TextField(Calendar.MONTH, months);\n } else if (tokenLen == 3) {\n rule = new TextField(Calendar.MONTH, shortMonths);\n } else if (tokenLen == 2) {\n rule = TwoDigitMonthField.INSTANCE;\n } else {\n rule = UnpaddedMonthField.INSTANCE;\n }\n break;\n case 'd': \n rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);\n break;\n case 'h': \n rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));\n break;\n case 'H': \n rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);\n break;\n case 'm': \n rule = selectNumberRule(Calendar.MINUTE, tokenLen);\n break;\n case 's': \n rule = selectNumberRule(Calendar.SECOND, tokenLen);\n break;\n case 'S': \n rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);\n break;\n case 'E': \n rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);\n break;\n case 'D': \n rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);\n break;\n case 'F': \n rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);\n break;\n case 'w': \n rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);\n break;\n case 'W': \n rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);\n break;\n case 'a': \n rule = new TextField(Calendar.AM_PM, AmPmStrings);\n break;\n case 'k': \n rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));\n break;\n case 'K': \n rule = selectNumberRule(Calendar.HOUR, tokenLen);\n break;\n case 'z': \n if (tokenLen >= 4) {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);\n } else {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);\n }\n break;\n case 'Z': \n if (tokenLen == 1) {\n rule = TimeZoneNumberRule.INSTANCE_NO_COLON;\n } else {\n rule = TimeZoneNumberRule.INSTANCE_COLON;\n }\n break;\n case '\\'': \n String sub = token.substring(1);\n if (sub.length() == 1) {\n rule = new CharacterLiteral(sub.charAt(0));\n } else {\n rule = new StringLiteral(sub);\n }\n break;\n default:\n throw new IllegalArgumentException(\"Illegal pattern component: \" + token);\n }\n rules.add(rule);\n }\n return rules;\n }\n"}, "reference": " protected List parsePattern() {\n DateFormatSymbols symbols = new DateFormatSymbols(mLocale);\n List rules = new ArrayList();\n String[] ERAs = symbols.getEras();\n String[] months = symbols.getMonths();\n String[] shortMonths = symbols.getShortMonths();\n String[] weekdays = symbols.getWeekdays();\n String[] shortWeekdays = symbols.getShortWeekdays();\n String[] AmPmStrings = symbols.getAmPmStrings();\n int length = mPattern.length();\n int[] indexRef = new int[1];\n for (int i = 0; i < length; i++) {\n indexRef[0] = i;\n String token = parseToken(mPattern, indexRef);\n i = indexRef[0];\n int tokenLen = token.length();\n if (tokenLen == 0) {\n break;\n }\n Rule rule;\n char c = token.charAt(0);\n switch (c) {\n case 'G': \n rule = new TextField(Calendar.ERA, ERAs);\n break;\n case 'y': \n if (tokenLen == 2) {\n rule = TwoDigitYearField.INSTANCE;\n } else {\n rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);\n }\n break;\n case 'M': \n if (tokenLen >= 4) {\n rule = new TextField(Calendar.MONTH, months);\n } else if (tokenLen == 3) {\n rule = new TextField(Calendar.MONTH, shortMonths);\n } else if (tokenLen == 2) {\n rule = TwoDigitMonthField.INSTANCE;\n } else {\n rule = UnpaddedMonthField.INSTANCE;\n }\n break;\n case 'd': \n rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);\n break;\n case 'h': \n rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));\n break;\n case 'H': \n rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);\n break;\n case 'm': \n rule = selectNumberRule(Calendar.MINUTE, tokenLen);\n break;\n case 's': \n rule = selectNumberRule(Calendar.SECOND, tokenLen);\n break;\n case 'S': \n rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);\n break;\n case 'E': \n rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);\n break;\n case 'D': \n rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);\n break;\n case 'F': \n rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);\n break;\n case 'w': \n rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);\n break;\n case 'W': \n rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);\n break;\n case 'a': \n rule = new TextField(Calendar.AM_PM, AmPmStrings);\n break;\n case 'k': \n rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));\n break;\n case 'K': \n rule = selectNumberRule(Calendar.HOUR, tokenLen);\n break;\n case 'z': \n if (tokenLen >= 4) {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);\n } else {\n rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);\n }\n break;\n case 'Z': \n if (tokenLen == 1) {\n rule = TimeZoneNumberRule.INSTANCE_NO_COLON;\n } else {\n rule = TimeZoneNumberRule.INSTANCE_COLON;\n }\n break;\n case '\\'': \n String sub = token.substring(1);\n if (sub.length() == 1) {\n rule = new CharacterLiteral(sub.charAt(0));\n } else {\n rule = new StringLiteral(sub);\n }\n break;\n default:\n throw new IllegalArgumentException(\"Illegal pattern component: \" + token);\n }\n rules.add(rule);\n }\n return rules;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-18"}} {"sample_uid": "defects4j_function_repair::Closure-115", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n boolean hasSideEffects = false;\n if (block.hasChildren()) {\n Preconditions.checkState(block.hasOneChild());\n Node stmt = block.getFirstChild();\n if (stmt.isReturn()) {\n hasSideEffects = NodeUtil.mayHaveSideEffects(stmt.getFirstChild(), compiler);\n }\n }\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) {\n return CanInlineResult.NO;\n }\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n boolean hasSideEffects = false;\n if (block.hasChildren()) {\n Preconditions.checkState(block.hasOneChild());\n Node stmt = block.getFirstChild();\n if (stmt.isReturn()) {\n hasSideEffects = NodeUtil.mayHaveSideEffects(stmt.getFirstChild(), compiler);\n }\n }\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (hasSideEffects && NodeUtil.canBeSideEffected(cArg)) {\n return CanInlineResult.NO;\n }\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n"}, "reference": " private CanInlineResult canInlineReferenceDirectly(\n Node callNode, Node fnNode) {\n if (!isDirectCallNodeReplacementPossible(fnNode)) {\n return CanInlineResult.NO;\n }\n Node block = fnNode.getLastChild();\n Node cArg = callNode.getFirstChild().getNext();\n if (!callNode.getFirstChild().isName()) {\n if (NodeUtil.isFunctionObjectCall(callNode)) {\n if (cArg == null || !cArg.isThis()) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n } else {\n Preconditions.checkState(!NodeUtil.isFunctionObjectApply(callNode));\n }\n }\n Node fnParam = NodeUtil.getFunctionParameters(fnNode).getFirstChild();\n while (cArg != null || fnParam != null) {\n if (fnParam != null) {\n if (cArg != null) {\n if (NodeUtil.mayEffectMutableState(cArg, compiler)\n && NodeUtil.getNameReferenceCount(\n block, fnParam.getString()) > 1) {\n return CanInlineResult.NO;\n }\n }\n fnParam = fnParam.getNext();\n }\n if (cArg != null) {\n if (NodeUtil.mayHaveSideEffects(cArg, compiler)) {\n return CanInlineResult.NO;\n }\n cArg = cArg.getNext();\n }\n }\n return CanInlineResult.YES;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-115"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-115"}} {"sample_uid": "defects4j_function_repair::Closure-159", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void findCalledFunctions(\n Node node, Set changed) {\n Preconditions.checkArgument(changed != null);\n if (node.getType() == Token.CALL) {\n Node child = node.getFirstChild();\n if (child.getType() == Token.NAME) {\n changed.add(child.getString());\n }\n }\n for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {\n findCalledFunctions(c, changed);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void findCalledFunctions(\n Node node, Set changed) {\n Preconditions.checkArgument(changed != null);\n if (node.getType() == Token.CALL) {\n Node child = node.getFirstChild();\n if (child.getType() == Token.NAME) {\n changed.add(child.getString());\n }\n }\n for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {\n findCalledFunctions(c, changed);\n }\n }\n"}, "reference": " private void findCalledFunctions(\n Node node, Set changed) {\n Preconditions.checkArgument(changed != null);\n if (node.getType() == Token.NAME) {\n if (isCandidateUsage(node)) {\n changed.add(node.getString());\n }\n }\n for (Node c = node.getFirstChild(); c != null; c = c.getNext()) {\n findCalledFunctions(c, changed);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-159"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-159"}} {"sample_uid": "defects4j_function_repair::Chart-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void updateBounds(TimePeriod period, int index) {\n long start = period.getStart().getTime();\n long end = period.getEnd().getTime();\n long middle = start + ((end - start) / 2);\n if (this.minStartIndex >= 0) {\n long minStart = getDataItem(this.minStartIndex).getPeriod()\n .getStart().getTime();\n if (start < minStart) {\n this.minStartIndex = index; \n }\n }\n else {\n this.minStartIndex = index;\n }\n if (this.maxStartIndex >= 0) {\n long maxStart = getDataItem(this.maxStartIndex).getPeriod()\n .getStart().getTime();\n if (start > maxStart) {\n this.maxStartIndex = index; \n }\n }\n else {\n this.maxStartIndex = index;\n }\n if (this.minMiddleIndex >= 0) {\n long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()\n .getTime();\n long minMiddle = s + (e - s) / 2;\n if (middle < minMiddle) {\n this.minMiddleIndex = index; \n }\n }\n else {\n this.minMiddleIndex = index;\n }\n if (this.maxMiddleIndex >= 0) {\n long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()\n .getTime();\n long maxMiddle = s + (e - s) / 2;\n if (middle > maxMiddle) {\n this.maxMiddleIndex = index; \n }\n }\n else {\n this.maxMiddleIndex = index;\n }\n if (this.minEndIndex >= 0) {\n long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd()\n .getTime();\n if (end < minEnd) {\n this.minEndIndex = index; \n }\n }\n else {\n this.minEndIndex = index;\n }\n if (this.maxEndIndex >= 0) {\n long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd()\n .getTime();\n if (end > maxEnd) {\n this.maxEndIndex = index; \n }\n }\n else {\n this.maxEndIndex = index;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void updateBounds(TimePeriod period, int index) {\n long start = period.getStart().getTime();\n long end = period.getEnd().getTime();\n long middle = start + ((end - start) / 2);\n if (this.minStartIndex >= 0) {\n long minStart = getDataItem(this.minStartIndex).getPeriod()\n .getStart().getTime();\n if (start < minStart) {\n this.minStartIndex = index; \n }\n }\n else {\n this.minStartIndex = index;\n }\n if (this.maxStartIndex >= 0) {\n long maxStart = getDataItem(this.maxStartIndex).getPeriod()\n .getStart().getTime();\n if (start > maxStart) {\n this.maxStartIndex = index; \n }\n }\n else {\n this.maxStartIndex = index;\n }\n if (this.minMiddleIndex >= 0) {\n long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()\n .getTime();\n long minMiddle = s + (e - s) / 2;\n if (middle < minMiddle) {\n this.minMiddleIndex = index; \n }\n }\n else {\n this.minMiddleIndex = index;\n }\n if (this.maxMiddleIndex >= 0) {\n long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()\n .getTime();\n long maxMiddle = s + (e - s) / 2;\n if (middle > maxMiddle) {\n this.maxMiddleIndex = index; \n }\n }\n else {\n this.maxMiddleIndex = index;\n }\n if (this.minEndIndex >= 0) {\n long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd()\n .getTime();\n if (end < minEnd) {\n this.minEndIndex = index; \n }\n }\n else {\n this.minEndIndex = index;\n }\n if (this.maxEndIndex >= 0) {\n long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd()\n .getTime();\n if (end > maxEnd) {\n this.maxEndIndex = index; \n }\n }\n else {\n this.maxEndIndex = index;\n }\n }\n"}, "reference": " private void updateBounds(TimePeriod period, int index) {\n long start = period.getStart().getTime();\n long end = period.getEnd().getTime();\n long middle = start + ((end - start) / 2);\n if (this.minStartIndex >= 0) {\n long minStart = getDataItem(this.minStartIndex).getPeriod()\n .getStart().getTime();\n if (start < minStart) {\n this.minStartIndex = index; \n }\n }\n else {\n this.minStartIndex = index;\n }\n if (this.maxStartIndex >= 0) {\n long maxStart = getDataItem(this.maxStartIndex).getPeriod()\n .getStart().getTime();\n if (start > maxStart) {\n this.maxStartIndex = index; \n }\n }\n else {\n this.maxStartIndex = index;\n }\n if (this.minMiddleIndex >= 0) {\n long s = getDataItem(this.minMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.minMiddleIndex).getPeriod().getEnd()\n .getTime();\n long minMiddle = s + (e - s) / 2;\n if (middle < minMiddle) {\n this.minMiddleIndex = index; \n }\n }\n else {\n this.minMiddleIndex = index;\n }\n if (this.maxMiddleIndex >= 0) {\n long s = getDataItem(this.maxMiddleIndex).getPeriod().getStart()\n .getTime();\n long e = getDataItem(this.maxMiddleIndex).getPeriod().getEnd()\n .getTime();\n long maxMiddle = s + (e - s) / 2;\n if (middle > maxMiddle) {\n this.maxMiddleIndex = index; \n }\n }\n else {\n this.maxMiddleIndex = index;\n }\n if (this.minEndIndex >= 0) {\n long minEnd = getDataItem(this.minEndIndex).getPeriod().getEnd()\n .getTime();\n if (end < minEnd) {\n this.minEndIndex = index; \n }\n }\n else {\n this.minEndIndex = index;\n }\n if (this.maxEndIndex >= 0) {\n long maxEnd = getDataItem(this.maxEndIndex).getPeriod().getEnd()\n .getTime();\n if (end > maxEnd) {\n this.maxEndIndex = index; \n }\n }\n else {\n this.maxEndIndex = index;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-7"}} {"sample_uid": "defects4j_function_repair::Jsoup-48", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void processResponseHeaders(Map> resHeaders) {\n for (Map.Entry> entry : resHeaders.entrySet()) {\n String name = entry.getKey();\n if (name == null)\n continue; \n List values = entry.getValue();\n if (name.equalsIgnoreCase(\"Set-Cookie\")) {\n for (String value : values) {\n if (value == null)\n continue;\n TokenQueue cd = new TokenQueue(value);\n String cookieName = cd.chompTo(\"=\").trim();\n String cookieVal = cd.consumeTo(\";\").trim();\n if (cookieName.length() > 0)\n cookie(cookieName, cookieVal);\n }\n } else { \n if (!values.isEmpty())\n header(name, values.get(0));\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void processResponseHeaders(Map> resHeaders) {\n for (Map.Entry> entry : resHeaders.entrySet()) {\n String name = entry.getKey();\n if (name == null)\n continue; \n List values = entry.getValue();\n if (name.equalsIgnoreCase(\"Set-Cookie\")) {\n for (String value : values) {\n if (value == null)\n continue;\n TokenQueue cd = new TokenQueue(value);\n String cookieName = cd.chompTo(\"=\").trim();\n String cookieVal = cd.consumeTo(\";\").trim();\n if (cookieName.length() > 0)\n cookie(cookieName, cookieVal);\n }\n } else { \n if (!values.isEmpty())\n header(name, values.get(0));\n }\n }\n }\n"}, "reference": " void processResponseHeaders(Map> resHeaders) {\n for (Map.Entry> entry : resHeaders.entrySet()) {\n String name = entry.getKey();\n if (name == null)\n continue; \n List values = entry.getValue();\n if (name.equalsIgnoreCase(\"Set-Cookie\")) {\n for (String value : values) {\n if (value == null)\n continue;\n TokenQueue cd = new TokenQueue(value);\n String cookieName = cd.chompTo(\"=\").trim();\n String cookieVal = cd.consumeTo(\";\").trim();\n if (cookieName.length() > 0)\n cookie(cookieName, cookieVal);\n }\n } else { \n if (values.size() == 1)\n header(name, values.get(0));\n else if (values.size() > 1) {\n StringBuilder accum = new StringBuilder();\n for (int i = 0; i < values.size(); i++) {\n final String val = values.get(i);\n if (i != 0)\n accum.append(\", \");\n accum.append(val);\n }\n header(name, accum.toString());\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-48"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-48"}} {"sample_uid": "defects4j_function_repair::Closure-109", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node parseContextTypeExpression(JsDocToken token) {\n return parseTypeName(token);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node parseContextTypeExpression(JsDocToken token) {\n return parseTypeName(token);\n }\n"}, "reference": " private Node parseContextTypeExpression(JsDocToken token) {\n if (token == JsDocToken.QMARK) {\n return newNode(Token.QMARK);\n } else {\n return parseBasicTypeExpression(token);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-109"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-109"}} {"sample_uid": "defects4j_function_repair::Closure-70", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void declareArguments(Node functionNode) {\n Node astParameters = functionNode.getFirstChild().getNext();\n Node body = astParameters.getNext();\n FunctionType functionType = (FunctionType) functionNode.getJSType();\n if (functionType != null) {\n Node jsDocParameters = functionType.getParametersNode();\n if (jsDocParameters != null) {\n Node jsDocParameter = jsDocParameters.getFirstChild();\n for (Node astParameter : astParameters.children()) {\n if (jsDocParameter != null) {\n defineSlot(astParameter, functionNode,\n jsDocParameter.getJSType(), true);\n jsDocParameter = jsDocParameter.getNext();\n } else {\n defineSlot(astParameter, functionNode, null, true);\n }\n }\n }\n }\n } \n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void declareArguments(Node functionNode) {\n Node astParameters = functionNode.getFirstChild().getNext();\n Node body = astParameters.getNext();\n FunctionType functionType = (FunctionType) functionNode.getJSType();\n if (functionType != null) {\n Node jsDocParameters = functionType.getParametersNode();\n if (jsDocParameters != null) {\n Node jsDocParameter = jsDocParameters.getFirstChild();\n for (Node astParameter : astParameters.children()) {\n if (jsDocParameter != null) {\n defineSlot(astParameter, functionNode,\n jsDocParameter.getJSType(), true);\n jsDocParameter = jsDocParameter.getNext();\n } else {\n defineSlot(astParameter, functionNode, null, true);\n }\n }\n }\n }\n } \n"}, "reference": " private void declareArguments(Node functionNode) {\n Node astParameters = functionNode.getFirstChild().getNext();\n Node body = astParameters.getNext();\n FunctionType functionType = (FunctionType) functionNode.getJSType();\n if (functionType != null) {\n Node jsDocParameters = functionType.getParametersNode();\n if (jsDocParameters != null) {\n Node jsDocParameter = jsDocParameters.getFirstChild();\n for (Node astParameter : astParameters.children()) {\n if (jsDocParameter != null) {\n defineSlot(astParameter, functionNode,\n jsDocParameter.getJSType(), false);\n jsDocParameter = jsDocParameter.getNext();\n } else {\n defineSlot(astParameter, functionNode, null, true);\n }\n }\n }\n }\n } \n", "tests": {}, "repo_meta": {"bug_id": "Closure-70"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-70"}} {"sample_uid": "defects4j_function_repair::Closure-129", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void annotateCalls(Node n) {\n Preconditions.checkState(n.isCall());\n Node first = n.getFirstChild();\n if (!NodeUtil.isGet(first)) {\n n.putBooleanProp(Node.FREE_CALL, true);\n }\n if (first.isName() &&\n \"eval\".equals(first.getString())) {\n first.putBooleanProp(Node.DIRECT_EVAL, true);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void annotateCalls(Node n) {\n Preconditions.checkState(n.isCall());\n Node first = n.getFirstChild();\n if (!NodeUtil.isGet(first)) {\n n.putBooleanProp(Node.FREE_CALL, true);\n }\n if (first.isName() &&\n \"eval\".equals(first.getString())) {\n first.putBooleanProp(Node.DIRECT_EVAL, true);\n }\n }\n"}, "reference": " private void annotateCalls(Node n) {\n Preconditions.checkState(n.isCall());\n Node first = n.getFirstChild();\n while (first.isCast()) {\n first = first.getFirstChild();\n }\n if (!NodeUtil.isGet(first)) {\n n.putBooleanProp(Node.FREE_CALL, true);\n }\n if (first.isName() &&\n \"eval\".equals(first.getString())) {\n first.putBooleanProp(Node.DIRECT_EVAL, true);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-129"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-129"}} {"sample_uid": "defects4j_function_repair::Gson-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Date read(JsonReader in) throws IOException {\n if (in.peek() != JsonToken.STRING) {\n throw new JsonParseException(\"The date should be a string value\");\n }\n Date date = deserializeToDate(in.nextString());\n if (dateType == Date.class) {\n return date;\n } else if (dateType == Timestamp.class) {\n return new Timestamp(date.getTime());\n } else if (dateType == java.sql.Date.class) {\n return new java.sql.Date(date.getTime());\n } else {\n throw new AssertionError();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Date read(JsonReader in) throws IOException {\n if (in.peek() != JsonToken.STRING) {\n throw new JsonParseException(\"The date should be a string value\");\n }\n Date date = deserializeToDate(in.nextString());\n if (dateType == Date.class) {\n return date;\n } else if (dateType == Timestamp.class) {\n return new Timestamp(date.getTime());\n } else if (dateType == java.sql.Date.class) {\n return new java.sql.Date(date.getTime());\n } else {\n throw new AssertionError();\n }\n }\n"}, "reference": " public Date read(JsonReader in) throws IOException {\n if (in.peek() == JsonToken.NULL) {\n in.nextNull();\n return null;\n }\n Date date = deserializeToDate(in.nextString());\n if (dateType == Date.class) {\n return date;\n } else if (dateType == Timestamp.class) {\n return new Timestamp(date.getTime());\n } else if (dateType == java.sql.Date.class) {\n return new java.sql.Date(date.getTime());\n } else {\n throw new AssertionError();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-17"}} {"sample_uid": "defects4j_function_repair::Compress-32", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void applyPaxHeadersToCurrentEntry(Map headers) {\n for (Entry ent : headers.entrySet()){\n String key = ent.getKey();\n String val = ent.getValue();\n if (\"path\".equals(key)){\n currEntry.setName(val);\n } else if (\"linkpath\".equals(key)){\n currEntry.setLinkName(val);\n } else if (\"gid\".equals(key)){\n currEntry.setGroupId(Integer.parseInt(val));\n } else if (\"gname\".equals(key)){\n currEntry.setGroupName(val);\n } else if (\"uid\".equals(key)){\n currEntry.setUserId(Integer.parseInt(val));\n } else if (\"uname\".equals(key)){\n currEntry.setUserName(val);\n } else if (\"size\".equals(key)){\n currEntry.setSize(Long.parseLong(val));\n } else if (\"mtime\".equals(key)){\n currEntry.setModTime((long) (Double.parseDouble(val) * 1000));\n } else if (\"SCHILY.devminor\".equals(key)){\n currEntry.setDevMinor(Integer.parseInt(val));\n } else if (\"SCHILY.devmajor\".equals(key)){\n currEntry.setDevMajor(Integer.parseInt(val));\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void applyPaxHeadersToCurrentEntry(Map headers) {\n for (Entry ent : headers.entrySet()){\n String key = ent.getKey();\n String val = ent.getValue();\n if (\"path\".equals(key)){\n currEntry.setName(val);\n } else if (\"linkpath\".equals(key)){\n currEntry.setLinkName(val);\n } else if (\"gid\".equals(key)){\n currEntry.setGroupId(Integer.parseInt(val));\n } else if (\"gname\".equals(key)){\n currEntry.setGroupName(val);\n } else if (\"uid\".equals(key)){\n currEntry.setUserId(Integer.parseInt(val));\n } else if (\"uname\".equals(key)){\n currEntry.setUserName(val);\n } else if (\"size\".equals(key)){\n currEntry.setSize(Long.parseLong(val));\n } else if (\"mtime\".equals(key)){\n currEntry.setModTime((long) (Double.parseDouble(val) * 1000));\n } else if (\"SCHILY.devminor\".equals(key)){\n currEntry.setDevMinor(Integer.parseInt(val));\n } else if (\"SCHILY.devmajor\".equals(key)){\n currEntry.setDevMajor(Integer.parseInt(val));\n }\n }\n }\n"}, "reference": " private void applyPaxHeadersToCurrentEntry(Map headers) {\n for (Entry ent : headers.entrySet()){\n String key = ent.getKey();\n String val = ent.getValue();\n if (\"path\".equals(key)){\n currEntry.setName(val);\n } else if (\"linkpath\".equals(key)){\n currEntry.setLinkName(val);\n } else if (\"gid\".equals(key)){\n currEntry.setGroupId(Long.parseLong(val));\n } else if (\"gname\".equals(key)){\n currEntry.setGroupName(val);\n } else if (\"uid\".equals(key)){\n currEntry.setUserId(Long.parseLong(val));\n } else if (\"uname\".equals(key)){\n currEntry.setUserName(val);\n } else if (\"size\".equals(key)){\n currEntry.setSize(Long.parseLong(val));\n } else if (\"mtime\".equals(key)){\n currEntry.setModTime((long) (Double.parseDouble(val) * 1000));\n } else if (\"SCHILY.devminor\".equals(key)){\n currEntry.setDevMinor(Integer.parseInt(val));\n } else if (\"SCHILY.devmajor\".equals(key)){\n currEntry.setDevMajor(Integer.parseInt(val));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-32"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-32"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-51", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);\n if (actual == null) { \n return null;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);\n if (actual == null) { \n return null;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n"}, "reference": " protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);\n if (actual == null) { \n return null;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n if (!type.hasGenericTypes()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-51"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-51"}} {"sample_uid": "defects4j_function_repair::Jsoup-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Attribute parseAttribute() {\n tq.consumeWhitespace();\n String key = tq.consumeAttributeKey();\n String value = \"\";\n tq.consumeWhitespace();\n if (tq.matchChomp(\"=\")) {\n tq.consumeWhitespace();\n if (tq.matchChomp(SQ)) {\n value = tq.chompTo(SQ);\n } else if (tq.matchChomp(DQ)) {\n value = tq.chompTo(DQ);\n } else {\n StringBuilder valueAccum = new StringBuilder();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.matchesWhitespace() && !tq.isEmpty()) {\n valueAccum.append(tq.consume());\n }\n value = valueAccum.toString();\n }\n tq.consumeWhitespace();\n }\n if (key.length() != 0)\n return Attribute.createFromEncoded(key, value);\n else {\n tq.consume();\n return null;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Attribute parseAttribute() {\n tq.consumeWhitespace();\n String key = tq.consumeAttributeKey();\n String value = \"\";\n tq.consumeWhitespace();\n if (tq.matchChomp(\"=\")) {\n tq.consumeWhitespace();\n if (tq.matchChomp(SQ)) {\n value = tq.chompTo(SQ);\n } else if (tq.matchChomp(DQ)) {\n value = tq.chompTo(DQ);\n } else {\n StringBuilder valueAccum = new StringBuilder();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.matchesWhitespace() && !tq.isEmpty()) {\n valueAccum.append(tq.consume());\n }\n value = valueAccum.toString();\n }\n tq.consumeWhitespace();\n }\n if (key.length() != 0)\n return Attribute.createFromEncoded(key, value);\n else {\n tq.consume();\n return null;\n }\n }\n"}, "reference": " private Attribute parseAttribute() {\n tq.consumeWhitespace();\n String key = tq.consumeAttributeKey();\n String value = \"\";\n tq.consumeWhitespace();\n if (tq.matchChomp(\"=\")) {\n tq.consumeWhitespace();\n if (tq.matchChomp(SQ)) {\n value = tq.chompTo(SQ);\n } else if (tq.matchChomp(DQ)) {\n value = tq.chompTo(DQ);\n } else {\n StringBuilder valueAccum = new StringBuilder();\n while (!tq.matchesAny(\"<\", \"/>\", \">\") && !tq.matchesWhitespace() && !tq.isEmpty()) {\n valueAccum.append(tq.consume());\n }\n value = valueAccum.toString();\n }\n tq.consumeWhitespace();\n }\n if (key.length() != 0)\n return Attribute.createFromEncoded(key, value);\n else {\n if (value.length() == 0) \n tq.advance();\n return null;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-5"}} {"sample_uid": "defects4j_function_repair::Jsoup-47", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(\" \");\n break;\n case '<':\n if (!inAttribute)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(\" \");\n break;\n case '<':\n if (!inAttribute)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n"}, "reference": " static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(\" \");\n break;\n case '<':\n if (!inAttribute || escapeMode == EscapeMode.xhtml)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-47"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-47"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-71", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static StdKeyDeserializer forType(Class raw)\n {\n int kind;\n if (raw == String.class || raw == Object.class) {\n return StringKD.forType(raw);\n } else if (raw == UUID.class) {\n kind = TYPE_UUID;\n } else if (raw == Integer.class) {\n kind = TYPE_INT;\n } else if (raw == Long.class) {\n kind = TYPE_LONG;\n } else if (raw == Date.class) {\n kind = TYPE_DATE;\n } else if (raw == Calendar.class) {\n kind = TYPE_CALENDAR;\n } else if (raw == Boolean.class) {\n kind = TYPE_BOOLEAN;\n } else if (raw == Byte.class) {\n kind = TYPE_BYTE;\n } else if (raw == Character.class) {\n kind = TYPE_CHAR;\n } else if (raw == Short.class) {\n kind = TYPE_SHORT;\n } else if (raw == Float.class) {\n kind = TYPE_FLOAT;\n } else if (raw == Double.class) {\n kind = TYPE_DOUBLE;\n } else if (raw == URI.class) {\n kind = TYPE_URI;\n } else if (raw == URL.class) {\n kind = TYPE_URL;\n } else if (raw == Class.class) {\n kind = TYPE_CLASS;\n } else if (raw == Locale.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Locale.class);\n return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);\n } else if (raw == Currency.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Currency.class);\n return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);\n } else {\n return null;\n }\n return new StdKeyDeserializer(kind, raw);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static StdKeyDeserializer forType(Class raw)\n {\n int kind;\n if (raw == String.class || raw == Object.class) {\n return StringKD.forType(raw);\n } else if (raw == UUID.class) {\n kind = TYPE_UUID;\n } else if (raw == Integer.class) {\n kind = TYPE_INT;\n } else if (raw == Long.class) {\n kind = TYPE_LONG;\n } else if (raw == Date.class) {\n kind = TYPE_DATE;\n } else if (raw == Calendar.class) {\n kind = TYPE_CALENDAR;\n } else if (raw == Boolean.class) {\n kind = TYPE_BOOLEAN;\n } else if (raw == Byte.class) {\n kind = TYPE_BYTE;\n } else if (raw == Character.class) {\n kind = TYPE_CHAR;\n } else if (raw == Short.class) {\n kind = TYPE_SHORT;\n } else if (raw == Float.class) {\n kind = TYPE_FLOAT;\n } else if (raw == Double.class) {\n kind = TYPE_DOUBLE;\n } else if (raw == URI.class) {\n kind = TYPE_URI;\n } else if (raw == URL.class) {\n kind = TYPE_URL;\n } else if (raw == Class.class) {\n kind = TYPE_CLASS;\n } else if (raw == Locale.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Locale.class);\n return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);\n } else if (raw == Currency.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Currency.class);\n return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);\n } else {\n return null;\n }\n return new StdKeyDeserializer(kind, raw);\n }\n"}, "reference": " public static StdKeyDeserializer forType(Class raw)\n {\n int kind;\n if (raw == String.class || raw == Object.class || raw == CharSequence.class) {\n return StringKD.forType(raw);\n } else if (raw == UUID.class) {\n kind = TYPE_UUID;\n } else if (raw == Integer.class) {\n kind = TYPE_INT;\n } else if (raw == Long.class) {\n kind = TYPE_LONG;\n } else if (raw == Date.class) {\n kind = TYPE_DATE;\n } else if (raw == Calendar.class) {\n kind = TYPE_CALENDAR;\n } else if (raw == Boolean.class) {\n kind = TYPE_BOOLEAN;\n } else if (raw == Byte.class) {\n kind = TYPE_BYTE;\n } else if (raw == Character.class) {\n kind = TYPE_CHAR;\n } else if (raw == Short.class) {\n kind = TYPE_SHORT;\n } else if (raw == Float.class) {\n kind = TYPE_FLOAT;\n } else if (raw == Double.class) {\n kind = TYPE_DOUBLE;\n } else if (raw == URI.class) {\n kind = TYPE_URI;\n } else if (raw == URL.class) {\n kind = TYPE_URL;\n } else if (raw == Class.class) {\n kind = TYPE_CLASS;\n } else if (raw == Locale.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Locale.class);\n return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);\n } else if (raw == Currency.class) {\n FromStringDeserializer deser = FromStringDeserializer.findDeserializer(Currency.class);\n return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);\n } else {\n return null;\n }\n return new StdKeyDeserializer(kind, raw);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-71"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-71"}} {"sample_uid": "defects4j_function_repair::Closure-124", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isSafeReplacement(Node node, Node replacement) {\n if (node.isName()) {\n return true;\n }\n Preconditions.checkArgument(node.isGetProp());\n node = node.getFirstChild();\n if (node.isName()\n && isNameAssignedTo(node.getString(), replacement)) {\n return false;\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isSafeReplacement(Node node, Node replacement) {\n if (node.isName()) {\n return true;\n }\n Preconditions.checkArgument(node.isGetProp());\n node = node.getFirstChild();\n if (node.isName()\n && isNameAssignedTo(node.getString(), replacement)) {\n return false;\n }\n return true;\n }\n"}, "reference": " private boolean isSafeReplacement(Node node, Node replacement) {\n if (node.isName()) {\n return true;\n }\n Preconditions.checkArgument(node.isGetProp());\n while (node.isGetProp()) {\n node = node.getFirstChild();\n }\n if (node.isName()\n && isNameAssignedTo(node.getString(), replacement)) {\n return false;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-124"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-124"}} {"sample_uid": "defects4j_function_repair::Jsoup-41", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Element element = (Element) o;\n return this == o;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Element element = (Element) o;\n return this == o;\n }\n"}, "reference": " public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n if (!super.equals(o)) return false;\n Element element = (Element) o;\n return tag.equals(element.tag);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-41"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-41"}} {"sample_uid": "defects4j_function_repair::Mockito-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void registerTypeVariablesOn(Type classType) {\n if (!(classType instanceof ParameterizedType)) {\n return;\n }\n ParameterizedType parameterizedType = (ParameterizedType) classType;\n TypeVariable[] typeParameters = ((Class) parameterizedType.getRawType()).getTypeParameters();\n Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();\n for (int i = 0; i < actualTypeArguments.length; i++) {\n TypeVariable typeParameter = typeParameters[i];\n Type actualTypeArgument = actualTypeArguments[i];\n if (actualTypeArgument instanceof WildcardType) {\n contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));\n } else {\n contextualActualTypeParameters.put(typeParameter, actualTypeArgument);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void registerTypeVariablesOn(Type classType) {\n if (!(classType instanceof ParameterizedType)) {\n return;\n }\n ParameterizedType parameterizedType = (ParameterizedType) classType;\n TypeVariable[] typeParameters = ((Class) parameterizedType.getRawType()).getTypeParameters();\n Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();\n for (int i = 0; i < actualTypeArguments.length; i++) {\n TypeVariable typeParameter = typeParameters[i];\n Type actualTypeArgument = actualTypeArguments[i];\n if (actualTypeArgument instanceof WildcardType) {\n contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));\n } else {\n contextualActualTypeParameters.put(typeParameter, actualTypeArgument);\n }\n }\n }\n"}, "reference": " protected void registerTypeVariablesOn(Type classType) {\n if (!(classType instanceof ParameterizedType)) {\n return;\n }\n ParameterizedType parameterizedType = (ParameterizedType) classType;\n TypeVariable[] typeParameters = ((Class) parameterizedType.getRawType()).getTypeParameters();\n Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();\n for (int i = 0; i < actualTypeArguments.length; i++) {\n TypeVariable typeParameter = typeParameters[i];\n Type actualTypeArgument = actualTypeArguments[i];\n if (actualTypeArgument instanceof WildcardType) {\n contextualActualTypeParameters.put(typeParameter, boundsOf((WildcardType) actualTypeArgument));\n } else if (typeParameter != actualTypeArgument) {\n contextualActualTypeParameters.put(typeParameter, actualTypeArgument);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-8"}} {"sample_uid": "defects4j_function_repair::JacksonCore-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public char[] getTextBuffer()\n {\n if (_inputStart >= 0) return _inputBuffer;\n if (_resultArray != null) return _resultArray;\n if (_resultString != null) {\n return (_resultArray = _resultString.toCharArray());\n }\n if (!_hasSegments) return _currentSegment;\n return contentsAsArray();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public char[] getTextBuffer()\n {\n if (_inputStart >= 0) return _inputBuffer;\n if (_resultArray != null) return _resultArray;\n if (_resultString != null) {\n return (_resultArray = _resultString.toCharArray());\n }\n if (!_hasSegments) return _currentSegment;\n return contentsAsArray();\n }\n"}, "reference": " public char[] getTextBuffer()\n {\n if (_inputStart >= 0) return _inputBuffer;\n if (_resultArray != null) return _resultArray;\n if (_resultString != null) {\n return (_resultArray = _resultString.toCharArray());\n }\n if (!_hasSegments && _currentSegment != null) return _currentSegment;\n return contentsAsArray();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-8"}} {"sample_uid": "defects4j_function_repair::Cli-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void burstToken(String token, boolean stopAtNonOption)\n {\n for (int i = 1; i < token.length(); i++)\n {\n String ch = String.valueOf(token.charAt(i));\n if (options.hasOption(ch))\n {\n tokens.add(\"-\" + ch);\n currentOption = options.getOption(ch);\n if (currentOption.hasArg() && (token.length() != (i + 1)))\n {\n tokens.add(token.substring(i + 1));\n break;\n }\n }\n else if (stopAtNonOption)\n {\n process(token.substring(i));\n }\n else\n {\n tokens.add(token);\n break;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void burstToken(String token, boolean stopAtNonOption)\n {\n for (int i = 1; i < token.length(); i++)\n {\n String ch = String.valueOf(token.charAt(i));\n if (options.hasOption(ch))\n {\n tokens.add(\"-\" + ch);\n currentOption = options.getOption(ch);\n if (currentOption.hasArg() && (token.length() != (i + 1)))\n {\n tokens.add(token.substring(i + 1));\n break;\n }\n }\n else if (stopAtNonOption)\n {\n process(token.substring(i));\n }\n else\n {\n tokens.add(token);\n break;\n }\n }\n }\n"}, "reference": " protected void burstToken(String token, boolean stopAtNonOption)\n {\n for (int i = 1; i < token.length(); i++)\n {\n String ch = String.valueOf(token.charAt(i));\n if (options.hasOption(ch))\n {\n tokens.add(\"-\" + ch);\n currentOption = options.getOption(ch);\n if (currentOption.hasArg() && (token.length() != (i + 1)))\n {\n tokens.add(token.substring(i + 1));\n break;\n }\n }\n else if (stopAtNonOption)\n {\n process(token.substring(i));\n break;\n }\n else\n {\n tokens.add(token);\n break;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-17"}} {"sample_uid": "defects4j_function_repair::Math-86", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public CholeskyDecompositionImpl(final RealMatrix matrix,\n final double relativeSymmetryThreshold,\n final double absolutePositivityThreshold)\n throws NonSquareMatrixException,\n NotSymmetricMatrixException, NotPositiveDefiniteMatrixException {\n if (!matrix.isSquare()) {\n throw new NonSquareMatrixException(matrix.getRowDimension(),\n matrix.getColumnDimension());\n }\n final int order = matrix.getRowDimension();\n lTData = matrix.getData();\n cachedL = null;\n cachedLT = null;\n for (int i = 0; i < order; ++i) {\n final double[] lI = lTData[i];\n if (lTData[i][i] < absolutePositivityThreshold) {\n throw new NotPositiveDefiniteMatrixException();\n }\n for (int j = i + 1; j < order; ++j) {\n final double[] lJ = lTData[j];\n final double lIJ = lI[j];\n final double lJI = lJ[i];\n final double maxDelta =\n relativeSymmetryThreshold * Math.max(Math.abs(lIJ), Math.abs(lJI));\n if (Math.abs(lIJ - lJI) > maxDelta) {\n throw new NotSymmetricMatrixException();\n }\n lJ[i] = 0;\n }\n }\n for (int i = 0; i < order; ++i) {\n final double[] ltI = lTData[i];\n ltI[i] = Math.sqrt(ltI[i]);\n final double inverse = 1.0 / ltI[i];\n for (int q = order - 1; q > i; --q) {\n ltI[q] *= inverse;\n final double[] ltQ = lTData[q];\n for (int p = q; p < order; ++p) {\n ltQ[p] -= ltI[q] * ltI[p];\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public CholeskyDecompositionImpl(final RealMatrix matrix,\n final double relativeSymmetryThreshold,\n final double absolutePositivityThreshold)\n throws NonSquareMatrixException,\n NotSymmetricMatrixException, NotPositiveDefiniteMatrixException {\n if (!matrix.isSquare()) {\n throw new NonSquareMatrixException(matrix.getRowDimension(),\n matrix.getColumnDimension());\n }\n final int order = matrix.getRowDimension();\n lTData = matrix.getData();\n cachedL = null;\n cachedLT = null;\n for (int i = 0; i < order; ++i) {\n final double[] lI = lTData[i];\n if (lTData[i][i] < absolutePositivityThreshold) {\n throw new NotPositiveDefiniteMatrixException();\n }\n for (int j = i + 1; j < order; ++j) {\n final double[] lJ = lTData[j];\n final double lIJ = lI[j];\n final double lJI = lJ[i];\n final double maxDelta =\n relativeSymmetryThreshold * Math.max(Math.abs(lIJ), Math.abs(lJI));\n if (Math.abs(lIJ - lJI) > maxDelta) {\n throw new NotSymmetricMatrixException();\n }\n lJ[i] = 0;\n }\n }\n for (int i = 0; i < order; ++i) {\n final double[] ltI = lTData[i];\n ltI[i] = Math.sqrt(ltI[i]);\n final double inverse = 1.0 / ltI[i];\n for (int q = order - 1; q > i; --q) {\n ltI[q] *= inverse;\n final double[] ltQ = lTData[q];\n for (int p = q; p < order; ++p) {\n ltQ[p] -= ltI[q] * ltI[p];\n }\n }\n }\n }\n"}, "reference": " public CholeskyDecompositionImpl(final RealMatrix matrix,\n final double relativeSymmetryThreshold,\n final double absolutePositivityThreshold)\n throws NonSquareMatrixException,\n NotSymmetricMatrixException, NotPositiveDefiniteMatrixException {\n if (!matrix.isSquare()) {\n throw new NonSquareMatrixException(matrix.getRowDimension(),\n matrix.getColumnDimension());\n }\n final int order = matrix.getRowDimension();\n lTData = matrix.getData();\n cachedL = null;\n cachedLT = null;\n for (int i = 0; i < order; ++i) {\n final double[] lI = lTData[i];\n for (int j = i + 1; j < order; ++j) {\n final double[] lJ = lTData[j];\n final double lIJ = lI[j];\n final double lJI = lJ[i];\n final double maxDelta =\n relativeSymmetryThreshold * Math.max(Math.abs(lIJ), Math.abs(lJI));\n if (Math.abs(lIJ - lJI) > maxDelta) {\n throw new NotSymmetricMatrixException();\n }\n lJ[i] = 0;\n }\n }\n for (int i = 0; i < order; ++i) {\n final double[] ltI = lTData[i];\n if (ltI[i] < absolutePositivityThreshold) {\n throw new NotPositiveDefiniteMatrixException();\n }\n ltI[i] = Math.sqrt(ltI[i]);\n final double inverse = 1.0 / ltI[i];\n for (int q = order - 1; q > i; --q) {\n ltI[q] *= inverse;\n final double[] ltQ = lTData[q];\n for (int p = q; p < order; ++p) {\n ltQ[p] -= ltI[q] * ltI[p];\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-86"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-86"}} {"sample_uid": "defects4j_function_repair::Closure-83", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int parseArguments(Parameters params) throws CmdLineException {\n String param = params.getParameter(0);\n if (param == null) {\n setter.addValue(true);\n return 0;\n } else {\n String lowerParam = param.toLowerCase();\n if (TRUES.contains(lowerParam)) {\n setter.addValue(true);\n } else if (FALSES.contains(lowerParam)) {\n setter.addValue(false);\n } else {\n setter.addValue(true);\n return 0;\n }\n return 1;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int parseArguments(Parameters params) throws CmdLineException {\n String param = params.getParameter(0);\n if (param == null) {\n setter.addValue(true);\n return 0;\n } else {\n String lowerParam = param.toLowerCase();\n if (TRUES.contains(lowerParam)) {\n setter.addValue(true);\n } else if (FALSES.contains(lowerParam)) {\n setter.addValue(false);\n } else {\n setter.addValue(true);\n return 0;\n }\n return 1;\n }\n }\n"}, "reference": " public int parseArguments(Parameters params) throws CmdLineException {\n String param = null;\n try {\n param = params.getParameter(0);\n } catch (CmdLineException e) {}\n if (param == null) {\n setter.addValue(true);\n return 0;\n } else {\n String lowerParam = param.toLowerCase();\n if (TRUES.contains(lowerParam)) {\n setter.addValue(true);\n } else if (FALSES.contains(lowerParam)) {\n setter.addValue(false);\n } else {\n setter.addValue(true);\n return 0;\n }\n return 1;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-83"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-83"}} {"sample_uid": "defects4j_function_repair::Jsoup-61", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean hasClass(String className) {\n final String classAttr = attributes.get(\"class\");\n final int len = classAttr.length();\n final int wantLen = className.length();\n if (len == 0 || len < wantLen) {\n return false;\n }\n if (len == wantLen) {\n return className.equalsIgnoreCase(classAttr);\n }\n boolean inClass = false;\n int start = 0;\n for (int i = 0; i < len; i++) {\n if (Character.isWhitespace(classAttr.charAt(i))) {\n if (inClass) {\n if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) {\n return true;\n }\n inClass = false;\n }\n } else {\n if (!inClass) {\n inClass = true;\n start = i;\n }\n }\n }\n if (inClass && len - start == wantLen) {\n return classAttr.regionMatches(true, start, className, 0, wantLen);\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean hasClass(String className) {\n final String classAttr = attributes.get(\"class\");\n final int len = classAttr.length();\n final int wantLen = className.length();\n if (len == 0 || len < wantLen) {\n return false;\n }\n if (len == wantLen) {\n return className.equalsIgnoreCase(classAttr);\n }\n boolean inClass = false;\n int start = 0;\n for (int i = 0; i < len; i++) {\n if (Character.isWhitespace(classAttr.charAt(i))) {\n if (inClass) {\n if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) {\n return true;\n }\n inClass = false;\n }\n } else {\n if (!inClass) {\n inClass = true;\n start = i;\n }\n }\n }\n if (inClass && len - start == wantLen) {\n return classAttr.regionMatches(true, start, className, 0, wantLen);\n }\n return false;\n }\n"}, "reference": " public boolean hasClass(String className) {\n final String classAttr = attributes.getIgnoreCase(\"class\");\n final int len = classAttr.length();\n final int wantLen = className.length();\n if (len == 0 || len < wantLen) {\n return false;\n }\n if (len == wantLen) {\n return className.equalsIgnoreCase(classAttr);\n }\n boolean inClass = false;\n int start = 0;\n for (int i = 0; i < len; i++) {\n if (Character.isWhitespace(classAttr.charAt(i))) {\n if (inClass) {\n if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) {\n return true;\n }\n inClass = false;\n }\n } else {\n if (!inClass) {\n inClass = true;\n start = i;\n }\n }\n }\n if (inClass && len - start == wantLen) {\n return classAttr.regionMatches(true, start, className, 0, wantLen);\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-61"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-61"}} {"sample_uid": "defects4j_function_repair::Closure-32", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,\n WhitespaceOption option) {\n if (token == JsDocToken.EOC || token == JsDocToken.EOL ||\n token == JsDocToken.EOF) {\n return new ExtractionInfo(\"\", token);\n }\n stream.update();\n int startLineno = stream.getLineno();\n int startCharno = stream.getCharno() + 1;\n String line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = line.trim();\n }\n StringBuilder builder = new StringBuilder();\n builder.append(line);\n state = State.SEARCHING_ANNOTATION;\n token = next();\n boolean ignoreStar = false;\n do {\n switch (token) {\n case STAR:\n if (ignoreStar) {\n } else {\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append('*');\n }\n token = next();\n continue;\n case EOL:\n if (option != WhitespaceOption.SINGLE_LINE) {\n builder.append(\"\\n\");\n }\n ignoreStar = true;\n token = next();\n continue;\n default:\n ignoreStar = false;\n state = State.SEARCHING_ANNOTATION;\n if (token == JsDocToken.EOC ||\n token == JsDocToken.EOF ||\n (token == JsDocToken.ANNOTATION &&\n option != WhitespaceOption.PRESERVE)) {\n String multilineText = builder.toString();\n if (option != WhitespaceOption.PRESERVE) {\n multilineText = multilineText.trim();\n }\n int endLineno = stream.getLineno();\n int endCharno = stream.getCharno();\n if (multilineText.length() > 0) {\n jsdocBuilder.markText(multilineText, startLineno, startCharno,\n endLineno, endCharno);\n }\n return new ExtractionInfo(multilineText, token);\n }\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append(toString(token));\n line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = trimEnd(line);\n }\n builder.append(line);\n token = next();\n }\n } while (true);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,\n WhitespaceOption option) {\n if (token == JsDocToken.EOC || token == JsDocToken.EOL ||\n token == JsDocToken.EOF) {\n return new ExtractionInfo(\"\", token);\n }\n stream.update();\n int startLineno = stream.getLineno();\n int startCharno = stream.getCharno() + 1;\n String line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = line.trim();\n }\n StringBuilder builder = new StringBuilder();\n builder.append(line);\n state = State.SEARCHING_ANNOTATION;\n token = next();\n boolean ignoreStar = false;\n do {\n switch (token) {\n case STAR:\n if (ignoreStar) {\n } else {\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append('*');\n }\n token = next();\n continue;\n case EOL:\n if (option != WhitespaceOption.SINGLE_LINE) {\n builder.append(\"\\n\");\n }\n ignoreStar = true;\n token = next();\n continue;\n default:\n ignoreStar = false;\n state = State.SEARCHING_ANNOTATION;\n if (token == JsDocToken.EOC ||\n token == JsDocToken.EOF ||\n (token == JsDocToken.ANNOTATION &&\n option != WhitespaceOption.PRESERVE)) {\n String multilineText = builder.toString();\n if (option != WhitespaceOption.PRESERVE) {\n multilineText = multilineText.trim();\n }\n int endLineno = stream.getLineno();\n int endCharno = stream.getCharno();\n if (multilineText.length() > 0) {\n jsdocBuilder.markText(multilineText, startLineno, startCharno,\n endLineno, endCharno);\n }\n return new ExtractionInfo(multilineText, token);\n }\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append(toString(token));\n line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = trimEnd(line);\n }\n builder.append(line);\n token = next();\n }\n } while (true);\n }\n"}, "reference": " private ExtractionInfo extractMultilineTextualBlock(JsDocToken token,\n WhitespaceOption option) {\n if (token == JsDocToken.EOC || token == JsDocToken.EOL ||\n token == JsDocToken.EOF) {\n return new ExtractionInfo(\"\", token);\n }\n stream.update();\n int startLineno = stream.getLineno();\n int startCharno = stream.getCharno() + 1;\n String line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = line.trim();\n }\n StringBuilder builder = new StringBuilder();\n builder.append(line);\n state = State.SEARCHING_ANNOTATION;\n token = next();\n boolean ignoreStar = false;\n int lineStartChar = -1;\n do {\n switch (token) {\n case STAR:\n if (ignoreStar) {\n lineStartChar = stream.getCharno() + 1;\n } else {\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append('*');\n }\n token = next();\n continue;\n case EOL:\n if (option != WhitespaceOption.SINGLE_LINE) {\n builder.append(\"\\n\");\n }\n ignoreStar = true;\n lineStartChar = 0;\n token = next();\n continue;\n default:\n ignoreStar = false;\n state = State.SEARCHING_ANNOTATION;\n boolean isEOC = token == JsDocToken.EOC;\n if (!isEOC) {\n if (lineStartChar != -1 && option == WhitespaceOption.PRESERVE) {\n int numSpaces = stream.getCharno() - lineStartChar;\n for (int i = 0; i < numSpaces; i++) {\n builder.append(' ');\n }\n lineStartChar = -1;\n } else if (builder.length() > 0) {\n builder.append(' ');\n }\n }\n if (token == JsDocToken.EOC ||\n token == JsDocToken.EOF ||\n (token == JsDocToken.ANNOTATION &&\n option != WhitespaceOption.PRESERVE)) {\n String multilineText = builder.toString();\n if (option != WhitespaceOption.PRESERVE) {\n multilineText = multilineText.trim();\n }\n int endLineno = stream.getLineno();\n int endCharno = stream.getCharno();\n if (multilineText.length() > 0) {\n jsdocBuilder.markText(multilineText, startLineno, startCharno,\n endLineno, endCharno);\n }\n return new ExtractionInfo(multilineText, token);\n }\n builder.append(toString(token));\n line = stream.getRemainingJSDocLine();\n if (option != WhitespaceOption.PRESERVE) {\n line = trimEnd(line);\n }\n builder.append(line);\n token = next();\n }\n } while (true);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-32"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-32"}} {"sample_uid": "defects4j_function_repair::Math-53", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Complex add(Complex rhs)\n throws NullArgumentException {\n MathUtils.checkNotNull(rhs);\n return createComplex(real + rhs.getReal(),\n imaginary + rhs.getImaginary());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Complex add(Complex rhs)\n throws NullArgumentException {\n MathUtils.checkNotNull(rhs);\n return createComplex(real + rhs.getReal(),\n imaginary + rhs.getImaginary());\n }\n"}, "reference": " public Complex add(Complex rhs)\n throws NullArgumentException {\n MathUtils.checkNotNull(rhs);\n if (isNaN || rhs.isNaN) {\n return NaN;\n }\n return createComplex(real + rhs.getReal(),\n imaginary + rhs.getImaginary());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-53"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-53"}} {"sample_uid": "defects4j_function_repair::Math-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Integer getPivotRow(SimplexTableau tableau, final int col) {\n List minRatioPositions = new ArrayList();\n double minRatio = Double.MAX_VALUE;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (Precision.compareTo(entry, 0d, maxUlps) > 0) {\n final double ratio = rhs / entry;\n final int cmp = Double.compare(ratio, minRatio);\n if (cmp == 0) {\n minRatioPositions.add(i);\n } else if (cmp < 0) {\n minRatio = ratio;\n minRatioPositions = new ArrayList();\n minRatioPositions.add(i);\n }\n }\n }\n if (minRatioPositions.size() == 0) {\n return null;\n } else if (minRatioPositions.size() > 1) {\n for (Integer row : minRatioPositions) {\n for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {\n int column = i + tableau.getArtificialVariableOffset();\n final double entry = tableau.getEntry(row, column);\n if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {\n return row;\n }\n }\n }\n Integer minRow = null;\n int minIndex = tableau.getWidth();\n for (Integer row : minRatioPositions) {\n int i = tableau.getNumObjectiveFunctions();\n for (; i < tableau.getWidth() - 1 && minRow != row; i++) {\n if (row == tableau.getBasicRow(i)) {\n if (i < minIndex) {\n minIndex = i;\n minRow = row;\n }\n }\n }\n }\n return minRow;\n }\n return minRatioPositions.get(0);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Integer getPivotRow(SimplexTableau tableau, final int col) {\n List minRatioPositions = new ArrayList();\n double minRatio = Double.MAX_VALUE;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (Precision.compareTo(entry, 0d, maxUlps) > 0) {\n final double ratio = rhs / entry;\n final int cmp = Double.compare(ratio, minRatio);\n if (cmp == 0) {\n minRatioPositions.add(i);\n } else if (cmp < 0) {\n minRatio = ratio;\n minRatioPositions = new ArrayList();\n minRatioPositions.add(i);\n }\n }\n }\n if (minRatioPositions.size() == 0) {\n return null;\n } else if (minRatioPositions.size() > 1) {\n for (Integer row : minRatioPositions) {\n for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {\n int column = i + tableau.getArtificialVariableOffset();\n final double entry = tableau.getEntry(row, column);\n if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {\n return row;\n }\n }\n }\n Integer minRow = null;\n int minIndex = tableau.getWidth();\n for (Integer row : minRatioPositions) {\n int i = tableau.getNumObjectiveFunctions();\n for (; i < tableau.getWidth() - 1 && minRow != row; i++) {\n if (row == tableau.getBasicRow(i)) {\n if (i < minIndex) {\n minIndex = i;\n minRow = row;\n }\n }\n }\n }\n return minRow;\n }\n return minRatioPositions.get(0);\n }\n"}, "reference": " private Integer getPivotRow(SimplexTableau tableau, final int col) {\n List minRatioPositions = new ArrayList();\n double minRatio = Double.MAX_VALUE;\n for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {\n final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);\n final double entry = tableau.getEntry(i, col);\n if (Precision.compareTo(entry, 0d, maxUlps) > 0) {\n final double ratio = rhs / entry;\n final int cmp = Double.compare(ratio, minRatio);\n if (cmp == 0) {\n minRatioPositions.add(i);\n } else if (cmp < 0) {\n minRatio = ratio;\n minRatioPositions = new ArrayList();\n minRatioPositions.add(i);\n }\n }\n }\n if (minRatioPositions.size() == 0) {\n return null;\n } else if (minRatioPositions.size() > 1) {\n if (tableau.getNumArtificialVariables() > 0) {\n for (Integer row : minRatioPositions) {\n for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {\n int column = i + tableau.getArtificialVariableOffset();\n final double entry = tableau.getEntry(row, column);\n if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {\n return row;\n }\n }\n }\n }\n if (getIterations() < getMaxIterations() / 2) {\n Integer minRow = null;\n int minIndex = tableau.getWidth();\n for (Integer row : minRatioPositions) {\n int i = tableau.getNumObjectiveFunctions();\n for (; i < tableau.getWidth() - 1 && minRow != row; i++) {\n if (row == tableau.getBasicRow(i)) {\n if (i < minIndex) {\n minIndex = i;\n minRow = row;\n }\n }\n }\n }\n return minRow;\n }\n }\n return minRatioPositions.get(0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-28"}} {"sample_uid": "defects4j_function_repair::Closure-128", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean isSimpleNumber(String s) {\n int len = s.length();\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len > 0 && s.charAt(0) != '0';\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean isSimpleNumber(String s) {\n int len = s.length();\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len > 0 && s.charAt(0) != '0';\n }\n"}, "reference": " static boolean isSimpleNumber(String s) {\n int len = s.length();\n if (len == 0) {\n return false;\n }\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len == 1 || s.charAt(0) != '0';\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-128"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-128"}} {"sample_uid": "defects4j_function_repair::Compress-37", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Map parsePaxHeaders(final InputStream i)\n throws IOException {\n final Map headers = new HashMap(globalPaxHeaders);\n while(true){ \n int ch;\n int len = 0;\n int read = 0;\n while((ch = i.read()) != -1) {\n read++;\n if (ch == ' '){\n final ByteArrayOutputStream coll = new ByteArrayOutputStream();\n while((ch = i.read()) != -1) {\n read++;\n if (ch == '='){ \n final String keyword = coll.toString(CharsetNames.UTF_8);\n final int restLen = len - read;\n if (restLen == 1) { \n headers.remove(keyword);\n } else {\n final byte[] rest = new byte[restLen];\n final int got = IOUtils.readFully(i, rest);\n if (got != restLen) {\n throw new IOException(\"Failed to read \"\n + \"Paxheader. Expected \"\n + restLen\n + \" bytes, read \"\n + got);\n }\n final String value = new String(rest, 0,\n restLen - 1, CharsetNames.UTF_8);\n headers.put(keyword, value);\n }\n break;\n }\n coll.write((byte) ch);\n }\n break; \n }\n len *= 10;\n len += ch - '0';\n }\n if (ch == -1){ \n break;\n }\n }\n return headers;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Map parsePaxHeaders(final InputStream i)\n throws IOException {\n final Map headers = new HashMap(globalPaxHeaders);\n while(true){ \n int ch;\n int len = 0;\n int read = 0;\n while((ch = i.read()) != -1) {\n read++;\n if (ch == ' '){\n final ByteArrayOutputStream coll = new ByteArrayOutputStream();\n while((ch = i.read()) != -1) {\n read++;\n if (ch == '='){ \n final String keyword = coll.toString(CharsetNames.UTF_8);\n final int restLen = len - read;\n if (restLen == 1) { \n headers.remove(keyword);\n } else {\n final byte[] rest = new byte[restLen];\n final int got = IOUtils.readFully(i, rest);\n if (got != restLen) {\n throw new IOException(\"Failed to read \"\n + \"Paxheader. Expected \"\n + restLen\n + \" bytes, read \"\n + got);\n }\n final String value = new String(rest, 0,\n restLen - 1, CharsetNames.UTF_8);\n headers.put(keyword, value);\n }\n break;\n }\n coll.write((byte) ch);\n }\n break; \n }\n len *= 10;\n len += ch - '0';\n }\n if (ch == -1){ \n break;\n }\n }\n return headers;\n }\n"}, "reference": " Map parsePaxHeaders(final InputStream i)\n throws IOException {\n final Map headers = new HashMap(globalPaxHeaders);\n while(true){ \n int ch;\n int len = 0;\n int read = 0;\n while((ch = i.read()) != -1) {\n read++;\n if (ch == '\\n') { \n break;\n } else if (ch == ' '){ \n final ByteArrayOutputStream coll = new ByteArrayOutputStream();\n while((ch = i.read()) != -1) {\n read++;\n if (ch == '='){ \n final String keyword = coll.toString(CharsetNames.UTF_8);\n final int restLen = len - read;\n if (restLen == 1) { \n headers.remove(keyword);\n } else {\n final byte[] rest = new byte[restLen];\n final int got = IOUtils.readFully(i, rest);\n if (got != restLen) {\n throw new IOException(\"Failed to read \"\n + \"Paxheader. Expected \"\n + restLen\n + \" bytes, read \"\n + got);\n }\n final String value = new String(rest, 0,\n restLen - 1, CharsetNames.UTF_8);\n headers.put(keyword, value);\n }\n break;\n }\n coll.write((byte) ch);\n }\n break; \n }\n len *= 10;\n len += ch - '0';\n }\n if (ch == -1){ \n break;\n }\n }\n return headers;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-37"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-37"}} {"sample_uid": "defects4j_function_repair::Compress-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String parseName(byte[] buffer, final int offset, final int length) {\n StringBuffer result = new StringBuffer(length);\n int end = offset + length;\n for (int i = offset; i < end; ++i) {\n if (buffer[i] == 0) {\n break;\n }\n result.append((char) buffer[i]);\n }\n return result.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String parseName(byte[] buffer, final int offset, final int length) {\n StringBuffer result = new StringBuffer(length);\n int end = offset + length;\n for (int i = offset; i < end; ++i) {\n if (buffer[i] == 0) {\n break;\n }\n result.append((char) buffer[i]);\n }\n return result.toString();\n }\n"}, "reference": " public static String parseName(byte[] buffer, final int offset, final int length) {\n StringBuffer result = new StringBuffer(length);\n int end = offset + length;\n for (int i = offset; i < end; ++i) {\n byte b = buffer[i];\n if (b == 0) { \n break;\n }\n result.append((char) (b & 0xFF)); \n }\n return result.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-7"}} {"sample_uid": "defects4j_function_repair::Cli-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void checkRequiredOptions()\n throws MissingOptionException\n {\n if (requiredOptions.size() > 0)\n {\n Iterator iter = requiredOptions.iterator();\n StringBuffer buff = new StringBuffer();\n while (iter.hasNext())\n {\n buff.append(iter.next());\n }\n throw new MissingOptionException(buff.toString());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void checkRequiredOptions()\n throws MissingOptionException\n {\n if (requiredOptions.size() > 0)\n {\n Iterator iter = requiredOptions.iterator();\n StringBuffer buff = new StringBuffer();\n while (iter.hasNext())\n {\n buff.append(iter.next());\n }\n throw new MissingOptionException(buff.toString());\n }\n }\n"}, "reference": " private void checkRequiredOptions()\n throws MissingOptionException\n {\n if (requiredOptions.size() > 0)\n {\n Iterator iter = requiredOptions.iterator();\n StringBuffer buff = new StringBuffer(\"Missing required option\");\n buff.append(requiredOptions.size() == 1 ? \"\" : \"s\");\n buff.append(\": \");\n while (iter.hasNext())\n {\n buff.append(iter.next());\n }\n throw new MissingOptionException(buff.toString());\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-4"}} {"sample_uid": "defects4j_function_repair::Time-16", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, iDefaultYear);\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, iDefaultYear);\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n"}, "reference": " public int parseInto(ReadWritableInstant instant, String text, int position) {\n DateTimeParser parser = requireParser();\n if (instant == null) {\n throw new IllegalArgumentException(\"Instant must not be null\");\n }\n long instantMillis = instant.getMillis();\n Chronology chrono = instant.getChronology();\n long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis);\n chrono = selectChronology(chrono);\n DateTimeParserBucket bucket = new DateTimeParserBucket(\n instantLocal, chrono, iLocale, iPivotYear, chrono.year().get(instantLocal));\n int newPos = parser.parseInto(bucket, text, position);\n instant.setMillis(bucket.computeMillis(false, text));\n if (iOffsetParsed && bucket.getOffsetInteger() != null) {\n int parsedOffset = bucket.getOffsetInteger();\n DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);\n chrono = chrono.withZone(parsedZone);\n } else if (bucket.getZone() != null) {\n chrono = chrono.withZone(bucket.getZone());\n }\n instant.setChronology(chrono);\n if (iZone != null) {\n instant.setZone(iZone);\n }\n return newPos;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-16"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-16"}} {"sample_uid": "defects4j_function_repair::Jsoup-42", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public List formData() {\n ArrayList data = new ArrayList();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (\"select\".equals(el.tagName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val();\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public List formData() {\n ArrayList data = new ArrayList();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (\"select\".equals(el.tagName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val();\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n"}, "reference": " public List formData() {\n ArrayList data = new ArrayList();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n if (el.hasAttr(\"disabled\")) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (\"select\".equals(el.tagName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val().length() > 0 ? el.val() : \"on\";\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-42"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-42"}} {"sample_uid": "defects4j_function_repair::Closure-166", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void matchConstraint(JSType constraint) {\n if (hasReferenceName()) {\n return;\n }\n if (constraint.isRecordType()) {\n matchRecordTypeConstraint(constraint.toObjectType());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void matchConstraint(JSType constraint) {\n if (hasReferenceName()) {\n return;\n }\n if (constraint.isRecordType()) {\n matchRecordTypeConstraint(constraint.toObjectType());\n }\n }\n"}, "reference": " public void matchConstraint(JSType constraint) {\n if (hasReferenceName()) {\n return;\n }\n if (constraint.isRecordType()) {\n matchRecordTypeConstraint(constraint.toObjectType());\n } else if (constraint.isUnionType()) {\n for (JSType alt : constraint.toMaybeUnionType().getAlternates()) {\n if (alt.isRecordType()) {\n matchRecordTypeConstraint(alt.toObjectType());\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-166"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-166"}} {"sample_uid": "defects4j_function_repair::Closure-87", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isFoldableExpressBlock(Node n) {\n if (n.getType() == Token.BLOCK) {\n if (n.hasOneChild()) {\n Node maybeExpr = n.getFirstChild();\n return NodeUtil.isExpressionNode(maybeExpr);\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isFoldableExpressBlock(Node n) {\n if (n.getType() == Token.BLOCK) {\n if (n.hasOneChild()) {\n Node maybeExpr = n.getFirstChild();\n return NodeUtil.isExpressionNode(maybeExpr);\n }\n }\n return false;\n }\n"}, "reference": " private boolean isFoldableExpressBlock(Node n) {\n if (n.getType() == Token.BLOCK) {\n if (n.hasOneChild()) {\n Node maybeExpr = n.getFirstChild();\n if (maybeExpr.getType() == Token.EXPR_RESULT) {\n if (maybeExpr.getFirstChild().getType() == Token.CALL) {\n Node calledFn = maybeExpr.getFirstChild().getFirstChild();\n if (calledFn.getType() == Token.GETELEM) {\n return false;\n } else if (calledFn.getType() == Token.GETPROP &&\n calledFn.getLastChild().getString().startsWith(\"on\")) {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-87"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-87"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-107", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId);\n if (actual == null) { \n return null;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n if (!type.hasGenericTypes()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId);\n if (actual == null) { \n return null;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n if (!type.hasGenericTypes()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n"}, "reference": " protected final JsonDeserializer _findDeserializer(DeserializationContext ctxt,\n String typeId) throws IOException\n {\n JsonDeserializer deser = _deserializers.get(typeId);\n if (deser == null) {\n JavaType type = _idResolver.typeFromId(ctxt, typeId);\n if (type == null) {\n deser = _findDefaultImplDeserializer(ctxt);\n if (deser == null) {\n JavaType actual = _handleUnknownTypeId(ctxt, typeId);\n if (actual == null) { \n return NullifyingDeserializer.instance;\n }\n deser = ctxt.findContextualValueDeserializer(actual, _property);\n }\n } else {\n if ((_baseType != null)\n && _baseType.getClass() == type.getClass()) {\n if (!type.hasGenericTypes()) {\n type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());\n }\n }\n deser = ctxt.findContextualValueDeserializer(type, _property);\n }\n _deserializers.put(typeId, deser);\n }\n return deser;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-107"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-107"}} {"sample_uid": "defects4j_function_repair::Jsoup-62", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {\n String name = t.asEndTag().normalName();\n ArrayList stack = tb.getStack();\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (node.nodeName().equals(name)) {\n tb.generateImpliedEndTags(name);\n if (!name.equals(tb.currentElement().nodeName()))\n tb.error(this);\n tb.popStackToClose(name);\n break;\n } else {\n if (tb.isSpecial(node)) {\n tb.error(this);\n return false;\n }\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {\n String name = t.asEndTag().normalName();\n ArrayList stack = tb.getStack();\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (node.nodeName().equals(name)) {\n tb.generateImpliedEndTags(name);\n if (!name.equals(tb.currentElement().nodeName()))\n tb.error(this);\n tb.popStackToClose(name);\n break;\n } else {\n if (tb.isSpecial(node)) {\n tb.error(this);\n return false;\n }\n }\n }\n return true;\n }\n"}, "reference": " boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {\n String name = t.asEndTag().name(); \n ArrayList stack = tb.getStack();\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (node.nodeName().equals(name)) {\n tb.generateImpliedEndTags(name);\n if (!name.equals(tb.currentElement().nodeName()))\n tb.error(this);\n tb.popStackToClose(name);\n break;\n } else {\n if (tb.isSpecial(node)) {\n tb.error(this);\n return false;\n }\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-62"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-62"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-37", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n return new SimpleType(subclass, _bindings, _superClass, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n return new SimpleType(subclass, _bindings, _superClass, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n"}, "reference": " protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n return new SimpleType(subclass, _bindings, this, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-37"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-37"}} {"sample_uid": "defects4j_function_repair::Math-51", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n default:\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n default:\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n"}, "reference": " protected final double doSolve() {\n double x0 = getMin();\n double x1 = getMax();\n double f0 = computeObjectiveValue(x0);\n double f1 = computeObjectiveValue(x1);\n if (f0 == 0.0) {\n return x0;\n }\n if (f1 == 0.0) {\n return x1;\n }\n verifyBracketing(x0, x1);\n final double ftol = getFunctionValueAccuracy();\n final double atol = getAbsoluteAccuracy();\n final double rtol = getRelativeAccuracy();\n boolean inverted = false;\n while (true) {\n final double x = x1 - ((f1 * (x1 - x0)) / (f1 - f0));\n final double fx = computeObjectiveValue(x);\n if (fx == 0.0) {\n return x;\n }\n if (f1 * fx < 0) {\n x0 = x1;\n f0 = f1;\n inverted = !inverted;\n } else {\n switch (method) {\n case ILLINOIS:\n f0 *= 0.5;\n break;\n case PEGASUS:\n f0 *= f1 / (f1 + fx);\n break;\n case REGULA_FALSI:\n if (x == x1) {\n final double delta = FastMath.max(rtol * FastMath.abs(x1),\n atol);\n x0 = 0.5 * (x0 + x1 - delta);\n f0 = computeObjectiveValue(x0);\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n x1 = x;\n f1 = fx;\n if (FastMath.abs(f1) <= ftol) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n if (inverted) {\n return x1;\n }\n break;\n case RIGHT_SIDE:\n if (!inverted) {\n return x1;\n }\n break;\n case BELOW_SIDE:\n if (f1 <= 0) {\n return x1;\n }\n break;\n case ABOVE_SIDE:\n if (f1 >= 0) {\n return x1;\n }\n break;\n default:\n throw new MathInternalError();\n }\n }\n if (FastMath.abs(x1 - x0) < FastMath.max(rtol * FastMath.abs(x1),\n atol)) {\n switch (allowed) {\n case ANY_SIDE:\n return x1;\n case LEFT_SIDE:\n return inverted ? x1 : x0;\n case RIGHT_SIDE:\n return inverted ? x0 : x1;\n case BELOW_SIDE:\n return (f1 <= 0) ? x1 : x0;\n case ABOVE_SIDE:\n return (f1 >= 0) ? x1 : x0;\n default:\n throw new MathInternalError();\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-51"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-51"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-100", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public byte[] getBinaryValue(Base64Variant b64variant)\n throws IOException, JsonParseException\n {\n JsonNode n = currentNode();\n if (n != null) {\n byte[] data = n.binaryValue();\n if (data != null) {\n return data;\n }\n if (n.isPojo()) {\n Object ob = ((POJONode) n).getPojo();\n if (ob instanceof byte[]) {\n return (byte[]) ob;\n }\n }\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public byte[] getBinaryValue(Base64Variant b64variant)\n throws IOException, JsonParseException\n {\n JsonNode n = currentNode();\n if (n != null) {\n byte[] data = n.binaryValue();\n if (data != null) {\n return data;\n }\n if (n.isPojo()) {\n Object ob = ((POJONode) n).getPojo();\n if (ob instanceof byte[]) {\n return (byte[]) ob;\n }\n }\n }\n return null;\n }\n"}, "reference": " public byte[] getBinaryValue(Base64Variant b64variant)\n throws IOException, JsonParseException\n {\n JsonNode n = currentNode();\n if (n != null) {\n if (n instanceof TextNode) {\n return ((TextNode) n).getBinaryValue(b64variant);\n }\n return n.binaryValue();\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-100"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-100"}} {"sample_uid": "defects4j_function_repair::Time-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int parseInto(DateTimeParserBucket bucket, String text, int position) {\n String str = text.substring(position);\n for (String id : ALL_IDS) {\n if (str.startsWith(id)) {\n bucket.setZone(DateTimeZone.forID(id));\n return position + id.length();\n }\n }\n return ~position;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int parseInto(DateTimeParserBucket bucket, String text, int position) {\n String str = text.substring(position);\n for (String id : ALL_IDS) {\n if (str.startsWith(id)) {\n bucket.setZone(DateTimeZone.forID(id));\n return position + id.length();\n }\n }\n return ~position;\n }\n"}, "reference": " public int parseInto(DateTimeParserBucket bucket, String text, int position) {\n String str = text.substring(position);\n String best = null;\n for (String id : ALL_IDS) {\n if (str.startsWith(id)) {\n \tif (best == null || id.length() > best.length()) {\n \t\tbest = id;\n \t}\n }\n }\n if (best != null) {\n bucket.setZone(DateTimeZone.forID(best));\n return position + best.length();\n }\n return ~position;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-20"}} {"sample_uid": "defects4j_function_repair::Jsoup-68", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {\n int bottom = stack.size() -1;\n if (bottom > MaxScopeSearchDepth) {\n bottom = MaxScopeSearchDepth;\n }\n final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;\n for (int pos = bottom; pos >= top; pos--) {\n final String elName = stack.get(pos).nodeName();\n if (inSorted(elName, targetNames))\n return true;\n if (inSorted(elName, baseTypes))\n return false;\n if (extraTypes != null && inSorted(elName, extraTypes))\n return false;\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {\n int bottom = stack.size() -1;\n if (bottom > MaxScopeSearchDepth) {\n bottom = MaxScopeSearchDepth;\n }\n final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;\n for (int pos = bottom; pos >= top; pos--) {\n final String elName = stack.get(pos).nodeName();\n if (inSorted(elName, targetNames))\n return true;\n if (inSorted(elName, baseTypes))\n return false;\n if (extraTypes != null && inSorted(elName, extraTypes))\n return false;\n }\n return false;\n }\n"}, "reference": " private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {\n final int bottom = stack.size() -1;\n final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;\n for (int pos = bottom; pos >= top; pos--) {\n final String elName = stack.get(pos).nodeName();\n if (inSorted(elName, targetNames))\n return true;\n if (inSorted(elName, baseTypes))\n return false;\n if (extraTypes != null && inSorted(elName, extraTypes))\n return false;\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-68"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-68"}} {"sample_uid": "defects4j_function_repair::Jsoup-51", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean matchesLetter() {\n if (isEmpty())\n return false;\n char c = input[pos];\n return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean matchesLetter() {\n if (isEmpty())\n return false;\n char c = input[pos];\n return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');\n }\n"}, "reference": " boolean matchesLetter() {\n if (isEmpty())\n return false;\n char c = input[pos];\n return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-51"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-51"}} {"sample_uid": "defects4j_function_repair::Gson-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static Type getSupertype(Type context, Class contextRawType, Class supertype) {\n checkArgument(supertype.isAssignableFrom(contextRawType));\n return resolve(context, contextRawType,\n $Gson$Types.getGenericSupertype(context, contextRawType, supertype));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static Type getSupertype(Type context, Class contextRawType, Class supertype) {\n checkArgument(supertype.isAssignableFrom(contextRawType));\n return resolve(context, contextRawType,\n $Gson$Types.getGenericSupertype(context, contextRawType, supertype));\n }\n"}, "reference": " static Type getSupertype(Type context, Class contextRawType, Class supertype) {\n if (context instanceof WildcardType) {\n context = ((WildcardType)context).getUpperBounds()[0];\n }\n checkArgument(supertype.isAssignableFrom(contextRawType));\n return resolve(context, contextRawType,\n $Gson$Types.getGenericSupertype(context, contextRawType, supertype));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-18"}} {"sample_uid": "defects4j_function_repair::Closure-88", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private VariableLiveness isVariableReadBeforeKill(\n Node n, String variable) {\n if (NodeUtil.isName(n) && variable.equals(n.getString())) {\n if (NodeUtil.isLhs(n, n.getParent())) {\n return VariableLiveness.KILL;\n } else {\n return VariableLiveness.READ;\n }\n }\n for (Node child = n.getFirstChild();\n child != null; child = child.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { \n VariableLiveness state = isVariableReadBeforeKill(child, variable);\n if (state != VariableLiveness.MAYBE_LIVE) {\n return state;\n }\n }\n }\n return VariableLiveness.MAYBE_LIVE;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private VariableLiveness isVariableReadBeforeKill(\n Node n, String variable) {\n if (NodeUtil.isName(n) && variable.equals(n.getString())) {\n if (NodeUtil.isLhs(n, n.getParent())) {\n return VariableLiveness.KILL;\n } else {\n return VariableLiveness.READ;\n }\n }\n for (Node child = n.getFirstChild();\n child != null; child = child.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { \n VariableLiveness state = isVariableReadBeforeKill(child, variable);\n if (state != VariableLiveness.MAYBE_LIVE) {\n return state;\n }\n }\n }\n return VariableLiveness.MAYBE_LIVE;\n }\n"}, "reference": " private VariableLiveness isVariableReadBeforeKill(\n Node n, String variable) {\n if (NodeUtil.isName(n) && variable.equals(n.getString())) {\n if (NodeUtil.isLhs(n, n.getParent())) {\n Preconditions.checkState(n.getParent().getType() == Token.ASSIGN);\n Node rhs = n.getNext();\n VariableLiveness state = isVariableReadBeforeKill(rhs, variable);\n if (state == VariableLiveness.READ) {\n return state;\n }\n return VariableLiveness.KILL;\n } else {\n return VariableLiveness.READ;\n }\n }\n for (Node child = n.getFirstChild();\n child != null; child = child.getNext()) {\n if (!ControlFlowGraph.isEnteringNewCfgNode(child)) { \n VariableLiveness state = isVariableReadBeforeKill(child, variable);\n if (state != VariableLiveness.MAYBE_LIVE) {\n return state;\n }\n }\n }\n return VariableLiveness.MAYBE_LIVE;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-88"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-88"}} {"sample_uid": "defects4j_function_repair::Closure-123", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void add(Node n, Context context) {\n if (!cc.continueProcessing()) {\n return;\n }\n int type = n.getType();\n String opstr = NodeUtil.opToStr(type);\n int childCount = n.getChildCount();\n Node first = n.getFirstChild();\n Node last = n.getLastChild();\n if (opstr != null && first != last) {\n Preconditions.checkState(\n childCount == 2,\n \"Bad binary operator \\\"%s\\\": expected 2 arguments but got %s\",\n opstr, childCount);\n int p = NodeUtil.precedence(type);\n Context rhsContext = getContextForNoInOperator(context);\n if (last.getType() == type &&\n NodeUtil.isAssociative(type)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else {\n unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);\n }\n return;\n }\n cc.startSourceMapping(n);\n switch (type) {\n case Token.TRY: {\n Preconditions.checkState(first.getNext().isBlock() &&\n !first.getNext().hasMoreThanOneChild());\n Preconditions.checkState(childCount >= 2 && childCount <= 3);\n add(\"try\");\n add(first, Context.PRESERVE_BLOCK);\n Node catchblock = first.getNext().getFirstChild();\n if (catchblock != null) {\n add(catchblock);\n }\n if (childCount == 3) {\n add(\"finally\");\n add(last, Context.PRESERVE_BLOCK);\n }\n break;\n }\n case Token.CATCH:\n Preconditions.checkState(childCount == 2);\n add(\"catch(\");\n add(first);\n add(\")\");\n add(last, Context.PRESERVE_BLOCK);\n break;\n case Token.THROW:\n Preconditions.checkState(childCount == 1);\n add(\"throw\");\n add(first);\n cc.endStatement(true);\n break;\n case Token.RETURN:\n add(\"return\");\n if (childCount == 1) {\n add(first);\n } else {\n Preconditions.checkState(childCount == 0);\n }\n cc.endStatement();\n break;\n case Token.VAR:\n if (first != null) {\n add(\"var \");\n addList(first, false, getContextForNoInOperator(context));\n }\n break;\n case Token.LABEL_NAME:\n Preconditions.checkState(!n.getString().isEmpty());\n addIdentifier(n.getString());\n break;\n case Token.NAME:\n if (first == null || first.isEmpty()) {\n addIdentifier(n.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n addIdentifier(n.getString());\n cc.addOp(\"=\", true);\n if (first.isComma()) {\n addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);\n } else {\n addExpr(first, 0, getContextForNoInOperator(context));\n }\n }\n break;\n case Token.ARRAYLIT:\n add(\"[\");\n addArrayList(first);\n add(\"]\");\n break;\n case Token.PARAM_LIST:\n add(\"(\");\n addList(first);\n add(\")\");\n break;\n case Token.COMMA:\n Preconditions.checkState(childCount == 2);\n unrollBinaryOperator(n, Token.COMMA, \",\", context,\n getContextForNoInOperator(context), 0, 0);\n break;\n case Token.NUMBER:\n Preconditions.checkState(childCount == 0);\n cc.addNumber(n.getDouble());\n break;\n case Token.TYPEOF:\n case Token.VOID:\n case Token.NOT:\n case Token.BITNOT:\n case Token.POS: {\n Preconditions.checkState(childCount == 1);\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n break;\n }\n case Token.NEG: {\n Preconditions.checkState(childCount == 1);\n if (n.getFirstChild().isNumber()) {\n cc.addNumber(-n.getFirstChild().getDouble());\n } else {\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n }\n break;\n }\n case Token.HOOK: {\n Preconditions.checkState(childCount == 3);\n int p = NodeUtil.precedence(type);\n Context rhsContext = Context.OTHER;\n addExpr(first, p + 1, context);\n cc.addOp(\"?\", true);\n addExpr(first.getNext(), 1, rhsContext);\n cc.addOp(\":\", true);\n addExpr(last, 1, rhsContext);\n break;\n }\n case Token.REGEXP:\n if (!first.isString() ||\n !last.isString()) {\n throw new Error(\"Expected children to be strings\");\n }\n String regexp = regexpEscape(first.getString(), outputCharsetEncoder);\n if (childCount == 2) {\n add(regexp + last.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n add(regexp);\n }\n break;\n case Token.FUNCTION:\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n Preconditions.checkState(childCount == 3);\n boolean funcNeedsParens = (context == Context.START_OF_EXPR);\n if (funcNeedsParens) {\n add(\"(\");\n }\n add(\"function\");\n add(first);\n add(first.getNext());\n add(last, Context.PRESERVE_BLOCK);\n cc.endFunction(context == Context.STATEMENT);\n if (funcNeedsParens) {\n add(\")\");\n }\n break;\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n Preconditions.checkState(n.getParent().isObjectLit());\n Preconditions.checkState(childCount == 1);\n Preconditions.checkState(first.isFunction());\n Preconditions.checkState(first.getFirstChild().getString().isEmpty());\n if (type == Token.GETTER_DEF) {\n Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());\n add(\"get \");\n } else {\n Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());\n add(\"set \");\n }\n String name = n.getString();\n Node fn = first;\n Node parameters = fn.getChildAtIndex(1);\n Node body = fn.getLastChild();\n if (!n.isQuotedString() &&\n TokenStream.isJSIdentifier(name) &&\n NodeUtil.isLatin(name)) {\n add(name);\n } else {\n double d = getSimpleNumber(name);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addJsString(n);\n }\n }\n add(parameters);\n add(body, Context.PRESERVE_BLOCK);\n break;\n case Token.SCRIPT:\n case Token.BLOCK: {\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n boolean preserveBlock = context == Context.PRESERVE_BLOCK;\n if (preserveBlock) {\n cc.beginBlock();\n }\n boolean preferLineBreaks =\n type == Token.SCRIPT ||\n (type == Token.BLOCK &&\n !preserveBlock &&\n n.getParent() != null &&\n n.getParent().isScript());\n for (Node c = first; c != null; c = c.getNext()) {\n add(c, Context.STATEMENT);\n if (c.isVar()) {\n cc.endStatement();\n }\n if (c.isFunction()) {\n cc.maybeLineBreak();\n }\n if (preferLineBreaks) {\n cc.notePreferredLineBreak();\n }\n }\n if (preserveBlock) {\n cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));\n }\n break;\n }\n case Token.FOR:\n if (childCount == 4) {\n add(\"for(\");\n if (first.isVar()) {\n add(first, Context.IN_FOR_INIT_CLAUSE);\n } else {\n addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);\n }\n add(\";\");\n add(first.getNext());\n add(\";\");\n add(first.getNext().getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n Preconditions.checkState(childCount == 3);\n add(\"for(\");\n add(first);\n add(\"in\");\n add(first.getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n }\n break;\n case Token.DO:\n Preconditions.checkState(childCount == 2);\n add(\"do\");\n addNonEmptyStatement(first, Context.OTHER, false);\n add(\"while(\");\n add(last);\n add(\")\");\n cc.endStatement();\n break;\n case Token.WHILE:\n Preconditions.checkState(childCount == 2);\n add(\"while(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.EMPTY:\n Preconditions.checkState(childCount == 0);\n break;\n case Token.GETPROP: {\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETPROP: expected 2 children, but got %s\", childCount);\n Preconditions.checkState(\n last.isString(),\n \"Bad GETPROP: RHS should be STRING\");\n boolean needsParens = (first.isNumber());\n if (needsParens) {\n add(\"(\");\n }\n addExpr(first, NodeUtil.precedence(type), context);\n if (needsParens) {\n add(\")\");\n }\n if (this.languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(last.getString())) {\n add(\"[\");\n add(last);\n add(\"]\");\n } else {\n add(\".\");\n addIdentifier(last.getString());\n }\n break;\n }\n case Token.GETELEM:\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETELEM: expected 2 children but got %s\", childCount);\n addExpr(first, NodeUtil.precedence(type), context);\n add(\"[\");\n add(first.getNext());\n add(\"]\");\n break;\n case Token.WITH:\n Preconditions.checkState(childCount == 2);\n add(\"with(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.INC:\n case Token.DEC: {\n Preconditions.checkState(childCount == 1);\n String o = type == Token.INC ? \"++\" : \"--\";\n int postProp = n.getIntProp(Node.INCRDECR_PROP);\n if (postProp != 0) {\n addExpr(first, NodeUtil.precedence(type), context);\n cc.addOp(o, false);\n } else {\n cc.addOp(o, false);\n add(first);\n }\n break;\n }\n case Token.CALL:\n if (isIndirectEval(first)\n || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {\n add(\"(0,\");\n addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);\n add(\")\");\n } else {\n addExpr(first, NodeUtil.precedence(type), context);\n }\n add(\"(\");\n addList(first.getNext());\n add(\")\");\n break;\n case Token.IF:\n boolean hasElse = childCount == 3;\n boolean ambiguousElseClause =\n context == Context.BEFORE_DANGLING_ELSE && !hasElse;\n if (ambiguousElseClause) {\n cc.beginBlock();\n }\n add(\"if(\");\n add(first);\n add(\")\");\n if (hasElse) {\n addNonEmptyStatement(\n first.getNext(), Context.BEFORE_DANGLING_ELSE, false);\n add(\"else\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n addNonEmptyStatement(first.getNext(), Context.OTHER, false);\n Preconditions.checkState(childCount == 2);\n }\n if (ambiguousElseClause) {\n cc.endBlock();\n }\n break;\n case Token.NULL:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"null\");\n break;\n case Token.THIS:\n Preconditions.checkState(childCount == 0);\n add(\"this\");\n break;\n case Token.FALSE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"false\");\n break;\n case Token.TRUE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"true\");\n break;\n case Token.CONTINUE:\n Preconditions.checkState(childCount <= 1);\n add(\"continue\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.DEBUGGER:\n Preconditions.checkState(childCount == 0);\n add(\"debugger\");\n cc.endStatement();\n break;\n case Token.BREAK:\n Preconditions.checkState(childCount <= 1);\n add(\"break\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.EXPR_RESULT:\n Preconditions.checkState(childCount == 1);\n add(first, Context.START_OF_EXPR);\n cc.endStatement();\n break;\n case Token.NEW:\n add(\"new \");\n int precedence = NodeUtil.precedence(type);\n if (NodeUtil.containsType(\n first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {\n precedence = NodeUtil.precedence(first.getType()) + 1;\n }\n addExpr(first, precedence, Context.OTHER);\n Node next = first.getNext();\n if (next != null) {\n add(\"(\");\n addList(next);\n add(\")\");\n }\n break;\n case Token.STRING_KEY:\n Preconditions.checkState(\n childCount == 1, \"Object lit key must have 1 child\");\n addJsString(n);\n break;\n case Token.STRING:\n Preconditions.checkState(\n childCount == 0, \"A string may not have children\");\n addJsString(n);\n break;\n case Token.DELPROP:\n Preconditions.checkState(childCount == 1);\n add(\"delete \");\n add(first);\n break;\n case Token.OBJECTLIT: {\n boolean needsParens = (context == Context.START_OF_EXPR);\n if (needsParens) {\n add(\"(\");\n }\n add(\"{\");\n for (Node c = first; c != null; c = c.getNext()) {\n if (c != first) {\n cc.listSeparator();\n }\n if (c.isGetterDef() || c.isSetterDef()) {\n add(c);\n } else {\n Preconditions.checkState(c.isStringKey());\n String key = c.getString();\n if (!c.isQuotedString()\n && !(languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(key))\n && TokenStream.isJSIdentifier(key)\n && NodeUtil.isLatin(key)) {\n add(key);\n } else {\n double d = getSimpleNumber(key);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addExpr(c, 1, Context.OTHER);\n }\n }\n add(\":\");\n addExpr(c.getFirstChild(), 1, Context.OTHER);\n }\n }\n add(\"}\");\n if (needsParens) {\n add(\")\");\n }\n break;\n }\n case Token.SWITCH:\n add(\"switch(\");\n add(first);\n add(\")\");\n cc.beginBlock();\n addAllSiblings(first.getNext());\n cc.endBlock(context == Context.STATEMENT);\n break;\n case Token.CASE:\n Preconditions.checkState(childCount == 2);\n add(\"case \");\n add(first);\n addCaseBody(last);\n break;\n case Token.DEFAULT_CASE:\n Preconditions.checkState(childCount == 1);\n add(\"default\");\n addCaseBody(first);\n break;\n case Token.LABEL:\n Preconditions.checkState(childCount == 2);\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(first);\n add(\":\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), true);\n break;\n case Token.CAST:\n add(\"(\");\n add(first);\n add(\")\");\n break;\n default:\n throw new Error(\"Unknown type \" + type + \"\\n\" + n.toStringTree());\n }\n cc.endSourceMapping(n);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void add(Node n, Context context) {\n if (!cc.continueProcessing()) {\n return;\n }\n int type = n.getType();\n String opstr = NodeUtil.opToStr(type);\n int childCount = n.getChildCount();\n Node first = n.getFirstChild();\n Node last = n.getLastChild();\n if (opstr != null && first != last) {\n Preconditions.checkState(\n childCount == 2,\n \"Bad binary operator \\\"%s\\\": expected 2 arguments but got %s\",\n opstr, childCount);\n int p = NodeUtil.precedence(type);\n Context rhsContext = getContextForNoInOperator(context);\n if (last.getType() == type &&\n NodeUtil.isAssociative(type)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else {\n unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);\n }\n return;\n }\n cc.startSourceMapping(n);\n switch (type) {\n case Token.TRY: {\n Preconditions.checkState(first.getNext().isBlock() &&\n !first.getNext().hasMoreThanOneChild());\n Preconditions.checkState(childCount >= 2 && childCount <= 3);\n add(\"try\");\n add(first, Context.PRESERVE_BLOCK);\n Node catchblock = first.getNext().getFirstChild();\n if (catchblock != null) {\n add(catchblock);\n }\n if (childCount == 3) {\n add(\"finally\");\n add(last, Context.PRESERVE_BLOCK);\n }\n break;\n }\n case Token.CATCH:\n Preconditions.checkState(childCount == 2);\n add(\"catch(\");\n add(first);\n add(\")\");\n add(last, Context.PRESERVE_BLOCK);\n break;\n case Token.THROW:\n Preconditions.checkState(childCount == 1);\n add(\"throw\");\n add(first);\n cc.endStatement(true);\n break;\n case Token.RETURN:\n add(\"return\");\n if (childCount == 1) {\n add(first);\n } else {\n Preconditions.checkState(childCount == 0);\n }\n cc.endStatement();\n break;\n case Token.VAR:\n if (first != null) {\n add(\"var \");\n addList(first, false, getContextForNoInOperator(context));\n }\n break;\n case Token.LABEL_NAME:\n Preconditions.checkState(!n.getString().isEmpty());\n addIdentifier(n.getString());\n break;\n case Token.NAME:\n if (first == null || first.isEmpty()) {\n addIdentifier(n.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n addIdentifier(n.getString());\n cc.addOp(\"=\", true);\n if (first.isComma()) {\n addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);\n } else {\n addExpr(first, 0, getContextForNoInOperator(context));\n }\n }\n break;\n case Token.ARRAYLIT:\n add(\"[\");\n addArrayList(first);\n add(\"]\");\n break;\n case Token.PARAM_LIST:\n add(\"(\");\n addList(first);\n add(\")\");\n break;\n case Token.COMMA:\n Preconditions.checkState(childCount == 2);\n unrollBinaryOperator(n, Token.COMMA, \",\", context,\n getContextForNoInOperator(context), 0, 0);\n break;\n case Token.NUMBER:\n Preconditions.checkState(childCount == 0);\n cc.addNumber(n.getDouble());\n break;\n case Token.TYPEOF:\n case Token.VOID:\n case Token.NOT:\n case Token.BITNOT:\n case Token.POS: {\n Preconditions.checkState(childCount == 1);\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n break;\n }\n case Token.NEG: {\n Preconditions.checkState(childCount == 1);\n if (n.getFirstChild().isNumber()) {\n cc.addNumber(-n.getFirstChild().getDouble());\n } else {\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n }\n break;\n }\n case Token.HOOK: {\n Preconditions.checkState(childCount == 3);\n int p = NodeUtil.precedence(type);\n Context rhsContext = Context.OTHER;\n addExpr(first, p + 1, context);\n cc.addOp(\"?\", true);\n addExpr(first.getNext(), 1, rhsContext);\n cc.addOp(\":\", true);\n addExpr(last, 1, rhsContext);\n break;\n }\n case Token.REGEXP:\n if (!first.isString() ||\n !last.isString()) {\n throw new Error(\"Expected children to be strings\");\n }\n String regexp = regexpEscape(first.getString(), outputCharsetEncoder);\n if (childCount == 2) {\n add(regexp + last.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n add(regexp);\n }\n break;\n case Token.FUNCTION:\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n Preconditions.checkState(childCount == 3);\n boolean funcNeedsParens = (context == Context.START_OF_EXPR);\n if (funcNeedsParens) {\n add(\"(\");\n }\n add(\"function\");\n add(first);\n add(first.getNext());\n add(last, Context.PRESERVE_BLOCK);\n cc.endFunction(context == Context.STATEMENT);\n if (funcNeedsParens) {\n add(\")\");\n }\n break;\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n Preconditions.checkState(n.getParent().isObjectLit());\n Preconditions.checkState(childCount == 1);\n Preconditions.checkState(first.isFunction());\n Preconditions.checkState(first.getFirstChild().getString().isEmpty());\n if (type == Token.GETTER_DEF) {\n Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());\n add(\"get \");\n } else {\n Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());\n add(\"set \");\n }\n String name = n.getString();\n Node fn = first;\n Node parameters = fn.getChildAtIndex(1);\n Node body = fn.getLastChild();\n if (!n.isQuotedString() &&\n TokenStream.isJSIdentifier(name) &&\n NodeUtil.isLatin(name)) {\n add(name);\n } else {\n double d = getSimpleNumber(name);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addJsString(n);\n }\n }\n add(parameters);\n add(body, Context.PRESERVE_BLOCK);\n break;\n case Token.SCRIPT:\n case Token.BLOCK: {\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n boolean preserveBlock = context == Context.PRESERVE_BLOCK;\n if (preserveBlock) {\n cc.beginBlock();\n }\n boolean preferLineBreaks =\n type == Token.SCRIPT ||\n (type == Token.BLOCK &&\n !preserveBlock &&\n n.getParent() != null &&\n n.getParent().isScript());\n for (Node c = first; c != null; c = c.getNext()) {\n add(c, Context.STATEMENT);\n if (c.isVar()) {\n cc.endStatement();\n }\n if (c.isFunction()) {\n cc.maybeLineBreak();\n }\n if (preferLineBreaks) {\n cc.notePreferredLineBreak();\n }\n }\n if (preserveBlock) {\n cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));\n }\n break;\n }\n case Token.FOR:\n if (childCount == 4) {\n add(\"for(\");\n if (first.isVar()) {\n add(first, Context.IN_FOR_INIT_CLAUSE);\n } else {\n addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);\n }\n add(\";\");\n add(first.getNext());\n add(\";\");\n add(first.getNext().getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n Preconditions.checkState(childCount == 3);\n add(\"for(\");\n add(first);\n add(\"in\");\n add(first.getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n }\n break;\n case Token.DO:\n Preconditions.checkState(childCount == 2);\n add(\"do\");\n addNonEmptyStatement(first, Context.OTHER, false);\n add(\"while(\");\n add(last);\n add(\")\");\n cc.endStatement();\n break;\n case Token.WHILE:\n Preconditions.checkState(childCount == 2);\n add(\"while(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.EMPTY:\n Preconditions.checkState(childCount == 0);\n break;\n case Token.GETPROP: {\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETPROP: expected 2 children, but got %s\", childCount);\n Preconditions.checkState(\n last.isString(),\n \"Bad GETPROP: RHS should be STRING\");\n boolean needsParens = (first.isNumber());\n if (needsParens) {\n add(\"(\");\n }\n addExpr(first, NodeUtil.precedence(type), context);\n if (needsParens) {\n add(\")\");\n }\n if (this.languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(last.getString())) {\n add(\"[\");\n add(last);\n add(\"]\");\n } else {\n add(\".\");\n addIdentifier(last.getString());\n }\n break;\n }\n case Token.GETELEM:\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETELEM: expected 2 children but got %s\", childCount);\n addExpr(first, NodeUtil.precedence(type), context);\n add(\"[\");\n add(first.getNext());\n add(\"]\");\n break;\n case Token.WITH:\n Preconditions.checkState(childCount == 2);\n add(\"with(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.INC:\n case Token.DEC: {\n Preconditions.checkState(childCount == 1);\n String o = type == Token.INC ? \"++\" : \"--\";\n int postProp = n.getIntProp(Node.INCRDECR_PROP);\n if (postProp != 0) {\n addExpr(first, NodeUtil.precedence(type), context);\n cc.addOp(o, false);\n } else {\n cc.addOp(o, false);\n add(first);\n }\n break;\n }\n case Token.CALL:\n if (isIndirectEval(first)\n || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {\n add(\"(0,\");\n addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);\n add(\")\");\n } else {\n addExpr(first, NodeUtil.precedence(type), context);\n }\n add(\"(\");\n addList(first.getNext());\n add(\")\");\n break;\n case Token.IF:\n boolean hasElse = childCount == 3;\n boolean ambiguousElseClause =\n context == Context.BEFORE_DANGLING_ELSE && !hasElse;\n if (ambiguousElseClause) {\n cc.beginBlock();\n }\n add(\"if(\");\n add(first);\n add(\")\");\n if (hasElse) {\n addNonEmptyStatement(\n first.getNext(), Context.BEFORE_DANGLING_ELSE, false);\n add(\"else\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n addNonEmptyStatement(first.getNext(), Context.OTHER, false);\n Preconditions.checkState(childCount == 2);\n }\n if (ambiguousElseClause) {\n cc.endBlock();\n }\n break;\n case Token.NULL:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"null\");\n break;\n case Token.THIS:\n Preconditions.checkState(childCount == 0);\n add(\"this\");\n break;\n case Token.FALSE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"false\");\n break;\n case Token.TRUE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"true\");\n break;\n case Token.CONTINUE:\n Preconditions.checkState(childCount <= 1);\n add(\"continue\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.DEBUGGER:\n Preconditions.checkState(childCount == 0);\n add(\"debugger\");\n cc.endStatement();\n break;\n case Token.BREAK:\n Preconditions.checkState(childCount <= 1);\n add(\"break\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.EXPR_RESULT:\n Preconditions.checkState(childCount == 1);\n add(first, Context.START_OF_EXPR);\n cc.endStatement();\n break;\n case Token.NEW:\n add(\"new \");\n int precedence = NodeUtil.precedence(type);\n if (NodeUtil.containsType(\n first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {\n precedence = NodeUtil.precedence(first.getType()) + 1;\n }\n addExpr(first, precedence, Context.OTHER);\n Node next = first.getNext();\n if (next != null) {\n add(\"(\");\n addList(next);\n add(\")\");\n }\n break;\n case Token.STRING_KEY:\n Preconditions.checkState(\n childCount == 1, \"Object lit key must have 1 child\");\n addJsString(n);\n break;\n case Token.STRING:\n Preconditions.checkState(\n childCount == 0, \"A string may not have children\");\n addJsString(n);\n break;\n case Token.DELPROP:\n Preconditions.checkState(childCount == 1);\n add(\"delete \");\n add(first);\n break;\n case Token.OBJECTLIT: {\n boolean needsParens = (context == Context.START_OF_EXPR);\n if (needsParens) {\n add(\"(\");\n }\n add(\"{\");\n for (Node c = first; c != null; c = c.getNext()) {\n if (c != first) {\n cc.listSeparator();\n }\n if (c.isGetterDef() || c.isSetterDef()) {\n add(c);\n } else {\n Preconditions.checkState(c.isStringKey());\n String key = c.getString();\n if (!c.isQuotedString()\n && !(languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(key))\n && TokenStream.isJSIdentifier(key)\n && NodeUtil.isLatin(key)) {\n add(key);\n } else {\n double d = getSimpleNumber(key);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addExpr(c, 1, Context.OTHER);\n }\n }\n add(\":\");\n addExpr(c.getFirstChild(), 1, Context.OTHER);\n }\n }\n add(\"}\");\n if (needsParens) {\n add(\")\");\n }\n break;\n }\n case Token.SWITCH:\n add(\"switch(\");\n add(first);\n add(\")\");\n cc.beginBlock();\n addAllSiblings(first.getNext());\n cc.endBlock(context == Context.STATEMENT);\n break;\n case Token.CASE:\n Preconditions.checkState(childCount == 2);\n add(\"case \");\n add(first);\n addCaseBody(last);\n break;\n case Token.DEFAULT_CASE:\n Preconditions.checkState(childCount == 1);\n add(\"default\");\n addCaseBody(first);\n break;\n case Token.LABEL:\n Preconditions.checkState(childCount == 2);\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(first);\n add(\":\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), true);\n break;\n case Token.CAST:\n add(\"(\");\n add(first);\n add(\")\");\n break;\n default:\n throw new Error(\"Unknown type \" + type + \"\\n\" + n.toStringTree());\n }\n cc.endSourceMapping(n);\n }\n"}, "reference": " void add(Node n, Context context) {\n if (!cc.continueProcessing()) {\n return;\n }\n int type = n.getType();\n String opstr = NodeUtil.opToStr(type);\n int childCount = n.getChildCount();\n Node first = n.getFirstChild();\n Node last = n.getLastChild();\n if (opstr != null && first != last) {\n Preconditions.checkState(\n childCount == 2,\n \"Bad binary operator \\\"%s\\\": expected 2 arguments but got %s\",\n opstr, childCount);\n int p = NodeUtil.precedence(type);\n Context rhsContext = getContextForNoInOperator(context);\n if (last.getType() == type &&\n NodeUtil.isAssociative(type)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else if (NodeUtil.isAssignmentOp(n) && NodeUtil.isAssignmentOp(last)) {\n addExpr(first, p, context);\n cc.addOp(opstr, true);\n addExpr(last, p, rhsContext);\n } else {\n unrollBinaryOperator(n, type, opstr, context, rhsContext, p, p + 1);\n }\n return;\n }\n cc.startSourceMapping(n);\n switch (type) {\n case Token.TRY: {\n Preconditions.checkState(first.getNext().isBlock() &&\n !first.getNext().hasMoreThanOneChild());\n Preconditions.checkState(childCount >= 2 && childCount <= 3);\n add(\"try\");\n add(first, Context.PRESERVE_BLOCK);\n Node catchblock = first.getNext().getFirstChild();\n if (catchblock != null) {\n add(catchblock);\n }\n if (childCount == 3) {\n add(\"finally\");\n add(last, Context.PRESERVE_BLOCK);\n }\n break;\n }\n case Token.CATCH:\n Preconditions.checkState(childCount == 2);\n add(\"catch(\");\n add(first);\n add(\")\");\n add(last, Context.PRESERVE_BLOCK);\n break;\n case Token.THROW:\n Preconditions.checkState(childCount == 1);\n add(\"throw\");\n add(first);\n cc.endStatement(true);\n break;\n case Token.RETURN:\n add(\"return\");\n if (childCount == 1) {\n add(first);\n } else {\n Preconditions.checkState(childCount == 0);\n }\n cc.endStatement();\n break;\n case Token.VAR:\n if (first != null) {\n add(\"var \");\n addList(first, false, getContextForNoInOperator(context));\n }\n break;\n case Token.LABEL_NAME:\n Preconditions.checkState(!n.getString().isEmpty());\n addIdentifier(n.getString());\n break;\n case Token.NAME:\n if (first == null || first.isEmpty()) {\n addIdentifier(n.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n addIdentifier(n.getString());\n cc.addOp(\"=\", true);\n if (first.isComma()) {\n addExpr(first, NodeUtil.precedence(Token.ASSIGN), Context.OTHER);\n } else {\n addExpr(first, 0, getContextForNoInOperator(context));\n }\n }\n break;\n case Token.ARRAYLIT:\n add(\"[\");\n addArrayList(first);\n add(\"]\");\n break;\n case Token.PARAM_LIST:\n add(\"(\");\n addList(first);\n add(\")\");\n break;\n case Token.COMMA:\n Preconditions.checkState(childCount == 2);\n unrollBinaryOperator(n, Token.COMMA, \",\", context,\n getContextForNoInOperator(context), 0, 0);\n break;\n case Token.NUMBER:\n Preconditions.checkState(childCount == 0);\n cc.addNumber(n.getDouble());\n break;\n case Token.TYPEOF:\n case Token.VOID:\n case Token.NOT:\n case Token.BITNOT:\n case Token.POS: {\n Preconditions.checkState(childCount == 1);\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n break;\n }\n case Token.NEG: {\n Preconditions.checkState(childCount == 1);\n if (n.getFirstChild().isNumber()) {\n cc.addNumber(-n.getFirstChild().getDouble());\n } else {\n cc.addOp(NodeUtil.opToStrNoFail(type), false);\n addExpr(first, NodeUtil.precedence(type), Context.OTHER);\n }\n break;\n }\n case Token.HOOK: {\n Preconditions.checkState(childCount == 3);\n int p = NodeUtil.precedence(type);\n Context rhsContext = getContextForNoInOperator(context);\n addExpr(first, p + 1, context);\n cc.addOp(\"?\", true);\n addExpr(first.getNext(), 1, rhsContext);\n cc.addOp(\":\", true);\n addExpr(last, 1, rhsContext);\n break;\n }\n case Token.REGEXP:\n if (!first.isString() ||\n !last.isString()) {\n throw new Error(\"Expected children to be strings\");\n }\n String regexp = regexpEscape(first.getString(), outputCharsetEncoder);\n if (childCount == 2) {\n add(regexp + last.getString());\n } else {\n Preconditions.checkState(childCount == 1);\n add(regexp);\n }\n break;\n case Token.FUNCTION:\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n Preconditions.checkState(childCount == 3);\n boolean funcNeedsParens = (context == Context.START_OF_EXPR);\n if (funcNeedsParens) {\n add(\"(\");\n }\n add(\"function\");\n add(first);\n add(first.getNext());\n add(last, Context.PRESERVE_BLOCK);\n cc.endFunction(context == Context.STATEMENT);\n if (funcNeedsParens) {\n add(\")\");\n }\n break;\n case Token.GETTER_DEF:\n case Token.SETTER_DEF:\n Preconditions.checkState(n.getParent().isObjectLit());\n Preconditions.checkState(childCount == 1);\n Preconditions.checkState(first.isFunction());\n Preconditions.checkState(first.getFirstChild().getString().isEmpty());\n if (type == Token.GETTER_DEF) {\n Preconditions.checkState(!first.getChildAtIndex(1).hasChildren());\n add(\"get \");\n } else {\n Preconditions.checkState(first.getChildAtIndex(1).hasOneChild());\n add(\"set \");\n }\n String name = n.getString();\n Node fn = first;\n Node parameters = fn.getChildAtIndex(1);\n Node body = fn.getLastChild();\n if (!n.isQuotedString() &&\n TokenStream.isJSIdentifier(name) &&\n NodeUtil.isLatin(name)) {\n add(name);\n } else {\n double d = getSimpleNumber(name);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addJsString(n);\n }\n }\n add(parameters);\n add(body, Context.PRESERVE_BLOCK);\n break;\n case Token.SCRIPT:\n case Token.BLOCK: {\n if (n.getClass() != Node.class) {\n throw new Error(\"Unexpected Node subclass.\");\n }\n boolean preserveBlock = context == Context.PRESERVE_BLOCK;\n if (preserveBlock) {\n cc.beginBlock();\n }\n boolean preferLineBreaks =\n type == Token.SCRIPT ||\n (type == Token.BLOCK &&\n !preserveBlock &&\n n.getParent() != null &&\n n.getParent().isScript());\n for (Node c = first; c != null; c = c.getNext()) {\n add(c, Context.STATEMENT);\n if (c.isVar()) {\n cc.endStatement();\n }\n if (c.isFunction()) {\n cc.maybeLineBreak();\n }\n if (preferLineBreaks) {\n cc.notePreferredLineBreak();\n }\n }\n if (preserveBlock) {\n cc.endBlock(cc.breakAfterBlockFor(n, context == Context.STATEMENT));\n }\n break;\n }\n case Token.FOR:\n if (childCount == 4) {\n add(\"for(\");\n if (first.isVar()) {\n add(first, Context.IN_FOR_INIT_CLAUSE);\n } else {\n addExpr(first, 0, Context.IN_FOR_INIT_CLAUSE);\n }\n add(\";\");\n add(first.getNext());\n add(\";\");\n add(first.getNext().getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n Preconditions.checkState(childCount == 3);\n add(\"for(\");\n add(first);\n add(\"in\");\n add(first.getNext());\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n }\n break;\n case Token.DO:\n Preconditions.checkState(childCount == 2);\n add(\"do\");\n addNonEmptyStatement(first, Context.OTHER, false);\n add(\"while(\");\n add(last);\n add(\")\");\n cc.endStatement();\n break;\n case Token.WHILE:\n Preconditions.checkState(childCount == 2);\n add(\"while(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.EMPTY:\n Preconditions.checkState(childCount == 0);\n break;\n case Token.GETPROP: {\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETPROP: expected 2 children, but got %s\", childCount);\n Preconditions.checkState(\n last.isString(),\n \"Bad GETPROP: RHS should be STRING\");\n boolean needsParens = (first.isNumber());\n if (needsParens) {\n add(\"(\");\n }\n addExpr(first, NodeUtil.precedence(type), context);\n if (needsParens) {\n add(\")\");\n }\n if (this.languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(last.getString())) {\n add(\"[\");\n add(last);\n add(\"]\");\n } else {\n add(\".\");\n addIdentifier(last.getString());\n }\n break;\n }\n case Token.GETELEM:\n Preconditions.checkState(\n childCount == 2,\n \"Bad GETELEM: expected 2 children but got %s\", childCount);\n addExpr(first, NodeUtil.precedence(type), context);\n add(\"[\");\n add(first.getNext());\n add(\"]\");\n break;\n case Token.WITH:\n Preconditions.checkState(childCount == 2);\n add(\"with(\");\n add(first);\n add(\")\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n break;\n case Token.INC:\n case Token.DEC: {\n Preconditions.checkState(childCount == 1);\n String o = type == Token.INC ? \"++\" : \"--\";\n int postProp = n.getIntProp(Node.INCRDECR_PROP);\n if (postProp != 0) {\n addExpr(first, NodeUtil.precedence(type), context);\n cc.addOp(o, false);\n } else {\n cc.addOp(o, false);\n add(first);\n }\n break;\n }\n case Token.CALL:\n if (isIndirectEval(first)\n || n.getBooleanProp(Node.FREE_CALL) && NodeUtil.isGet(first)) {\n add(\"(0,\");\n addExpr(first, NodeUtil.precedence(Token.COMMA), Context.OTHER);\n add(\")\");\n } else {\n addExpr(first, NodeUtil.precedence(type), context);\n }\n add(\"(\");\n addList(first.getNext());\n add(\")\");\n break;\n case Token.IF:\n boolean hasElse = childCount == 3;\n boolean ambiguousElseClause =\n context == Context.BEFORE_DANGLING_ELSE && !hasElse;\n if (ambiguousElseClause) {\n cc.beginBlock();\n }\n add(\"if(\");\n add(first);\n add(\")\");\n if (hasElse) {\n addNonEmptyStatement(\n first.getNext(), Context.BEFORE_DANGLING_ELSE, false);\n add(\"else\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), false);\n } else {\n addNonEmptyStatement(first.getNext(), Context.OTHER, false);\n Preconditions.checkState(childCount == 2);\n }\n if (ambiguousElseClause) {\n cc.endBlock();\n }\n break;\n case Token.NULL:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"null\");\n break;\n case Token.THIS:\n Preconditions.checkState(childCount == 0);\n add(\"this\");\n break;\n case Token.FALSE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"false\");\n break;\n case Token.TRUE:\n Preconditions.checkState(childCount == 0);\n cc.addConstant(\"true\");\n break;\n case Token.CONTINUE:\n Preconditions.checkState(childCount <= 1);\n add(\"continue\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.DEBUGGER:\n Preconditions.checkState(childCount == 0);\n add(\"debugger\");\n cc.endStatement();\n break;\n case Token.BREAK:\n Preconditions.checkState(childCount <= 1);\n add(\"break\");\n if (childCount == 1) {\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(\" \");\n add(first);\n }\n cc.endStatement();\n break;\n case Token.EXPR_RESULT:\n Preconditions.checkState(childCount == 1);\n add(first, Context.START_OF_EXPR);\n cc.endStatement();\n break;\n case Token.NEW:\n add(\"new \");\n int precedence = NodeUtil.precedence(type);\n if (NodeUtil.containsType(\n first, Token.CALL, NodeUtil.MATCH_NOT_FUNCTION)) {\n precedence = NodeUtil.precedence(first.getType()) + 1;\n }\n addExpr(first, precedence, Context.OTHER);\n Node next = first.getNext();\n if (next != null) {\n add(\"(\");\n addList(next);\n add(\")\");\n }\n break;\n case Token.STRING_KEY:\n Preconditions.checkState(\n childCount == 1, \"Object lit key must have 1 child\");\n addJsString(n);\n break;\n case Token.STRING:\n Preconditions.checkState(\n childCount == 0, \"A string may not have children\");\n addJsString(n);\n break;\n case Token.DELPROP:\n Preconditions.checkState(childCount == 1);\n add(\"delete \");\n add(first);\n break;\n case Token.OBJECTLIT: {\n boolean needsParens = (context == Context.START_OF_EXPR);\n if (needsParens) {\n add(\"(\");\n }\n add(\"{\");\n for (Node c = first; c != null; c = c.getNext()) {\n if (c != first) {\n cc.listSeparator();\n }\n if (c.isGetterDef() || c.isSetterDef()) {\n add(c);\n } else {\n Preconditions.checkState(c.isStringKey());\n String key = c.getString();\n if (!c.isQuotedString()\n && !(languageMode == LanguageMode.ECMASCRIPT3\n && TokenStream.isKeyword(key))\n && TokenStream.isJSIdentifier(key)\n && NodeUtil.isLatin(key)) {\n add(key);\n } else {\n double d = getSimpleNumber(key);\n if (!Double.isNaN(d)) {\n cc.addNumber(d);\n } else {\n addExpr(c, 1, Context.OTHER);\n }\n }\n add(\":\");\n addExpr(c.getFirstChild(), 1, Context.OTHER);\n }\n }\n add(\"}\");\n if (needsParens) {\n add(\")\");\n }\n break;\n }\n case Token.SWITCH:\n add(\"switch(\");\n add(first);\n add(\")\");\n cc.beginBlock();\n addAllSiblings(first.getNext());\n cc.endBlock(context == Context.STATEMENT);\n break;\n case Token.CASE:\n Preconditions.checkState(childCount == 2);\n add(\"case \");\n add(first);\n addCaseBody(last);\n break;\n case Token.DEFAULT_CASE:\n Preconditions.checkState(childCount == 1);\n add(\"default\");\n addCaseBody(first);\n break;\n case Token.LABEL:\n Preconditions.checkState(childCount == 2);\n if (!first.isLabelName()) {\n throw new Error(\"Unexpected token type. Should be LABEL_NAME.\");\n }\n add(first);\n add(\":\");\n addNonEmptyStatement(\n last, getContextForNonEmptyExpression(context), true);\n break;\n case Token.CAST:\n add(\"(\");\n add(first);\n add(\")\");\n break;\n default:\n throw new Error(\"Unknown type \" + type + \"\\n\" + n.toStringTree());\n }\n cc.endSourceMapping(n);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-123"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-123"}} {"sample_uid": "defects4j_function_repair::Math-42", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected RealPointValuePair getSolution() {\n int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL);\n Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null;\n double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset());\n Set basicRows = new HashSet();\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n for (int i = 0; i < coefficients.length; i++) {\n int colIndex = columnLabels.indexOf(\"x\" + i);\n if (colIndex < 0) {\n coefficients[i] = 0;\n continue;\n }\n Integer basicRow = getBasicRow(colIndex);\n if (basicRows.contains(basicRow)) {\n coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative);\n } else {\n basicRows.add(basicRow);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected RealPointValuePair getSolution() {\n int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL);\n Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null;\n double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset());\n Set basicRows = new HashSet();\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n for (int i = 0; i < coefficients.length; i++) {\n int colIndex = columnLabels.indexOf(\"x\" + i);\n if (colIndex < 0) {\n coefficients[i] = 0;\n continue;\n }\n Integer basicRow = getBasicRow(colIndex);\n if (basicRows.contains(basicRow)) {\n coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative);\n } else {\n basicRows.add(basicRow);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n"}, "reference": " protected RealPointValuePair getSolution() {\n int negativeVarColumn = columnLabels.indexOf(NEGATIVE_VAR_COLUMN_LABEL);\n Integer negativeVarBasicRow = negativeVarColumn > 0 ? getBasicRow(negativeVarColumn) : null;\n double mostNegative = negativeVarBasicRow == null ? 0 : getEntry(negativeVarBasicRow, getRhsOffset());\n Set basicRows = new HashSet();\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n for (int i = 0; i < coefficients.length; i++) {\n int colIndex = columnLabels.indexOf(\"x\" + i);\n if (colIndex < 0) {\n coefficients[i] = 0;\n continue;\n }\n Integer basicRow = getBasicRow(colIndex);\n if (basicRow != null && basicRow == 0) {\n coefficients[i] = 0;\n } else if (basicRows.contains(basicRow)) {\n coefficients[i] = 0 - (restrictToNonNegative ? 0 : mostNegative);\n } else {\n basicRows.add(basicRow);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-42"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-42"}} {"sample_uid": "defects4j_function_repair::Math-89", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void addValue(Object v) {\n addValue((Comparable) v); \n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void addValue(Object v) {\n addValue((Comparable) v); \n }\n"}, "reference": " public void addValue(Object v) {\n if (v instanceof Comparable){\n addValue((Comparable) v); \n } else {\n throw new IllegalArgumentException(\"Object must implement Comparable\");\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-89"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-89"}} {"sample_uid": "defects4j_function_repair::Math-78", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean evaluateStep(final StepInterpolator interpolator)\n throws DerivativeException, EventException, ConvergenceException {\n try {\n forward = interpolator.isForward();\n final double t1 = interpolator.getCurrentTime();\n final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval));\n final double h = (t1 - t0) / n;\n double ta = t0;\n double ga = g0;\n double tb = t0 + (interpolator.isForward() ? convergence : -convergence);\n for (int i = 0; i < n; ++i) {\n tb += h;\n interpolator.setInterpolatedTime(tb);\n final double gb = handler.g(tb, interpolator.getInterpolatedState());\n if (g0Positive ^ (gb >= 0)) {\n increasing = gb >= ga;\n final UnivariateRealFunction f = new UnivariateRealFunction() {\n public double value(final double t) throws FunctionEvaluationException {\n try {\n interpolator.setInterpolatedTime(t);\n return handler.g(t, interpolator.getInterpolatedState());\n } catch (DerivativeException e) {\n throw new FunctionEvaluationException(e, t);\n } catch (EventException e) {\n throw new FunctionEvaluationException(e, t);\n }\n }\n };\n final BrentSolver solver = new BrentSolver();\n solver.setAbsoluteAccuracy(convergence);\n solver.setMaximalIterationCount(maxIterationCount);\n final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta);\n if ((Math.abs(root - ta) <= convergence) &&\n (Math.abs(root - previousEventTime) <= convergence)) {\n ta = tb;\n ga = gb;\n } else if (Double.isNaN(previousEventTime) ||\n (Math.abs(previousEventTime - root) > convergence)) {\n pendingEventTime = root;\n if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) {\n return false;\n }\n pendingEvent = true;\n return true;\n }\n } else {\n ta = tb;\n ga = gb;\n }\n }\n pendingEvent = false;\n pendingEventTime = Double.NaN;\n return false;\n } catch (FunctionEvaluationException e) {\n final Throwable cause = e.getCause();\n if ((cause != null) && (cause instanceof DerivativeException)) {\n throw (DerivativeException) cause;\n } else if ((cause != null) && (cause instanceof EventException)) {\n throw (EventException) cause;\n }\n throw new EventException(e);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean evaluateStep(final StepInterpolator interpolator)\n throws DerivativeException, EventException, ConvergenceException {\n try {\n forward = interpolator.isForward();\n final double t1 = interpolator.getCurrentTime();\n final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval));\n final double h = (t1 - t0) / n;\n double ta = t0;\n double ga = g0;\n double tb = t0 + (interpolator.isForward() ? convergence : -convergence);\n for (int i = 0; i < n; ++i) {\n tb += h;\n interpolator.setInterpolatedTime(tb);\n final double gb = handler.g(tb, interpolator.getInterpolatedState());\n if (g0Positive ^ (gb >= 0)) {\n increasing = gb >= ga;\n final UnivariateRealFunction f = new UnivariateRealFunction() {\n public double value(final double t) throws FunctionEvaluationException {\n try {\n interpolator.setInterpolatedTime(t);\n return handler.g(t, interpolator.getInterpolatedState());\n } catch (DerivativeException e) {\n throw new FunctionEvaluationException(e, t);\n } catch (EventException e) {\n throw new FunctionEvaluationException(e, t);\n }\n }\n };\n final BrentSolver solver = new BrentSolver();\n solver.setAbsoluteAccuracy(convergence);\n solver.setMaximalIterationCount(maxIterationCount);\n final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta);\n if ((Math.abs(root - ta) <= convergence) &&\n (Math.abs(root - previousEventTime) <= convergence)) {\n ta = tb;\n ga = gb;\n } else if (Double.isNaN(previousEventTime) ||\n (Math.abs(previousEventTime - root) > convergence)) {\n pendingEventTime = root;\n if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) {\n return false;\n }\n pendingEvent = true;\n return true;\n }\n } else {\n ta = tb;\n ga = gb;\n }\n }\n pendingEvent = false;\n pendingEventTime = Double.NaN;\n return false;\n } catch (FunctionEvaluationException e) {\n final Throwable cause = e.getCause();\n if ((cause != null) && (cause instanceof DerivativeException)) {\n throw (DerivativeException) cause;\n } else if ((cause != null) && (cause instanceof EventException)) {\n throw (EventException) cause;\n }\n throw new EventException(e);\n }\n }\n"}, "reference": " public boolean evaluateStep(final StepInterpolator interpolator)\n throws DerivativeException, EventException, ConvergenceException {\n try {\n forward = interpolator.isForward();\n final double t1 = interpolator.getCurrentTime();\n final int n = Math.max(1, (int) Math.ceil(Math.abs(t1 - t0) / maxCheckInterval));\n final double h = (t1 - t0) / n;\n double ta = t0;\n double ga = g0;\n double tb = t0 + (interpolator.isForward() ? convergence : -convergence);\n for (int i = 0; i < n; ++i) {\n tb += h;\n interpolator.setInterpolatedTime(tb);\n final double gb = handler.g(tb, interpolator.getInterpolatedState());\n if (g0Positive ^ (gb >= 0)) {\n if (ga * gb > 0) {\n final double epsilon = (forward ? 0.25 : -0.25) * convergence;\n for (int k = 0; (k < 4) && (ga * gb > 0); ++k) {\n ta += epsilon;\n interpolator.setInterpolatedTime(ta);\n ga = handler.g(ta, interpolator.getInterpolatedState());\n }\n if (ga * gb > 0) {\n throw MathRuntimeException.createInternalError(null);\n }\n }\n increasing = gb >= ga;\n final UnivariateRealFunction f = new UnivariateRealFunction() {\n public double value(final double t) throws FunctionEvaluationException {\n try {\n interpolator.setInterpolatedTime(t);\n return handler.g(t, interpolator.getInterpolatedState());\n } catch (DerivativeException e) {\n throw new FunctionEvaluationException(e, t);\n } catch (EventException e) {\n throw new FunctionEvaluationException(e, t);\n }\n }\n };\n final BrentSolver solver = new BrentSolver();\n solver.setAbsoluteAccuracy(convergence);\n solver.setMaximalIterationCount(maxIterationCount);\n final double root = (ta <= tb) ? solver.solve(f, ta, tb) : solver.solve(f, tb, ta);\n if ((Math.abs(root - ta) <= convergence) &&\n (Math.abs(root - previousEventTime) <= convergence)) {\n ta = tb;\n ga = gb;\n } else if (Double.isNaN(previousEventTime) ||\n (Math.abs(previousEventTime - root) > convergence)) {\n pendingEventTime = root;\n if (pendingEvent && (Math.abs(t1 - pendingEventTime) <= convergence)) {\n return false;\n }\n pendingEvent = true;\n return true;\n }\n } else {\n ta = tb;\n ga = gb;\n }\n }\n pendingEvent = false;\n pendingEventTime = Double.NaN;\n return false;\n } catch (FunctionEvaluationException e) {\n final Throwable cause = e.getCause();\n if ((cause != null) && (cause instanceof DerivativeException)) {\n throw (DerivativeException) cause;\n } else if ((cause != null) && (cause instanceof EventException)) {\n throw (EventException) cause;\n }\n throw new EventException(e);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-78"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-78"}} {"sample_uid": "defects4j_function_repair::Time-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static PeriodFormatter toFormatter(List elementPairs, boolean notPrinter, boolean notParser) {\n if (notPrinter && notParser) {\n throw new IllegalStateException(\"Builder has created neither a printer nor a parser\");\n }\n int size = elementPairs.size();\n if (size >= 2 && elementPairs.get(0) instanceof Separator) {\n Separator sep = (Separator) elementPairs.get(0);\n PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser);\n sep = sep.finish(f.getPrinter(), f.getParser());\n return new PeriodFormatter(sep, sep);\n }\n Object[] comp = createComposite(elementPairs);\n if (notPrinter) {\n return new PeriodFormatter(null, (PeriodParser) comp[1]);\n } else if (notParser) {\n return new PeriodFormatter((PeriodPrinter) comp[0], null);\n } else {\n return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static PeriodFormatter toFormatter(List elementPairs, boolean notPrinter, boolean notParser) {\n if (notPrinter && notParser) {\n throw new IllegalStateException(\"Builder has created neither a printer nor a parser\");\n }\n int size = elementPairs.size();\n if (size >= 2 && elementPairs.get(0) instanceof Separator) {\n Separator sep = (Separator) elementPairs.get(0);\n PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser);\n sep = sep.finish(f.getPrinter(), f.getParser());\n return new PeriodFormatter(sep, sep);\n }\n Object[] comp = createComposite(elementPairs);\n if (notPrinter) {\n return new PeriodFormatter(null, (PeriodParser) comp[1]);\n } else if (notParser) {\n return new PeriodFormatter((PeriodPrinter) comp[0], null);\n } else {\n return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]);\n }\n }\n"}, "reference": " private static PeriodFormatter toFormatter(List elementPairs, boolean notPrinter, boolean notParser) {\n if (notPrinter && notParser) {\n throw new IllegalStateException(\"Builder has created neither a printer nor a parser\");\n }\n int size = elementPairs.size();\n if (size >= 2 && elementPairs.get(0) instanceof Separator) {\n Separator sep = (Separator) elementPairs.get(0);\n if (sep.iAfterParser == null && sep.iAfterPrinter == null) {\n PeriodFormatter f = toFormatter(elementPairs.subList(2, size), notPrinter, notParser);\n sep = sep.finish(f.getPrinter(), f.getParser());\n return new PeriodFormatter(sep, sep);\n }\n }\n Object[] comp = createComposite(elementPairs);\n if (notPrinter) {\n return new PeriodFormatter(null, (PeriodParser) comp[1]);\n } else if (notParser) {\n return new PeriodFormatter((PeriodPrinter) comp[0], null);\n } else {\n return new PeriodFormatter((PeriodPrinter) comp[0], (PeriodParser) comp[1]);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-27"}} {"sample_uid": "defects4j_function_repair::Time-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {\n if (valueToAdd == 0) {\n return values;\n }\n if (DateTimeUtils.isContiguous(partial)) {\n long instant = 0L;\n for (int i = 0, isize = partial.size(); i < isize; i++) {\n instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);\n }\n instant = add(instant, valueToAdd);\n return iChronology.get(partial, instant);\n } else {\n return super.add(partial, fieldIndex, values, valueToAdd);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {\n if (valueToAdd == 0) {\n return values;\n }\n if (DateTimeUtils.isContiguous(partial)) {\n long instant = 0L;\n for (int i = 0, isize = partial.size(); i < isize; i++) {\n instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);\n }\n instant = add(instant, valueToAdd);\n return iChronology.get(partial, instant);\n } else {\n return super.add(partial, fieldIndex, values, valueToAdd);\n }\n }\n"}, "reference": " public int[] add(ReadablePartial partial, int fieldIndex, int[] values, int valueToAdd) {\n if (valueToAdd == 0) {\n return values;\n }\n if (partial.size() > 0 && partial.getFieldType(0).equals(DateTimeFieldType.monthOfYear()) && fieldIndex == 0) {\n int curMonth0 = partial.getValue(0) - 1;\n int newMonth = ((curMonth0 + (valueToAdd % 12) + 12) % 12) + 1;\n return set(partial, 0, values, newMonth);\n }\n if (DateTimeUtils.isContiguous(partial)) {\n long instant = 0L;\n for (int i = 0, isize = partial.size(); i < isize; i++) {\n instant = partial.getFieldType(i).getField(iChronology).set(instant, values[i]);\n }\n instant = add(instant, valueToAdd);\n return iChronology.get(partial, instant);\n } else {\n return super.add(partial, fieldIndex, values, valueToAdd);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-14"}} {"sample_uid": "defects4j_function_repair::Chart-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": ""}, "reference": " public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof MinMaxCategoryRenderer)) {\n return false;\n }\n MinMaxCategoryRenderer that = (MinMaxCategoryRenderer) obj;\n if (this.plotLines != that.plotLines) {\n return false;\n }\n if (!PaintUtilities.equal(this.groupPaint, that.groupPaint)) {\n return false;\n }\n if (!this.groupStroke.equals(that.groupStroke)) {\n return false;\n }\n return super.equals(obj);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-23"}} {"sample_uid": "defects4j_function_repair::Mockito-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean hasSameMethod(Invocation candidate) { \n Method m1 = invocation.getMethod();\n Method m2 = candidate.getMethod();\n return m1.equals(m2);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean hasSameMethod(Invocation candidate) { \n Method m1 = invocation.getMethod();\n Method m2 = candidate.getMethod();\n return m1.equals(m2);\n }\n"}, "reference": " public boolean hasSameMethod(Invocation candidate) { \n Method m1 = invocation.getMethod();\n Method m2 = candidate.getMethod();\n if (m1.getName() != null && m1.getName().equals(m2.getName())) {\n \tClass[] params1 = m1.getParameterTypes();\n \tClass[] params2 = m2.getParameterTypes();\n \tif (params1.length == params2.length) {\n \t for (int i = 0; i < params1.length; i++) {\n \t\tif (params1[i] != params2[i])\n \t\t return false;\n \t }\n \t return true;\n \t}\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-33"}} {"sample_uid": "defects4j_function_repair::Closure-101", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n options.setCodingConvention(new ClosureCodingConvention());\n CompilationLevel level = flags.compilation_level;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n WarningLevel wLevel = flags.warning_level;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n if (flags.process_closure_primitives) {\n options.closurePass = true;\n }\n initOptionsFromFlags(options);\n return options;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n options.setCodingConvention(new ClosureCodingConvention());\n CompilationLevel level = flags.compilation_level;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n WarningLevel wLevel = flags.warning_level;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n if (flags.process_closure_primitives) {\n options.closurePass = true;\n }\n initOptionsFromFlags(options);\n return options;\n }\n"}, "reference": " protected CompilerOptions createOptions() {\n CompilerOptions options = new CompilerOptions();\n options.setCodingConvention(new ClosureCodingConvention());\n CompilationLevel level = flags.compilation_level;\n level.setOptionsForCompilationLevel(options);\n if (flags.debug) {\n level.setDebugOptionsForCompilationLevel(options);\n }\n WarningLevel wLevel = flags.warning_level;\n wLevel.setOptionsForWarningLevel(options);\n for (FormattingOption formattingOption : flags.formatting) {\n formattingOption.applyToOptions(options);\n }\n options.closurePass = flags.process_closure_primitives;\n initOptionsFromFlags(options);\n return options;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-101"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-101"}} {"sample_uid": "defects4j_function_repair::Closure-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void addNumber(double x) {\n char prev = getLastChar();\n boolean negativeZero = isNegativeZero(x);\n if (x < 0 && prev == '-') {\n add(\" \");\n }\n if ((long) x == x && !negativeZero) {\n long value = (long) x;\n long mantissa = value;\n int exp = 0;\n if (Math.abs(x) >= 100) {\n while (mantissa / 10 * Math.pow(10, exp + 1) == value) {\n mantissa /= 10;\n exp++;\n }\n }\n if (exp > 2) {\n add(Long.toString(mantissa) + \"E\" + Integer.toString(exp));\n } else {\n add(Long.toString(value));\n }\n } else {\n add(String.valueOf(x));\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void addNumber(double x) {\n char prev = getLastChar();\n boolean negativeZero = isNegativeZero(x);\n if (x < 0 && prev == '-') {\n add(\" \");\n }\n if ((long) x == x && !negativeZero) {\n long value = (long) x;\n long mantissa = value;\n int exp = 0;\n if (Math.abs(x) >= 100) {\n while (mantissa / 10 * Math.pow(10, exp + 1) == value) {\n mantissa /= 10;\n exp++;\n }\n }\n if (exp > 2) {\n add(Long.toString(mantissa) + \"E\" + Integer.toString(exp));\n } else {\n add(Long.toString(value));\n }\n } else {\n add(String.valueOf(x));\n }\n }\n"}, "reference": " void addNumber(double x) {\n char prev = getLastChar();\n boolean negativeZero = isNegativeZero(x);\n if ((x < 0 || negativeZero) && prev == '-') {\n add(\" \");\n }\n if ((long) x == x && !negativeZero) {\n long value = (long) x;\n long mantissa = value;\n int exp = 0;\n if (Math.abs(x) >= 100) {\n while (mantissa / 10 * Math.pow(10, exp + 1) == value) {\n mantissa /= 10;\n exp++;\n }\n }\n if (exp > 2) {\n add(Long.toString(mantissa) + \"E\" + Integer.toString(exp));\n } else {\n add(Long.toString(value));\n }\n } else {\n add(String.valueOf(x));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-38"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-70", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void remove(SettableBeanProperty propToRm)\n {\n ArrayList props = new ArrayList(_size);\n String key = getPropertyName(propToRm);\n boolean found = false;\n for (int i = 1, end = _hashArea.length; i < end; i += 2) {\n SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];\n if (prop == null) {\n continue;\n }\n if (!found) {\n found = key.equals(prop.getName());\n if (found) {\n _propsInOrder[_findFromOrdered(prop)] = null;\n continue;\n }\n }\n props.add(prop);\n }\n if (!found) {\n throw new NoSuchElementException(\"No entry '\"+propToRm.getName()+\"' found, can't remove\");\n }\n init(props);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void remove(SettableBeanProperty propToRm)\n {\n ArrayList props = new ArrayList(_size);\n String key = getPropertyName(propToRm);\n boolean found = false;\n for (int i = 1, end = _hashArea.length; i < end; i += 2) {\n SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];\n if (prop == null) {\n continue;\n }\n if (!found) {\n found = key.equals(prop.getName());\n if (found) {\n _propsInOrder[_findFromOrdered(prop)] = null;\n continue;\n }\n }\n props.add(prop);\n }\n if (!found) {\n throw new NoSuchElementException(\"No entry '\"+propToRm.getName()+\"' found, can't remove\");\n }\n init(props);\n }\n"}, "reference": " public void remove(SettableBeanProperty propToRm)\n {\n ArrayList props = new ArrayList(_size);\n String key = getPropertyName(propToRm);\n boolean found = false;\n for (int i = 1, end = _hashArea.length; i < end; i += 2) {\n SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];\n if (prop == null) {\n continue;\n }\n if (!found) {\n found = key.equals(_hashArea[i-1]);\n if (found) {\n _propsInOrder[_findFromOrdered(prop)] = null;\n continue;\n }\n }\n props.add(prop);\n }\n if (!found) {\n throw new NoSuchElementException(\"No entry '\"+propToRm.getName()+\"' found, can't remove\");\n }\n init(props);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-70"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-70"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Date parseAsISO8601(String dateStr, ParsePosition pos)\n {\n int len = dateStr.length();\n char c = dateStr.charAt(len-1);\n DateFormat df;\n if (len <= 10 && Character.isDigit(c)) {\n df = _formatPlain;\n if (df == null) {\n df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);\n }\n } else if (c == 'Z') {\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);\n }\n if (dateStr.charAt(len-4) == ':') {\n StringBuilder sb = new StringBuilder(dateStr);\n sb.insert(len-1, \".000\");\n dateStr = sb.toString();\n }\n } else {\n if (hasTimeZone(dateStr)) {\n c = dateStr.charAt(len-3);\n if (c == ':') { \n StringBuilder sb = new StringBuilder(dateStr);\n sb.delete(len-3, len-2);\n dateStr = sb.toString();\n } else if (c == '+' || c == '-') { \n dateStr += \"00\";\n }\n len = dateStr.length();\n c = dateStr.charAt(len-9);\n if (Character.isDigit(c)) {\n StringBuilder sb = new StringBuilder(dateStr);\n sb.insert(len-5, \".000\");\n dateStr = sb.toString();\n }\n df = _formatISO8601;\n if (_formatISO8601 == null) {\n df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);\n }\n } else {\n StringBuilder sb = new StringBuilder(dateStr);\n int timeLen = len - dateStr.lastIndexOf('T') - 1;\n if (timeLen <= 8) {\n sb.append(\".000\");\n }\n sb.append('Z');\n dateStr = sb.toString();\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,\n _timezone, _locale);\n }\n }\n }\n return df.parse(dateStr, pos);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Date parseAsISO8601(String dateStr, ParsePosition pos)\n {\n int len = dateStr.length();\n char c = dateStr.charAt(len-1);\n DateFormat df;\n if (len <= 10 && Character.isDigit(c)) {\n df = _formatPlain;\n if (df == null) {\n df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);\n }\n } else if (c == 'Z') {\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);\n }\n if (dateStr.charAt(len-4) == ':') {\n StringBuilder sb = new StringBuilder(dateStr);\n sb.insert(len-1, \".000\");\n dateStr = sb.toString();\n }\n } else {\n if (hasTimeZone(dateStr)) {\n c = dateStr.charAt(len-3);\n if (c == ':') { \n StringBuilder sb = new StringBuilder(dateStr);\n sb.delete(len-3, len-2);\n dateStr = sb.toString();\n } else if (c == '+' || c == '-') { \n dateStr += \"00\";\n }\n len = dateStr.length();\n c = dateStr.charAt(len-9);\n if (Character.isDigit(c)) {\n StringBuilder sb = new StringBuilder(dateStr);\n sb.insert(len-5, \".000\");\n dateStr = sb.toString();\n }\n df = _formatISO8601;\n if (_formatISO8601 == null) {\n df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);\n }\n } else {\n StringBuilder sb = new StringBuilder(dateStr);\n int timeLen = len - dateStr.lastIndexOf('T') - 1;\n if (timeLen <= 8) {\n sb.append(\".000\");\n }\n sb.append('Z');\n dateStr = sb.toString();\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,\n _timezone, _locale);\n }\n }\n }\n return df.parse(dateStr, pos);\n }\n"}, "reference": " protected Date parseAsISO8601(String dateStr, ParsePosition pos)\n {\n int len = dateStr.length();\n char c = dateStr.charAt(len-1);\n DateFormat df;\n if (len <= 10 && Character.isDigit(c)) {\n df = _formatPlain;\n if (df == null) {\n df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);\n }\n } else if (c == 'Z') {\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);\n }\n if (dateStr.charAt(len-4) == ':') {\n StringBuilder sb = new StringBuilder(dateStr);\n sb.insert(len-1, \".000\");\n dateStr = sb.toString();\n }\n } else {\n if (hasTimeZone(dateStr)) {\n c = dateStr.charAt(len-3);\n if (c == ':') { \n StringBuilder sb = new StringBuilder(dateStr);\n sb.delete(len-3, len-2);\n dateStr = sb.toString();\n } else if (c == '+' || c == '-') { \n dateStr += \"00\";\n }\n len = dateStr.length();\n int timeLen = len - dateStr.lastIndexOf('T') - 6;\n if (timeLen < 12) { \n int offset = len - 5; \n StringBuilder sb = new StringBuilder(dateStr);\n switch (timeLen) {\n case 11:\n sb.insert(offset, '0'); break;\n case 10:\n sb.insert(offset, \"00\"); break;\n case 9: \n sb.insert(offset, \"000\"); break;\n case 8:\n sb.insert(offset, \".000\"); break;\n case 7: \n break;\n case 6: \n sb.insert(offset, \"00.000\");\n case 5: \n sb.insert(offset, \":00.000\");\n }\n dateStr = sb.toString();\n }\n df = _formatISO8601;\n if (_formatISO8601 == null) {\n df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);\n }\n } else {\n StringBuilder sb = new StringBuilder(dateStr);\n int timeLen = len - dateStr.lastIndexOf('T') - 1;\n if (timeLen < 12) { \n switch (timeLen) {\n case 11: sb.append('0');\n case 10: sb.append('0');\n case 9: sb.append('0');\n break;\n default:\n sb.append(\".000\");\n }\n }\n sb.append('Z');\n dateStr = sb.toString();\n df = _formatISO8601_z;\n if (df == null) {\n df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,\n _timezone, _locale);\n }\n }\n }\n return df.parse(dateStr, pos);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-6"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-101", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (buffer.assignParameter(creatorProp,\n _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n bean = wrapInstantiationProblem(e, ctxt);\n }\n p.setCurrentValue(bean);\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken();\n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n tokens.writeEndObject();\n if (bean.getClass() != _beanType.getRawClass()) {\n ctxt.reportInputMismatch(creatorProp,\n \"Cannot create polymorphic instances with unwrapped values\");\n return null;\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter == null) {\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n } else {\n TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);\n tokens.writeFieldName(propName);\n tokens.append(b2);\n try {\n buffer.bufferAnyProperty(_anySetter, propName,\n _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n }\n continue;\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (buffer.assignParameter(creatorProp,\n _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n bean = wrapInstantiationProblem(e, ctxt);\n }\n p.setCurrentValue(bean);\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken();\n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n tokens.writeEndObject();\n if (bean.getClass() != _beanType.getRawClass()) {\n ctxt.reportInputMismatch(creatorProp,\n \"Cannot create polymorphic instances with unwrapped values\");\n return null;\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter == null) {\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n } else {\n TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);\n tokens.writeFieldName(propName);\n tokens.append(b2);\n try {\n buffer.bufferAnyProperty(_anySetter, propName,\n _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n }\n continue;\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n"}, "reference": " protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p, ctxt);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (buffer.assignParameter(creatorProp,\n _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n bean = wrapInstantiationProblem(e, ctxt);\n }\n p.setCurrentValue(bean);\n while (t == JsonToken.FIELD_NAME) {\n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n if (t != JsonToken.END_OBJECT) {\n ctxt.reportWrongTokenException(this, JsonToken.END_OBJECT, \n \"Attempted to unwrap '%s' value\",\n handledType().getName());\n }\n tokens.writeEndObject();\n if (bean.getClass() != _beanType.getRawClass()) {\n ctxt.reportInputMismatch(creatorProp,\n \"Cannot create polymorphic instances with unwrapped values\");\n return null;\n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter == null) {\n tokens.writeFieldName(propName);\n tokens.copyCurrentStructure(p);\n } else {\n TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);\n tokens.writeFieldName(propName);\n tokens.append(b2);\n try {\n buffer.bufferAnyProperty(_anySetter, propName,\n _anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n }\n continue;\n }\n }\n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-101"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-101"}} {"sample_uid": "defects4j_function_repair::Time-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static synchronized String getConvertedId(String id) {\n Map map = cZoneIdConversion;\n if (map == null) {\n map = new HashMap();\n map.put(\"GMT\", \"UTC\");\n map.put(\"MIT\", \"Pacific/Apia\");\n map.put(\"HST\", \"Pacific/Honolulu\"); \n map.put(\"AST\", \"America/Anchorage\");\n map.put(\"PST\", \"America/Los_Angeles\");\n map.put(\"MST\", \"America/Denver\"); \n map.put(\"PNT\", \"America/Phoenix\");\n map.put(\"CST\", \"America/Chicago\");\n map.put(\"EST\", \"America/New_York\"); \n map.put(\"IET\", \"America/Indianapolis\");\n map.put(\"PRT\", \"America/Puerto_Rico\");\n map.put(\"CNT\", \"America/St_Johns\");\n map.put(\"AGT\", \"America/Buenos_Aires\");\n map.put(\"BET\", \"America/Sao_Paulo\");\n map.put(\"WET\", \"Europe/London\");\n map.put(\"ECT\", \"Europe/Paris\");\n map.put(\"ART\", \"Africa/Cairo\");\n map.put(\"CAT\", \"Africa/Harare\");\n map.put(\"EET\", \"Europe/Bucharest\");\n map.put(\"EAT\", \"Africa/Addis_Ababa\");\n map.put(\"MET\", \"Asia/Tehran\");\n map.put(\"NET\", \"Asia/Yerevan\");\n map.put(\"PLT\", \"Asia/Karachi\");\n map.put(\"IST\", \"Asia/Calcutta\");\n map.put(\"BST\", \"Asia/Dhaka\");\n map.put(\"VST\", \"Asia/Saigon\");\n map.put(\"CTT\", \"Asia/Shanghai\");\n map.put(\"JST\", \"Asia/Tokyo\");\n map.put(\"ACT\", \"Australia/Darwin\");\n map.put(\"AET\", \"Australia/Sydney\");\n map.put(\"SST\", \"Pacific/Guadalcanal\");\n map.put(\"NST\", \"Pacific/Auckland\");\n cZoneIdConversion = map;\n }\n return map.get(id);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static synchronized String getConvertedId(String id) {\n Map map = cZoneIdConversion;\n if (map == null) {\n map = new HashMap();\n map.put(\"GMT\", \"UTC\");\n map.put(\"MIT\", \"Pacific/Apia\");\n map.put(\"HST\", \"Pacific/Honolulu\"); \n map.put(\"AST\", \"America/Anchorage\");\n map.put(\"PST\", \"America/Los_Angeles\");\n map.put(\"MST\", \"America/Denver\"); \n map.put(\"PNT\", \"America/Phoenix\");\n map.put(\"CST\", \"America/Chicago\");\n map.put(\"EST\", \"America/New_York\"); \n map.put(\"IET\", \"America/Indianapolis\");\n map.put(\"PRT\", \"America/Puerto_Rico\");\n map.put(\"CNT\", \"America/St_Johns\");\n map.put(\"AGT\", \"America/Buenos_Aires\");\n map.put(\"BET\", \"America/Sao_Paulo\");\n map.put(\"WET\", \"Europe/London\");\n map.put(\"ECT\", \"Europe/Paris\");\n map.put(\"ART\", \"Africa/Cairo\");\n map.put(\"CAT\", \"Africa/Harare\");\n map.put(\"EET\", \"Europe/Bucharest\");\n map.put(\"EAT\", \"Africa/Addis_Ababa\");\n map.put(\"MET\", \"Asia/Tehran\");\n map.put(\"NET\", \"Asia/Yerevan\");\n map.put(\"PLT\", \"Asia/Karachi\");\n map.put(\"IST\", \"Asia/Calcutta\");\n map.put(\"BST\", \"Asia/Dhaka\");\n map.put(\"VST\", \"Asia/Saigon\");\n map.put(\"CTT\", \"Asia/Shanghai\");\n map.put(\"JST\", \"Asia/Tokyo\");\n map.put(\"ACT\", \"Australia/Darwin\");\n map.put(\"AET\", \"Australia/Sydney\");\n map.put(\"SST\", \"Pacific/Guadalcanal\");\n map.put(\"NST\", \"Pacific/Auckland\");\n cZoneIdConversion = map;\n }\n return map.get(id);\n }\n"}, "reference": " private static synchronized String getConvertedId(String id) {\n Map map = cZoneIdConversion;\n if (map == null) {\n map = new HashMap();\n map.put(\"GMT\", \"UTC\");\n map.put(\"WET\", \"WET\");\n map.put(\"CET\", \"CET\");\n map.put(\"MET\", \"CET\");\n map.put(\"ECT\", \"CET\");\n map.put(\"EET\", \"EET\");\n map.put(\"MIT\", \"Pacific/Apia\");\n map.put(\"HST\", \"Pacific/Honolulu\"); \n map.put(\"AST\", \"America/Anchorage\");\n map.put(\"PST\", \"America/Los_Angeles\");\n map.put(\"MST\", \"America/Denver\"); \n map.put(\"PNT\", \"America/Phoenix\");\n map.put(\"CST\", \"America/Chicago\");\n map.put(\"EST\", \"America/New_York\"); \n map.put(\"IET\", \"America/Indiana/Indianapolis\");\n map.put(\"PRT\", \"America/Puerto_Rico\");\n map.put(\"CNT\", \"America/St_Johns\");\n map.put(\"AGT\", \"America/Argentina/Buenos_Aires\");\n map.put(\"BET\", \"America/Sao_Paulo\");\n map.put(\"ART\", \"Africa/Cairo\");\n map.put(\"CAT\", \"Africa/Harare\");\n map.put(\"EAT\", \"Africa/Addis_Ababa\");\n map.put(\"NET\", \"Asia/Yerevan\");\n map.put(\"PLT\", \"Asia/Karachi\");\n map.put(\"IST\", \"Asia/Kolkata\");\n map.put(\"BST\", \"Asia/Dhaka\");\n map.put(\"VST\", \"Asia/Ho_Chi_Minh\");\n map.put(\"CTT\", \"Asia/Shanghai\");\n map.put(\"JST\", \"Asia/Tokyo\");\n map.put(\"ACT\", \"Australia/Darwin\");\n map.put(\"AET\", \"Australia/Sydney\");\n map.put(\"SST\", \"Pacific/Guadalcanal\");\n map.put(\"NST\", \"Pacific/Auckland\");\n cZoneIdConversion = map;\n }\n return map.get(id);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-23"}} {"sample_uid": "defects4j_function_repair::Csv-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String get(final String name) {\n if (mapping == null) {\n throw new IllegalStateException(\n \"No header mapping was specified, the record values can't be accessed by name\");\n }\n final Integer index = mapping.get(name);\n return index != null ? values[index.intValue()] : null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String get(final String name) {\n if (mapping == null) {\n throw new IllegalStateException(\n \"No header mapping was specified, the record values can't be accessed by name\");\n }\n final Integer index = mapping.get(name);\n return index != null ? values[index.intValue()] : null;\n }\n"}, "reference": " public String get(final String name) {\n if (mapping == null) {\n throw new IllegalStateException(\n \"No header mapping was specified, the record values can't be accessed by name\");\n }\n final Integer index = mapping.get(name);\n try {\n return index != null ? values[index.intValue()] : null;\n } catch (ArrayIndexOutOfBoundsException e) {\n throw new IllegalArgumentException(\n String.format(\n \"Index for header '%s' is %d but CSVRecord only has %d values!\",\n name, index.intValue(), values.length));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-2"}} {"sample_uid": "defects4j_function_repair::Closure-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryFoldSimpleFunctionCall(Node n) {\n Preconditions.checkState(n.isCall());\n Node callTarget = n.getFirstChild();\n if (callTarget != null && callTarget.isName() &&\n callTarget.getString().equals(\"String\")) {\n Node value = callTarget.getNext();\n if (value != null) {\n Node addition = IR.add(\n IR.string(\"\").srcref(callTarget),\n value.detachFromParent());\n n.getParent().replaceChild(n, addition);\n reportCodeChange();\n return addition;\n }\n }\n return n;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryFoldSimpleFunctionCall(Node n) {\n Preconditions.checkState(n.isCall());\n Node callTarget = n.getFirstChild();\n if (callTarget != null && callTarget.isName() &&\n callTarget.getString().equals(\"String\")) {\n Node value = callTarget.getNext();\n if (value != null) {\n Node addition = IR.add(\n IR.string(\"\").srcref(callTarget),\n value.detachFromParent());\n n.getParent().replaceChild(n, addition);\n reportCodeChange();\n return addition;\n }\n }\n return n;\n }\n"}, "reference": " private Node tryFoldSimpleFunctionCall(Node n) {\n Preconditions.checkState(n.isCall());\n Node callTarget = n.getFirstChild();\n if (callTarget != null && callTarget.isName() &&\n callTarget.getString().equals(\"String\")) {\n Node value = callTarget.getNext();\n if (value != null && value.getNext() == null &&\n NodeUtil.isImmutableValue(value)) {\n Node addition = IR.add(\n IR.string(\"\").srcref(callTarget),\n value.detachFromParent());\n n.getParent().replaceChild(n, addition);\n reportCodeChange();\n return addition;\n }\n }\n return n;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-20"}} {"sample_uid": "defects4j_function_repair::Compress-45", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static int formatLongOctalOrBinaryBytes(\n final long value, final byte[] buf, final int offset, final int length) {\n final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE;\n final boolean negative = value < 0;\n if (!negative && value <= maxAsOctalChar) { \n return formatLongOctalBytes(value, buf, offset, length);\n }\n if (length < 9) {\n formatLongBinary(value, buf, offset, length, negative);\n }\n formatBigIntegerBinary(value, buf, offset, length, negative);\n buf[offset] = (byte) (negative ? 0xff : 0x80);\n return offset + length;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static int formatLongOctalOrBinaryBytes(\n final long value, final byte[] buf, final int offset, final int length) {\n final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE;\n final boolean negative = value < 0;\n if (!negative && value <= maxAsOctalChar) { \n return formatLongOctalBytes(value, buf, offset, length);\n }\n if (length < 9) {\n formatLongBinary(value, buf, offset, length, negative);\n }\n formatBigIntegerBinary(value, buf, offset, length, negative);\n buf[offset] = (byte) (negative ? 0xff : 0x80);\n return offset + length;\n }\n"}, "reference": " public static int formatLongOctalOrBinaryBytes(\n final long value, final byte[] buf, final int offset, final int length) {\n final long maxAsOctalChar = length == TarConstants.UIDLEN ? TarConstants.MAXID : TarConstants.MAXSIZE;\n final boolean negative = value < 0;\n if (!negative && value <= maxAsOctalChar) { \n return formatLongOctalBytes(value, buf, offset, length);\n }\n if (length < 9) {\n formatLongBinary(value, buf, offset, length, negative);\n } else {\n formatBigIntegerBinary(value, buf, offset, length, negative);\n }\n buf[offset] = (byte) (negative ? 0xff : 0x80);\n return offset + length;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-45"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-45"}} {"sample_uid": "defects4j_function_repair::Jsoup-54", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void copyAttributes(org.jsoup.nodes.Node source, Element el) {\n for (Attribute attribute : source.attributes()) {\n String key = attribute.getKey().replaceAll(\"[^-a-zA-Z0-9_:.]\", \"\");\n el.setAttribute(key, attribute.getValue());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void copyAttributes(org.jsoup.nodes.Node source, Element el) {\n for (Attribute attribute : source.attributes()) {\n String key = attribute.getKey().replaceAll(\"[^-a-zA-Z0-9_:.]\", \"\");\n el.setAttribute(key, attribute.getValue());\n }\n }\n"}, "reference": " private void copyAttributes(org.jsoup.nodes.Node source, Element el) {\n for (Attribute attribute : source.attributes()) {\n String key = attribute.getKey().replaceAll(\"[^-a-zA-Z0-9_:.]\", \"\");\n if (key.matches(\"[a-zA-Z_:]{1}[-a-zA-Z0-9_:.]*\"))\n el.setAttribute(key, attribute.getValue());\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-54"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-54"}} {"sample_uid": "defects4j_function_repair::Compress-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n tais.getNextEntry();\n return new TarArchiveInputStream(in);\n } catch (Exception e) { \n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n tais.getNextEntry();\n return new TarArchiveInputStream(in);\n } catch (Exception e) { \n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n"}, "reference": " public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n if (signatureLength >= 512) {\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n tais.getNextEntry();\n return new TarArchiveInputStream(in);\n } catch (Exception e) { \n }\n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-11"}} {"sample_uid": "defects4j_function_repair::JacksonXml-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected XmlSerializerProvider(XmlSerializerProvider src) {\n super(src);\n _rootNameLookup = src._rootNameLookup;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected XmlSerializerProvider(XmlSerializerProvider src) {\n super(src);\n _rootNameLookup = src._rootNameLookup;\n }\n"}, "reference": " protected XmlSerializerProvider(XmlSerializerProvider src) {\n super(src);\n _rootNameLookup = new XmlRootNameLookup();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonXml-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonXml-5"}} {"sample_uid": "defects4j_function_repair::Csv-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n case ALL_NON_NULL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) {\n quote = true;\n } else if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n case ALL_NON_NULL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) {\n quote = true;\n } else if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n"}, "reference": " private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n case ALL_NON_NULL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-15"}} {"sample_uid": "defects4j_function_repair::Chart-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof ShapeList)) {\n return false;\n }\n return super.equals(obj);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof ShapeList)) {\n return false;\n }\n return super.equals(obj);\n }\n"}, "reference": " public boolean equals(Object obj) {\n if (obj == this) {\n return true;\n }\n if (!(obj instanceof ShapeList)) {\n return false;\n }\n ShapeList that = (ShapeList) obj;\n int listSize = size();\n for (int i = 0; i < listSize; i++) {\n if (!ShapeUtilities.equal((Shape) get(i), (Shape) that.get(i))) {\n return false;\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-6"}} {"sample_uid": "defects4j_function_repair::Mockito-34", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void captureArgumentsFrom(Invocation i) {\n int k = 0;\n for (Matcher m : matchers) {\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(i.getArguments()[k]);\n }\n k++;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void captureArgumentsFrom(Invocation i) {\n int k = 0;\n for (Matcher m : matchers) {\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(i.getArguments()[k]);\n }\n k++;\n }\n }\n"}, "reference": " public void captureArgumentsFrom(Invocation i) {\n int k = 0;\n for (Matcher m : matchers) {\n if (m instanceof CapturesArguments && i.getArguments().length > k) {\n ((CapturesArguments) m).captureFrom(i.getArguments()[k]);\n }\n k++;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-34"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-34"}} {"sample_uid": "defects4j_function_repair::Math-34", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Iterator iterator() {\n return chromosomes.iterator();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Iterator iterator() {\n return chromosomes.iterator();\n }\n"}, "reference": " public Iterator iterator() {\n return getChromosomes().iterator();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-34"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-34"}} {"sample_uid": "defects4j_function_repair::Closure-44", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void add(String newcode) {\n maybeEndStatement();\n if (newcode.length() == 0) {\n return;\n }\n char c = newcode.charAt(0);\n if ((isWordChar(c) || c == '\\\\') &&\n isWordChar(getLastChar())) {\n append(\" \");\n }\n append(newcode);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void add(String newcode) {\n maybeEndStatement();\n if (newcode.length() == 0) {\n return;\n }\n char c = newcode.charAt(0);\n if ((isWordChar(c) || c == '\\\\') &&\n isWordChar(getLastChar())) {\n append(\" \");\n }\n append(newcode);\n }\n"}, "reference": " void add(String newcode) {\n maybeEndStatement();\n if (newcode.length() == 0) {\n return;\n }\n char c = newcode.charAt(0);\n if ((isWordChar(c) || c == '\\\\') &&\n isWordChar(getLastChar())) {\n append(\" \");\n } else if (c == '/' && getLastChar() == '/') {\n append(\" \");\n }\n append(newcode);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-44"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-44"}} {"sample_uid": "defects4j_function_repair::Compress-25", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ZipArchiveInputStream(InputStream inputStream,\n String encoding,\n boolean useUnicodeExtraFields,\n boolean allowStoredEntriesWithDataDescriptor) {\n zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);\n this.useUnicodeExtraFields = useUnicodeExtraFields;\n in = new PushbackInputStream(inputStream, buf.capacity());\n this.allowStoredEntriesWithDataDescriptor =\n allowStoredEntriesWithDataDescriptor;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ZipArchiveInputStream(InputStream inputStream,\n String encoding,\n boolean useUnicodeExtraFields,\n boolean allowStoredEntriesWithDataDescriptor) {\n zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);\n this.useUnicodeExtraFields = useUnicodeExtraFields;\n in = new PushbackInputStream(inputStream, buf.capacity());\n this.allowStoredEntriesWithDataDescriptor =\n allowStoredEntriesWithDataDescriptor;\n }\n"}, "reference": " public ZipArchiveInputStream(InputStream inputStream,\n String encoding,\n boolean useUnicodeExtraFields,\n boolean allowStoredEntriesWithDataDescriptor) {\n zipEncoding = ZipEncodingHelper.getZipEncoding(encoding);\n this.useUnicodeExtraFields = useUnicodeExtraFields;\n in = new PushbackInputStream(inputStream, buf.capacity());\n this.allowStoredEntriesWithDataDescriptor =\n allowStoredEntriesWithDataDescriptor;\n buf.limit(0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-25"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-25"}} {"sample_uid": "defects4j_function_repair::Closure-52", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean isSimpleNumber(String s) {\n int len = s.length();\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len > 0;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean isSimpleNumber(String s) {\n int len = s.length();\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len > 0;\n }\n"}, "reference": " static boolean isSimpleNumber(String s) {\n int len = s.length();\n for (int index = 0; index < len; index++) {\n char c = s.charAt(index);\n if (c < '0' || c > '9') {\n return false;\n }\n }\n return len > 0 && s.charAt(0) != '0';\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-52"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-52"}} {"sample_uid": "defects4j_function_repair::Closure-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static Node computeFollowNode(\n Node fromNode, Node node, ControlFlowAnalysis cfa) {\n Node parent = node.getParent();\n if (parent == null || parent.isFunction() ||\n (cfa != null && node == cfa.root)) {\n return null;\n }\n switch (parent.getType()) {\n case Token.IF:\n return computeFollowNode(fromNode, parent, cfa);\n case Token.CASE:\n case Token.DEFAULT_CASE:\n if (parent.getNext() != null) {\n if (parent.getNext().isCase()) {\n return parent.getNext().getFirstChild().getNext();\n } else if (parent.getNext().isDefaultCase()) {\n return parent.getNext().getFirstChild();\n } else {\n Preconditions.checkState(false, \"Not reachable\");\n }\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n break;\n case Token.FOR:\n if (NodeUtil.isForIn(parent)) {\n return parent;\n } else {\n return parent.getFirstChild().getNext().getNext();\n }\n case Token.WHILE:\n case Token.DO:\n return parent;\n case Token.TRY:\n if (parent.getFirstChild() == node) {\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(parent.getLastChild());\n } else { \n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (NodeUtil.getCatchBlock(parent) == node){\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(node.getNext());\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (parent.getLastChild() == node){\n if (cfa != null) {\n for (Node finallyNode : cfa.finallyMap.get(parent)) {\n cfa.createEdge(fromNode, Branch.UNCOND, finallyNode);\n }\n }\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n Node nextSibling = node.getNext();\n while (nextSibling != null && nextSibling.isFunction()) {\n nextSibling = nextSibling.getNext();\n }\n if (nextSibling != null) {\n return computeFallThrough(nextSibling);\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static Node computeFollowNode(\n Node fromNode, Node node, ControlFlowAnalysis cfa) {\n Node parent = node.getParent();\n if (parent == null || parent.isFunction() ||\n (cfa != null && node == cfa.root)) {\n return null;\n }\n switch (parent.getType()) {\n case Token.IF:\n return computeFollowNode(fromNode, parent, cfa);\n case Token.CASE:\n case Token.DEFAULT_CASE:\n if (parent.getNext() != null) {\n if (parent.getNext().isCase()) {\n return parent.getNext().getFirstChild().getNext();\n } else if (parent.getNext().isDefaultCase()) {\n return parent.getNext().getFirstChild();\n } else {\n Preconditions.checkState(false, \"Not reachable\");\n }\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n break;\n case Token.FOR:\n if (NodeUtil.isForIn(parent)) {\n return parent;\n } else {\n return parent.getFirstChild().getNext().getNext();\n }\n case Token.WHILE:\n case Token.DO:\n return parent;\n case Token.TRY:\n if (parent.getFirstChild() == node) {\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(parent.getLastChild());\n } else { \n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (NodeUtil.getCatchBlock(parent) == node){\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(node.getNext());\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (parent.getLastChild() == node){\n if (cfa != null) {\n for (Node finallyNode : cfa.finallyMap.get(parent)) {\n cfa.createEdge(fromNode, Branch.UNCOND, finallyNode);\n }\n }\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n Node nextSibling = node.getNext();\n while (nextSibling != null && nextSibling.isFunction()) {\n nextSibling = nextSibling.getNext();\n }\n if (nextSibling != null) {\n return computeFallThrough(nextSibling);\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n"}, "reference": " private static Node computeFollowNode(\n Node fromNode, Node node, ControlFlowAnalysis cfa) {\n Node parent = node.getParent();\n if (parent == null || parent.isFunction() ||\n (cfa != null && node == cfa.root)) {\n return null;\n }\n switch (parent.getType()) {\n case Token.IF:\n return computeFollowNode(fromNode, parent, cfa);\n case Token.CASE:\n case Token.DEFAULT_CASE:\n if (parent.getNext() != null) {\n if (parent.getNext().isCase()) {\n return parent.getNext().getFirstChild().getNext();\n } else if (parent.getNext().isDefaultCase()) {\n return parent.getNext().getFirstChild();\n } else {\n Preconditions.checkState(false, \"Not reachable\");\n }\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n break;\n case Token.FOR:\n if (NodeUtil.isForIn(parent)) {\n return parent;\n } else {\n return parent.getFirstChild().getNext().getNext();\n }\n case Token.WHILE:\n case Token.DO:\n return parent;\n case Token.TRY:\n if (parent.getFirstChild() == node) {\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(parent.getLastChild());\n } else { \n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (NodeUtil.getCatchBlock(parent) == node){\n if (NodeUtil.hasFinally(parent)) { \n return computeFallThrough(node.getNext());\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n } else if (parent.getLastChild() == node){\n if (cfa != null) {\n for (Node finallyNode : cfa.finallyMap.get(parent)) {\n cfa.createEdge(fromNode, Branch.ON_EX, finallyNode);\n }\n }\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n Node nextSibling = node.getNext();\n while (nextSibling != null && nextSibling.isFunction()) {\n nextSibling = nextSibling.getNext();\n }\n if (nextSibling != null) {\n return computeFallThrough(nextSibling);\n } else {\n return computeFollowNode(fromNode, parent, cfa);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-14"}} {"sample_uid": "defects4j_function_repair::Math-56", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int[] getCounts(int index) {\n if (index < 0 ||\n index >= totalSize) {\n throw new OutOfRangeException(index, 0, totalSize);\n }\n final int[] indices = new int[dimension];\n int count = 0;\n for (int i = 0; i < last; i++) {\n int idx = 0;\n final int offset = uniCounterOffset[i];\n while (count <= index) {\n count += offset;\n ++idx;\n }\n --idx;\n count -= offset;\n indices[i] = idx;\n }\n int idx = 1;\n while (count < index) {\n count += idx;\n ++idx;\n }\n --idx;\n indices[last] = idx;\n return indices;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int[] getCounts(int index) {\n if (index < 0 ||\n index >= totalSize) {\n throw new OutOfRangeException(index, 0, totalSize);\n }\n final int[] indices = new int[dimension];\n int count = 0;\n for (int i = 0; i < last; i++) {\n int idx = 0;\n final int offset = uniCounterOffset[i];\n while (count <= index) {\n count += offset;\n ++idx;\n }\n --idx;\n count -= offset;\n indices[i] = idx;\n }\n int idx = 1;\n while (count < index) {\n count += idx;\n ++idx;\n }\n --idx;\n indices[last] = idx;\n return indices;\n }\n"}, "reference": " public int[] getCounts(int index) {\n if (index < 0 ||\n index >= totalSize) {\n throw new OutOfRangeException(index, 0, totalSize);\n }\n final int[] indices = new int[dimension];\n int count = 0;\n for (int i = 0; i < last; i++) {\n int idx = 0;\n final int offset = uniCounterOffset[i];\n while (count <= index) {\n count += offset;\n ++idx;\n }\n --idx;\n count -= offset;\n indices[i] = idx;\n }\n indices[last] = index - count;\n return indices;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-56"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-56"}} {"sample_uid": "defects4j_function_repair::Math-79", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static double distance(int[] p1, int[] p2) {\n int sum = 0;\n for (int i = 0; i < p1.length; i++) {\n final int dp = p1[i] - p2[i];\n sum += dp * dp;\n }\n return Math.sqrt(sum);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static double distance(int[] p1, int[] p2) {\n int sum = 0;\n for (int i = 0; i < p1.length; i++) {\n final int dp = p1[i] - p2[i];\n sum += dp * dp;\n }\n return Math.sqrt(sum);\n }\n"}, "reference": " public static double distance(int[] p1, int[] p2) {\n double sum = 0;\n for (int i = 0; i < p1.length; i++) {\n final double dp = p1[i] - p2[i];\n sum += dp * dp;\n }\n return Math.sqrt(sum);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-79"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-79"}} {"sample_uid": "defects4j_function_repair::Jsoup-53", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String chompBalanced(char open, char close) {\n int start = -1;\n int end = -1;\n int depth = 0;\n char last = 0;\n do {\n if (isEmpty()) break;\n Character c = consume();\n if (last == 0 || last != ESC) {\n if (c.equals(open)) {\n depth++;\n if (start == -1)\n start = pos;\n }\n else if (c.equals(close))\n depth--;\n }\n if (depth > 0 && last != 0)\n end = pos; \n last = c;\n } while (depth > 0);\n return (end >= 0) ? queue.substring(start, end) : \"\";\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String chompBalanced(char open, char close) {\n int start = -1;\n int end = -1;\n int depth = 0;\n char last = 0;\n do {\n if (isEmpty()) break;\n Character c = consume();\n if (last == 0 || last != ESC) {\n if (c.equals(open)) {\n depth++;\n if (start == -1)\n start = pos;\n }\n else if (c.equals(close))\n depth--;\n }\n if (depth > 0 && last != 0)\n end = pos; \n last = c;\n } while (depth > 0);\n return (end >= 0) ? queue.substring(start, end) : \"\";\n }\n"}, "reference": " public String chompBalanced(char open, char close) {\n int start = -1;\n int end = -1;\n int depth = 0;\n char last = 0;\n boolean inQuote = false;\n do {\n if (isEmpty()) break;\n Character c = consume();\n if (last == 0 || last != ESC) {\n if (c.equals('\\'') || c.equals('\"') && c != open)\n inQuote = !inQuote;\n if (inQuote)\n continue;\n if (c.equals(open)) {\n depth++;\n if (start == -1)\n start = pos;\n }\n else if (c.equals(close))\n depth--;\n }\n if (depth > 0 && last != 0)\n end = pos; \n last = c;\n } while (depth > 0);\n return (end >= 0) ? queue.substring(start, end) : \"\";\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-53"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-53"}} {"sample_uid": "defects4j_function_repair::Closure-92", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void replace() {\n if (firstNode == null) {\n replacementNode = candidateDefinition;\n return;\n }\n if (candidateDefinition != null && explicitNode != null) {\n explicitNode.detachFromParent();\n compiler.reportCodeChange();\n replacementNode = candidateDefinition;\n if (NodeUtil.isExpressionNode(candidateDefinition)) {\n candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);\n Node assignNode = candidateDefinition.getFirstChild();\n Node nameNode = assignNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n Node valueNode = nameNode.getNext();\n assignNode.removeChild(nameNode);\n assignNode.removeChild(valueNode);\n nameNode.addChildToFront(valueNode);\n Node varNode = new Node(Token.VAR, nameNode);\n varNode.copyInformationFrom(candidateDefinition);\n candidateDefinition.getParent().replaceChild(\n candidateDefinition, varNode);\n nameNode.setJSDocInfo(assignNode.getJSDocInfo());\n compiler.reportCodeChange();\n replacementNode = varNode;\n }\n }\n } else {\n replacementNode = createDeclarationNode();\n if (firstModule == minimumModule) {\n firstNode.getParent().addChildBefore(replacementNode, firstNode);\n } else {\n int indexOfDot = namespace.indexOf('.');\n if (indexOfDot == -1) {\n compiler.getNodeForCodeInsertion(minimumModule)\n .addChildToBack(replacementNode);\n } else {\n ProvidedName parentName =\n providedNames.get(namespace.substring(0, indexOfDot));\n Preconditions.checkNotNull(parentName);\n Preconditions.checkNotNull(parentName.replacementNode);\n parentName.replacementNode.getParent().addChildAfter(\n replacementNode, parentName.replacementNode);\n }\n }\n if (explicitNode != null) {\n explicitNode.detachFromParent();\n }\n compiler.reportCodeChange();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void replace() {\n if (firstNode == null) {\n replacementNode = candidateDefinition;\n return;\n }\n if (candidateDefinition != null && explicitNode != null) {\n explicitNode.detachFromParent();\n compiler.reportCodeChange();\n replacementNode = candidateDefinition;\n if (NodeUtil.isExpressionNode(candidateDefinition)) {\n candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);\n Node assignNode = candidateDefinition.getFirstChild();\n Node nameNode = assignNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n Node valueNode = nameNode.getNext();\n assignNode.removeChild(nameNode);\n assignNode.removeChild(valueNode);\n nameNode.addChildToFront(valueNode);\n Node varNode = new Node(Token.VAR, nameNode);\n varNode.copyInformationFrom(candidateDefinition);\n candidateDefinition.getParent().replaceChild(\n candidateDefinition, varNode);\n nameNode.setJSDocInfo(assignNode.getJSDocInfo());\n compiler.reportCodeChange();\n replacementNode = varNode;\n }\n }\n } else {\n replacementNode = createDeclarationNode();\n if (firstModule == minimumModule) {\n firstNode.getParent().addChildBefore(replacementNode, firstNode);\n } else {\n int indexOfDot = namespace.indexOf('.');\n if (indexOfDot == -1) {\n compiler.getNodeForCodeInsertion(minimumModule)\n .addChildToBack(replacementNode);\n } else {\n ProvidedName parentName =\n providedNames.get(namespace.substring(0, indexOfDot));\n Preconditions.checkNotNull(parentName);\n Preconditions.checkNotNull(parentName.replacementNode);\n parentName.replacementNode.getParent().addChildAfter(\n replacementNode, parentName.replacementNode);\n }\n }\n if (explicitNode != null) {\n explicitNode.detachFromParent();\n }\n compiler.reportCodeChange();\n }\n }\n"}, "reference": " void replace() {\n if (firstNode == null) {\n replacementNode = candidateDefinition;\n return;\n }\n if (candidateDefinition != null && explicitNode != null) {\n explicitNode.detachFromParent();\n compiler.reportCodeChange();\n replacementNode = candidateDefinition;\n if (NodeUtil.isExpressionNode(candidateDefinition)) {\n candidateDefinition.putBooleanProp(Node.IS_NAMESPACE, true);\n Node assignNode = candidateDefinition.getFirstChild();\n Node nameNode = assignNode.getFirstChild();\n if (nameNode.getType() == Token.NAME) {\n Node valueNode = nameNode.getNext();\n assignNode.removeChild(nameNode);\n assignNode.removeChild(valueNode);\n nameNode.addChildToFront(valueNode);\n Node varNode = new Node(Token.VAR, nameNode);\n varNode.copyInformationFrom(candidateDefinition);\n candidateDefinition.getParent().replaceChild(\n candidateDefinition, varNode);\n nameNode.setJSDocInfo(assignNode.getJSDocInfo());\n compiler.reportCodeChange();\n replacementNode = varNode;\n }\n }\n } else {\n replacementNode = createDeclarationNode();\n if (firstModule == minimumModule) {\n firstNode.getParent().addChildBefore(replacementNode, firstNode);\n } else {\n int indexOfDot = namespace.lastIndexOf('.');\n if (indexOfDot == -1) {\n compiler.getNodeForCodeInsertion(minimumModule)\n .addChildToBack(replacementNode);\n } else {\n ProvidedName parentName =\n providedNames.get(namespace.substring(0, indexOfDot));\n Preconditions.checkNotNull(parentName);\n Preconditions.checkNotNull(parentName.replacementNode);\n parentName.replacementNode.getParent().addChildAfter(\n replacementNode, parentName.replacementNode);\n }\n }\n if (explicitNode != null) {\n explicitNode.detachFromParent();\n }\n compiler.reportCodeChange();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-92"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-92"}} {"sample_uid": "defects4j_function_repair::Compress-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void resolveLocalFileHeaderData(Map\n entriesWithoutUTF8Flag)\n throws IOException {\n for (ZipArchiveEntry ze : entries.keySet()) {\n OffsetEntry offsetEntry = entries.get(ze);\n long offset = offsetEntry.headerOffset;\n archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);\n byte[] b = new byte[SHORT];\n archive.readFully(b);\n int fileNameLen = ZipShort.getValue(b);\n archive.readFully(b);\n int extraFieldLen = ZipShort.getValue(b);\n int lenToSkip = fileNameLen;\n while (lenToSkip > 0) {\n int skipped = archive.skipBytes(lenToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip file name in\"\n + \" local file header\");\n }\n lenToSkip -= skipped;\n }\n byte[] localExtraData = new byte[extraFieldLen];\n archive.readFully(localExtraData);\n ze.setExtra(localExtraData);\n offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH\n + SHORT + SHORT + fileNameLen + extraFieldLen;\n if (entriesWithoutUTF8Flag.containsKey(ze)) {\n String orig = ze.getName();\n NameAndComment nc = entriesWithoutUTF8Flag.get(ze);\n ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name,\n nc.comment);\n if (!orig.equals(ze.getName())) {\n nameMap.remove(orig);\n nameMap.put(ze.getName(), ze);\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void resolveLocalFileHeaderData(Map\n entriesWithoutUTF8Flag)\n throws IOException {\n for (ZipArchiveEntry ze : entries.keySet()) {\n OffsetEntry offsetEntry = entries.get(ze);\n long offset = offsetEntry.headerOffset;\n archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);\n byte[] b = new byte[SHORT];\n archive.readFully(b);\n int fileNameLen = ZipShort.getValue(b);\n archive.readFully(b);\n int extraFieldLen = ZipShort.getValue(b);\n int lenToSkip = fileNameLen;\n while (lenToSkip > 0) {\n int skipped = archive.skipBytes(lenToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip file name in\"\n + \" local file header\");\n }\n lenToSkip -= skipped;\n }\n byte[] localExtraData = new byte[extraFieldLen];\n archive.readFully(localExtraData);\n ze.setExtra(localExtraData);\n offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH\n + SHORT + SHORT + fileNameLen + extraFieldLen;\n if (entriesWithoutUTF8Flag.containsKey(ze)) {\n String orig = ze.getName();\n NameAndComment nc = entriesWithoutUTF8Flag.get(ze);\n ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name,\n nc.comment);\n if (!orig.equals(ze.getName())) {\n nameMap.remove(orig);\n nameMap.put(ze.getName(), ze);\n }\n }\n }\n }\n"}, "reference": " private void resolveLocalFileHeaderData(Map\n entriesWithoutUTF8Flag)\n throws IOException {\n Map origMap =\n new LinkedHashMap(entries);\n entries.clear();\n for (ZipArchiveEntry ze : origMap.keySet()) {\n OffsetEntry offsetEntry = origMap.get(ze);\n long offset = offsetEntry.headerOffset;\n archive.seek(offset + LFH_OFFSET_FOR_FILENAME_LENGTH);\n byte[] b = new byte[SHORT];\n archive.readFully(b);\n int fileNameLen = ZipShort.getValue(b);\n archive.readFully(b);\n int extraFieldLen = ZipShort.getValue(b);\n int lenToSkip = fileNameLen;\n while (lenToSkip > 0) {\n int skipped = archive.skipBytes(lenToSkip);\n if (skipped <= 0) {\n throw new RuntimeException(\"failed to skip file name in\"\n + \" local file header\");\n }\n lenToSkip -= skipped;\n }\n byte[] localExtraData = new byte[extraFieldLen];\n archive.readFully(localExtraData);\n ze.setExtra(localExtraData);\n offsetEntry.dataOffset = offset + LFH_OFFSET_FOR_FILENAME_LENGTH\n + SHORT + SHORT + fileNameLen + extraFieldLen;\n if (entriesWithoutUTF8Flag.containsKey(ze)) {\n String orig = ze.getName();\n NameAndComment nc = entriesWithoutUTF8Flag.get(ze);\n ZipUtil.setNameAndCommentFromExtraFields(ze, nc.name,\n nc.comment);\n if (!orig.equals(ze.getName())) {\n nameMap.remove(orig);\n nameMap.put(ze.getName(), ze);\n }\n }\n entries.put(ze, offsetEntry);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-10"}} {"sample_uid": "defects4j_function_repair::Closure-121", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void inlineNonConstants(\n Var v, ReferenceCollection referenceInfo,\n boolean maybeModifiedArguments) {\n int refCount = referenceInfo.references.size();\n Reference declaration = referenceInfo.references.get(0);\n Reference init = referenceInfo.getInitializingReference();\n int firstRefAfterInit = (declaration == init) ? 2 : 3;\n if (refCount > 1 &&\n isImmutableAndWellDefinedVariable(v, referenceInfo)) {\n Node value;\n if (init != null) {\n value = init.getAssignedValue();\n } else {\n Node srcLocation = declaration.getNode();\n value = NodeUtil.newUndefinedNode(srcLocation);\n }\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n } else if (refCount == firstRefAfterInit) {\n Reference reference = referenceInfo.references.get(\n firstRefAfterInit - 1);\n if (canInline(declaration, init, reference)) {\n inline(v, declaration, init, reference);\n staleVars.add(v);\n }\n } else if (declaration != init && refCount == 2) {\n if (isValidDeclaration(declaration) && isValidInitialization(init)) {\n Node value = init.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n }\n }\n if (!maybeModifiedArguments &&\n !staleVars.contains(v) &&\n referenceInfo.isWellDefined() &&\n referenceInfo.isAssignedOnceInLifetime()) {\n List refs = referenceInfo.references;\n for (int i = 1 ; i < refs.size(); i++) {\n Node nameNode = refs.get(i).getNode();\n if (aliasCandidates.containsKey(nameNode)) {\n AliasCandidate candidate = aliasCandidates.get(nameNode);\n if (!staleVars.contains(candidate.alias) &&\n !isVarInlineForbidden(candidate.alias)) {\n Reference aliasInit;\n aliasInit = candidate.refInfo.getInitializingReference();\n Node value = aliasInit.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(candidate.alias,\n value,\n candidate.refInfo.references);\n staleVars.add(candidate.alias);\n }\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void inlineNonConstants(\n Var v, ReferenceCollection referenceInfo,\n boolean maybeModifiedArguments) {\n int refCount = referenceInfo.references.size();\n Reference declaration = referenceInfo.references.get(0);\n Reference init = referenceInfo.getInitializingReference();\n int firstRefAfterInit = (declaration == init) ? 2 : 3;\n if (refCount > 1 &&\n isImmutableAndWellDefinedVariable(v, referenceInfo)) {\n Node value;\n if (init != null) {\n value = init.getAssignedValue();\n } else {\n Node srcLocation = declaration.getNode();\n value = NodeUtil.newUndefinedNode(srcLocation);\n }\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n } else if (refCount == firstRefAfterInit) {\n Reference reference = referenceInfo.references.get(\n firstRefAfterInit - 1);\n if (canInline(declaration, init, reference)) {\n inline(v, declaration, init, reference);\n staleVars.add(v);\n }\n } else if (declaration != init && refCount == 2) {\n if (isValidDeclaration(declaration) && isValidInitialization(init)) {\n Node value = init.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n }\n }\n if (!maybeModifiedArguments &&\n !staleVars.contains(v) &&\n referenceInfo.isWellDefined() &&\n referenceInfo.isAssignedOnceInLifetime()) {\n List refs = referenceInfo.references;\n for (int i = 1 ; i < refs.size(); i++) {\n Node nameNode = refs.get(i).getNode();\n if (aliasCandidates.containsKey(nameNode)) {\n AliasCandidate candidate = aliasCandidates.get(nameNode);\n if (!staleVars.contains(candidate.alias) &&\n !isVarInlineForbidden(candidate.alias)) {\n Reference aliasInit;\n aliasInit = candidate.refInfo.getInitializingReference();\n Node value = aliasInit.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(candidate.alias,\n value,\n candidate.refInfo.references);\n staleVars.add(candidate.alias);\n }\n }\n }\n }\n }\n"}, "reference": " private void inlineNonConstants(\n Var v, ReferenceCollection referenceInfo,\n boolean maybeModifiedArguments) {\n int refCount = referenceInfo.references.size();\n Reference declaration = referenceInfo.references.get(0);\n Reference init = referenceInfo.getInitializingReference();\n int firstRefAfterInit = (declaration == init) ? 2 : 3;\n if (refCount > 1 &&\n isImmutableAndWellDefinedVariable(v, referenceInfo)) {\n Node value;\n if (init != null) {\n value = init.getAssignedValue();\n } else {\n Node srcLocation = declaration.getNode();\n value = NodeUtil.newUndefinedNode(srcLocation);\n }\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n } else if (refCount == firstRefAfterInit) {\n Reference reference = referenceInfo.references.get(\n firstRefAfterInit - 1);\n if (canInline(declaration, init, reference)) {\n inline(v, declaration, init, reference);\n staleVars.add(v);\n }\n } else if (declaration != init && refCount == 2) {\n if (isValidDeclaration(declaration) && isValidInitialization(init)) {\n Node value = init.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(v, value, referenceInfo.references);\n staleVars.add(v);\n }\n }\n if (!maybeModifiedArguments &&\n !staleVars.contains(v) &&\n referenceInfo.isWellDefined() &&\n referenceInfo.isAssignedOnceInLifetime() &&\n (isInlineableDeclaredConstant(v, referenceInfo) ||\n referenceInfo.isOnlyAssignmentSameScopeAsDeclaration())) {\n List refs = referenceInfo.references;\n for (int i = 1 ; i < refs.size(); i++) {\n Node nameNode = refs.get(i).getNode();\n if (aliasCandidates.containsKey(nameNode)) {\n AliasCandidate candidate = aliasCandidates.get(nameNode);\n if (!staleVars.contains(candidate.alias) &&\n !isVarInlineForbidden(candidate.alias)) {\n Reference aliasInit;\n aliasInit = candidate.refInfo.getInitializingReference();\n Node value = aliasInit.getAssignedValue();\n Preconditions.checkNotNull(value);\n inlineWellDefinedVariable(candidate.alias,\n value,\n candidate.refInfo.references);\n staleVars.add(candidate.alias);\n }\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-121"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-121"}} {"sample_uid": "defects4j_function_repair::Jsoup-59", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n final void newAttribute() {\n if (attributes == null)\n attributes = new Attributes();\n if (pendingAttributeName != null) {\n pendingAttributeName = pendingAttributeName.trim();\n Attribute attribute;\n if (hasPendingAttributeValue)\n attribute = new Attribute(pendingAttributeName,\n pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS);\n else if (hasEmptyAttributeValue)\n attribute = new Attribute(pendingAttributeName, \"\");\n else\n attribute = new BooleanAttribute(pendingAttributeName);\n attributes.put(attribute);\n }\n pendingAttributeName = null;\n hasEmptyAttributeValue = false;\n hasPendingAttributeValue = false;\n reset(pendingAttributeValue);\n pendingAttributeValueS = null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " final void newAttribute() {\n if (attributes == null)\n attributes = new Attributes();\n if (pendingAttributeName != null) {\n pendingAttributeName = pendingAttributeName.trim();\n Attribute attribute;\n if (hasPendingAttributeValue)\n attribute = new Attribute(pendingAttributeName,\n pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS);\n else if (hasEmptyAttributeValue)\n attribute = new Attribute(pendingAttributeName, \"\");\n else\n attribute = new BooleanAttribute(pendingAttributeName);\n attributes.put(attribute);\n }\n pendingAttributeName = null;\n hasEmptyAttributeValue = false;\n hasPendingAttributeValue = false;\n reset(pendingAttributeValue);\n pendingAttributeValueS = null;\n }\n"}, "reference": " final void newAttribute() {\n if (attributes == null)\n attributes = new Attributes();\n if (pendingAttributeName != null) {\n pendingAttributeName = pendingAttributeName.trim();\n if (pendingAttributeName.length() > 0) {\n Attribute attribute;\n if (hasPendingAttributeValue)\n attribute = new Attribute(pendingAttributeName,\n pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS);\n else if (hasEmptyAttributeValue)\n attribute = new Attribute(pendingAttributeName, \"\");\n else\n attribute = new BooleanAttribute(pendingAttributeName);\n attributes.put(attribute);\n }\n }\n pendingAttributeName = null;\n hasEmptyAttributeValue = false;\n hasPendingAttributeValue = false;\n reset(pendingAttributeValue);\n pendingAttributeValueS = null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-59"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-59"}} {"sample_uid": "defects4j_function_repair::Lang-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int translate(CharSequence input, int index, Writer out) throws IOException {\n if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') {\n int start = index + 2;\n boolean isHex = false;\n char firstChar = input.charAt(start);\n if(firstChar == 'x' || firstChar == 'X') {\n start++;\n isHex = true;\n }\n int end = start;\n while(input.charAt(end) != ';') {\n end++;\n }\n int entityValue;\n try {\n if(isHex) {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);\n } else {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);\n }\n } catch(NumberFormatException nfe) {\n return 0;\n }\n out.write(entityValue);\n return 2 + (end - start) + (isHex ? 1 : 0) + 1;\n }\n return 0;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int translate(CharSequence input, int index, Writer out) throws IOException {\n if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') {\n int start = index + 2;\n boolean isHex = false;\n char firstChar = input.charAt(start);\n if(firstChar == 'x' || firstChar == 'X') {\n start++;\n isHex = true;\n }\n int end = start;\n while(input.charAt(end) != ';') {\n end++;\n }\n int entityValue;\n try {\n if(isHex) {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);\n } else {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);\n }\n } catch(NumberFormatException nfe) {\n return 0;\n }\n out.write(entityValue);\n return 2 + (end - start) + (isHex ? 1 : 0) + 1;\n }\n return 0;\n }\n"}, "reference": " public int translate(CharSequence input, int index, Writer out) throws IOException {\n if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') {\n int start = index + 2;\n boolean isHex = false;\n char firstChar = input.charAt(start);\n if(firstChar == 'x' || firstChar == 'X') {\n start++;\n isHex = true;\n }\n int end = start;\n while(input.charAt(end) != ';') {\n end++;\n }\n int entityValue;\n try {\n if(isHex) {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);\n } else {\n entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);\n }\n } catch(NumberFormatException nfe) {\n return 0;\n }\n if(entityValue > 0xFFFF) {\n char[] chrs = Character.toChars(entityValue);\n out.write(chrs[0]);\n out.write(chrs[1]);\n } else {\n out.write(entityValue);\n }\n return 2 + (end - start) + (isHex ? 1 : 0) + 1;\n }\n return 0;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-28"}} {"sample_uid": "defects4j_function_repair::Math-87", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Integer getBasicRow(final int col) {\n Integer row = null;\n for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {\n if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {\n if (row == null) {\n row = i;\n } else {\n return null;\n }\n }\n }\n return row;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Integer getBasicRow(final int col) {\n Integer row = null;\n for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {\n if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {\n if (row == null) {\n row = i;\n } else {\n return null;\n }\n }\n }\n return row;\n }\n"}, "reference": " private Integer getBasicRow(final int col) {\n Integer row = null;\n for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) {\n if (MathUtils.equals(getEntry(i, col), 1.0, epsilon) && (row == null)) {\n row = i;\n } else if (!MathUtils.equals(getEntry(i, col), 0.0, epsilon)) {\n return null;\n }\n }\n return row;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-87"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-87"}} {"sample_uid": "defects4j_function_repair::JacksonCore-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public DefaultPrettyPrinter createInstance() {\n return new DefaultPrettyPrinter(this);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public DefaultPrettyPrinter createInstance() {\n return new DefaultPrettyPrinter(this);\n }\n"}, "reference": " public DefaultPrettyPrinter createInstance() {\n if (getClass() != DefaultPrettyPrinter.class) { \n throw new IllegalStateException(\"Failed `createInstance()`: \"+getClass().getName()\n +\" does not override method; it has to\");\n }\n return new DefaultPrettyPrinter(this);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-23"}} {"sample_uid": "defects4j_function_repair::Closure-122", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void handleBlockComment(Comment comment) {\n if (comment.getValue().indexOf(\"/* @\") != -1 || comment.getValue().indexOf(\"\\n * @\") != -1) {\n errorReporter.warning(\n SUSPICIOUS_COMMENT_WARNING,\n sourceName,\n comment.getLineno(), \"\", 0);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void handleBlockComment(Comment comment) {\n if (comment.getValue().indexOf(\"/* @\") != -1 || comment.getValue().indexOf(\"\\n * @\") != -1) {\n errorReporter.warning(\n SUSPICIOUS_COMMENT_WARNING,\n sourceName,\n comment.getLineno(), \"\", 0);\n }\n }\n"}, "reference": " private void handleBlockComment(Comment comment) {\n Pattern p = Pattern.compile(\"(/|(\\n[ \\t]*))\\\\*[ \\t]*@[a-zA-Z]\");\n if (p.matcher(comment.getValue()).find()) {\n errorReporter.warning(\n SUSPICIOUS_COMMENT_WARNING,\n sourceName,\n comment.getLineno(), \"\", 0);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-122"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-122"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)\n {\n final int mask = (1 << typeIndex);\n _hasNonDefaultCreator = true;\n AnnotatedWithParams oldOne = _creators[typeIndex];\n if (oldOne != null) {\n if ((_explicitCreators & mask) != 0) { \n if (!explicit) {\n return;\n }\n }\n if (oldOne.getClass() == newOne.getClass()) {\n throw new IllegalArgumentException(\"Conflicting \"+TYPE_DESCS[typeIndex]\n +\" creators: already had explicitly marked \"+oldOne+\", encountered \"+newOne);\n }\n }\n if (explicit) {\n _explicitCreators |= mask;\n }\n _creators[typeIndex] = _fixAccess(newOne);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)\n {\n final int mask = (1 << typeIndex);\n _hasNonDefaultCreator = true;\n AnnotatedWithParams oldOne = _creators[typeIndex];\n if (oldOne != null) {\n if ((_explicitCreators & mask) != 0) { \n if (!explicit) {\n return;\n }\n }\n if (oldOne.getClass() == newOne.getClass()) {\n throw new IllegalArgumentException(\"Conflicting \"+TYPE_DESCS[typeIndex]\n +\" creators: already had explicitly marked \"+oldOne+\", encountered \"+newOne);\n }\n }\n if (explicit) {\n _explicitCreators |= mask;\n }\n _creators[typeIndex] = _fixAccess(newOne);\n }\n"}, "reference": " protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)\n {\n final int mask = (1 << typeIndex);\n _hasNonDefaultCreator = true;\n AnnotatedWithParams oldOne = _creators[typeIndex];\n if (oldOne != null) {\n boolean verify;\n if ((_explicitCreators & mask) != 0) { \n if (!explicit) {\n return;\n }\n verify = true;\n } else {\n verify = !explicit;\n }\n if (verify && (oldOne.getClass() == newOne.getClass())) {\n Class oldType = oldOne.getRawParameterType(0);\n Class newType = newOne.getRawParameterType(0);\n if (oldType == newType) {\n throw new IllegalArgumentException(\"Conflicting \"+TYPE_DESCS[typeIndex]\n +\" creators: already had explicitly marked \"+oldOne+\", encountered \"+newOne);\n }\n if (newType.isAssignableFrom(oldType)) {\n return;\n }\n }\n }\n if (explicit) {\n _explicitCreators |= mask;\n }\n _creators[typeIndex] = _fixAccess(newOne);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-8"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-49", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Object generateId(Object forPojo) {\n id = generator.generateId(forPojo);\n return id;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Object generateId(Object forPojo) {\n id = generator.generateId(forPojo);\n return id;\n }\n"}, "reference": " public Object generateId(Object forPojo) {\n if (id == null) {\n id = generator.generateId(forPojo);\n }\n return id;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-49"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-49"}} {"sample_uid": "defects4j_function_repair::Jsoup-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static String unescape(String string) {\n if (!string.contains(\"&\"))\n return string;\n Matcher m = unescapePattern.matcher(string); \n StringBuffer accum = new StringBuffer(string.length()); \n while (m.find()) {\n int charval = -1;\n String num = m.group(3);\n if (num != null) {\n try {\n int base = m.group(2) != null ? 16 : 10; \n charval = Integer.valueOf(num, base);\n } catch (NumberFormatException e) {\n } \n } else {\n String name = m.group(1);\n if (full.containsKey(name))\n charval = full.get(name);\n }\n if (charval != -1 || charval > 0xFFFF) { \n String c = Character.toString((char) charval);\n m.appendReplacement(accum, c);\n } else {\n m.appendReplacement(accum, m.group(0));\n }\n }\n m.appendTail(accum);\n return accum.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static String unescape(String string) {\n if (!string.contains(\"&\"))\n return string;\n Matcher m = unescapePattern.matcher(string); \n StringBuffer accum = new StringBuffer(string.length()); \n while (m.find()) {\n int charval = -1;\n String num = m.group(3);\n if (num != null) {\n try {\n int base = m.group(2) != null ? 16 : 10; \n charval = Integer.valueOf(num, base);\n } catch (NumberFormatException e) {\n } \n } else {\n String name = m.group(1);\n if (full.containsKey(name))\n charval = full.get(name);\n }\n if (charval != -1 || charval > 0xFFFF) { \n String c = Character.toString((char) charval);\n m.appendReplacement(accum, c);\n } else {\n m.appendReplacement(accum, m.group(0));\n }\n }\n m.appendTail(accum);\n return accum.toString();\n }\n"}, "reference": " static String unescape(String string) {\n if (!string.contains(\"&\"))\n return string;\n Matcher m = unescapePattern.matcher(string); \n StringBuffer accum = new StringBuffer(string.length()); \n while (m.find()) {\n int charval = -1;\n String num = m.group(3);\n if (num != null) {\n try {\n int base = m.group(2) != null ? 16 : 10; \n charval = Integer.valueOf(num, base);\n } catch (NumberFormatException e) {\n } \n } else {\n String name = m.group(1);\n if (full.containsKey(name))\n charval = full.get(name);\n }\n if (charval != -1 || charval > 0xFFFF) { \n String c = Character.toString((char) charval);\n m.appendReplacement(accum, Matcher.quoteReplacement(c));\n } else {\n m.appendReplacement(accum, Matcher.quoteReplacement(m.group(0))); \n }\n }\n m.appendTail(accum);\n return accum.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-6"}} {"sample_uid": "defects4j_function_repair::Cli-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)\n {\n List tokens = new ArrayList();\n boolean eatTheRest = false;\n for (int i = 0; i < arguments.length; i++)\n {\n String arg = arguments[i];\n if (\"--\".equals(arg))\n {\n eatTheRest = true;\n tokens.add(\"--\");\n }\n else if (\"-\".equals(arg))\n {\n tokens.add(\"-\");\n }\n else if (arg.startsWith(\"-\"))\n {\n String opt = Util.stripLeadingHyphens(arg);\n if (options.hasOption(opt))\n {\n tokens.add(arg);\n }\n else\n {\n if (options.hasOption(arg.substring(0, 2)))\n {\n tokens.add(arg.substring(0, 2)); \n tokens.add(arg.substring(2)); \n }\n else\n {\n eatTheRest = stopAtNonOption;\n tokens.add(arg);\n }\n }\n }\n else\n {\n tokens.add(arg);\n }\n if (eatTheRest)\n {\n for (i++; i < arguments.length; i++)\n {\n tokens.add(arguments[i]);\n }\n }\n }\n return (String[]) tokens.toArray(new String[tokens.size()]);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)\n {\n List tokens = new ArrayList();\n boolean eatTheRest = false;\n for (int i = 0; i < arguments.length; i++)\n {\n String arg = arguments[i];\n if (\"--\".equals(arg))\n {\n eatTheRest = true;\n tokens.add(\"--\");\n }\n else if (\"-\".equals(arg))\n {\n tokens.add(\"-\");\n }\n else if (arg.startsWith(\"-\"))\n {\n String opt = Util.stripLeadingHyphens(arg);\n if (options.hasOption(opt))\n {\n tokens.add(arg);\n }\n else\n {\n if (options.hasOption(arg.substring(0, 2)))\n {\n tokens.add(arg.substring(0, 2)); \n tokens.add(arg.substring(2)); \n }\n else\n {\n eatTheRest = stopAtNonOption;\n tokens.add(arg);\n }\n }\n }\n else\n {\n tokens.add(arg);\n }\n if (eatTheRest)\n {\n for (i++; i < arguments.length; i++)\n {\n tokens.add(arguments[i]);\n }\n }\n }\n return (String[]) tokens.toArray(new String[tokens.size()]);\n }\n"}, "reference": " protected String[] flatten(Options options, String[] arguments, boolean stopAtNonOption)\n {\n List tokens = new ArrayList();\n boolean eatTheRest = false;\n for (int i = 0; i < arguments.length; i++)\n {\n String arg = arguments[i];\n if (\"--\".equals(arg))\n {\n eatTheRest = true;\n tokens.add(\"--\");\n }\n else if (\"-\".equals(arg))\n {\n tokens.add(\"-\");\n }\n else if (arg.startsWith(\"-\"))\n {\n String opt = Util.stripLeadingHyphens(arg);\n if (options.hasOption(opt))\n {\n tokens.add(arg);\n }\n else\n {\n if (opt.indexOf('=') != -1 && options.hasOption(opt.substring(0, opt.indexOf('='))))\n {\n tokens.add(arg.substring(0, arg.indexOf('='))); \n tokens.add(arg.substring(arg.indexOf('=') + 1)); \n }\n else if (options.hasOption(arg.substring(0, 2)))\n {\n tokens.add(arg.substring(0, 2)); \n tokens.add(arg.substring(2)); \n }\n else\n {\n eatTheRest = stopAtNonOption;\n tokens.add(arg);\n }\n }\n }\n else\n {\n tokens.add(arg);\n }\n if (eatTheRest)\n {\n for (i++; i < arguments.length; i++)\n {\n tokens.add(arguments[i]);\n }\n }\n }\n return (String[]) tokens.toArray(new String[tokens.size()]);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-12"}} {"sample_uid": "defects4j_function_repair::Codec-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void decode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n }\n for (int i = 0; i < inAvail; i++) {\n if (buffer == null || buffer.length - pos < decodeSize) {\n resizeBuffer();\n }\n byte b = in[inPos++];\n if (b == PAD) {\n eof = true;\n break;\n } else {\n if (b >= 0 && b < DECODE_TABLE.length) {\n int result = DECODE_TABLE[b];\n if (result >= 0) {\n modulus = (++modulus) % 4;\n x = (x << 6) + result;\n if (modulus == 0) {\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n buffer[pos++] = (byte) (x & MASK_8BITS);\n }\n }\n }\n }\n }\n if (eof && modulus != 0) {\n x = x << 6;\n switch (modulus) {\n case 2 :\n x = x << 6;\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n break;\n case 3 :\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n break;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void decode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n }\n for (int i = 0; i < inAvail; i++) {\n if (buffer == null || buffer.length - pos < decodeSize) {\n resizeBuffer();\n }\n byte b = in[inPos++];\n if (b == PAD) {\n eof = true;\n break;\n } else {\n if (b >= 0 && b < DECODE_TABLE.length) {\n int result = DECODE_TABLE[b];\n if (result >= 0) {\n modulus = (++modulus) % 4;\n x = (x << 6) + result;\n if (modulus == 0) {\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n buffer[pos++] = (byte) (x & MASK_8BITS);\n }\n }\n }\n }\n }\n if (eof && modulus != 0) {\n x = x << 6;\n switch (modulus) {\n case 2 :\n x = x << 6;\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n break;\n case 3 :\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n break;\n }\n }\n }\n"}, "reference": " void decode(byte[] in, int inPos, int inAvail) {\n if (eof) {\n return;\n }\n if (inAvail < 0) {\n eof = true;\n }\n for (int i = 0; i < inAvail; i++) {\n if (buffer == null || buffer.length - pos < decodeSize) {\n resizeBuffer();\n }\n byte b = in[inPos++];\n if (b == PAD) {\n eof = true;\n break;\n } else {\n if (b >= 0 && b < DECODE_TABLE.length) {\n int result = DECODE_TABLE[b];\n if (result >= 0) {\n modulus = (++modulus) % 4;\n x = (x << 6) + result;\n if (modulus == 0) {\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n buffer[pos++] = (byte) (x & MASK_8BITS);\n }\n }\n }\n }\n }\n if (eof && modulus != 0) {\n if (buffer == null || buffer.length - pos < decodeSize) {\n resizeBuffer();\n }\n x = x << 6;\n switch (modulus) {\n case 2 :\n x = x << 6;\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n break;\n case 3 :\n buffer[pos++] = (byte) ((x >> 16) & MASK_8BITS);\n buffer[pos++] = (byte) ((x >> 8) & MASK_8BITS);\n break;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-5"}} {"sample_uid": "defects4j_function_repair::Chart-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected AxisState drawLabel(String label, Graphics2D g2, \n Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, \n AxisState state, PlotRenderingInfo plotState) {\n if (state == null) {\n throw new IllegalArgumentException(\"Null 'state' argument.\");\n }\n if ((label == null) || (label.equals(\"\"))) {\n return state;\n }\n Font font = getLabelFont();\n RectangleInsets insets = getLabelInsets();\n g2.setFont(font);\n g2.setPaint(getLabelPaint());\n FontMetrics fm = g2.getFontMetrics();\n Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm);\n Shape hotspot = null;\n if (edge == RectangleEdge.TOP) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() - insets.getBottom() \n - h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorUp(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.BOTTOM) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() + insets.getTop() \n + h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorDown(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.LEFT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() - insets.getRight() \n - w / 2.0);\n float labely = (float) dataArea.getCenterY();\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorLeft(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n else if (edge == RectangleEdge.RIGHT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() + Math.PI / 2.0, \n labelBounds.getCenterX(), labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() \n + insets.getLeft() + w / 2.0);\n float labely = (float) (dataArea.getY() + dataArea.getHeight() \n / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorRight(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n if (plotState != null && hotspot != null) {\n ChartRenderingInfo owner = plotState.getOwner();\n EntityCollection entities = owner.getEntityCollection();\n if (entities != null) {\n entities.add(new AxisLabelEntity(this, hotspot, \n this.labelToolTip, this.labelURL));\n }\n }\n return state;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected AxisState drawLabel(String label, Graphics2D g2, \n Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, \n AxisState state, PlotRenderingInfo plotState) {\n if (state == null) {\n throw new IllegalArgumentException(\"Null 'state' argument.\");\n }\n if ((label == null) || (label.equals(\"\"))) {\n return state;\n }\n Font font = getLabelFont();\n RectangleInsets insets = getLabelInsets();\n g2.setFont(font);\n g2.setPaint(getLabelPaint());\n FontMetrics fm = g2.getFontMetrics();\n Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm);\n Shape hotspot = null;\n if (edge == RectangleEdge.TOP) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() - insets.getBottom() \n - h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorUp(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.BOTTOM) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() + insets.getTop() \n + h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorDown(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.LEFT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() - insets.getRight() \n - w / 2.0);\n float labely = (float) dataArea.getCenterY();\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorLeft(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n else if (edge == RectangleEdge.RIGHT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() + Math.PI / 2.0, \n labelBounds.getCenterX(), labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() \n + insets.getLeft() + w / 2.0);\n float labely = (float) (dataArea.getY() + dataArea.getHeight() \n / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorRight(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n if (plotState != null && hotspot != null) {\n ChartRenderingInfo owner = plotState.getOwner();\n EntityCollection entities = owner.getEntityCollection();\n if (entities != null) {\n entities.add(new AxisLabelEntity(this, hotspot, \n this.labelToolTip, this.labelURL));\n }\n }\n return state;\n }\n"}, "reference": " protected AxisState drawLabel(String label, Graphics2D g2, \n Rectangle2D plotArea, Rectangle2D dataArea, RectangleEdge edge, \n AxisState state, PlotRenderingInfo plotState) {\n if (state == null) {\n throw new IllegalArgumentException(\"Null 'state' argument.\");\n }\n if ((label == null) || (label.equals(\"\"))) {\n return state;\n }\n Font font = getLabelFont();\n RectangleInsets insets = getLabelInsets();\n g2.setFont(font);\n g2.setPaint(getLabelPaint());\n FontMetrics fm = g2.getFontMetrics();\n Rectangle2D labelBounds = TextUtilities.getTextBounds(label, g2, fm);\n Shape hotspot = null;\n if (edge == RectangleEdge.TOP) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() - insets.getBottom() \n - h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorUp(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.BOTTOM) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle(), labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) dataArea.getCenterX();\n float labely = (float) (state.getCursor() + insets.getTop() \n + h / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle(), TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorDown(insets.getTop() + labelBounds.getHeight() \n + insets.getBottom());\n }\n else if (edge == RectangleEdge.LEFT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() - Math.PI / 2.0, labelBounds.getCenterX(), \n labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() - insets.getRight() \n - w / 2.0);\n float labely = (float) dataArea.getCenterY();\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() - Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorLeft(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n else if (edge == RectangleEdge.RIGHT) {\n AffineTransform t = AffineTransform.getRotateInstance(\n getLabelAngle() + Math.PI / 2.0, \n labelBounds.getCenterX(), labelBounds.getCenterY());\n Shape rotatedLabelBounds = t.createTransformedShape(labelBounds);\n labelBounds = rotatedLabelBounds.getBounds2D();\n float w = (float) labelBounds.getWidth();\n float h = (float) labelBounds.getHeight();\n float labelx = (float) (state.getCursor() \n + insets.getLeft() + w / 2.0);\n float labely = (float) (dataArea.getY() + dataArea.getHeight() \n / 2.0);\n TextUtilities.drawRotatedString(label, g2, labelx, labely, \n TextAnchor.CENTER, getLabelAngle() + Math.PI / 2.0, \n TextAnchor.CENTER);\n hotspot = new Rectangle2D.Float(labelx - w / 2.0f, \n labely - h / 2.0f, w, h);\n state.cursorRight(insets.getLeft() + labelBounds.getWidth() \n + insets.getRight());\n }\n if (plotState != null && hotspot != null) {\n ChartRenderingInfo owner = plotState.getOwner();\n if (owner != null) {\n EntityCollection entities = owner.getEntityCollection();\n if (entities != null) {\n entities.add(new AxisLabelEntity(this, hotspot, \n this.labelToolTip, this.labelURL));\n }\n }\n }\n return state;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-26"}} {"sample_uid": "defects4j_function_repair::Math-105", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double getSumSquaredErrors() {\n return sumYY - sumXY * sumXY / sumXX;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double getSumSquaredErrors() {\n return sumYY - sumXY * sumXY / sumXX;\n }\n"}, "reference": " public double getSumSquaredErrors() {\n return Math.max(0d, sumYY - sumXY * sumXY / sumXX);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-105"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-105"}} {"sample_uid": "defects4j_function_repair::Time-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,\n int hourOfDay, int minuteOfHour,\n int secondOfMinute, int millisOfSecond)\n throws IllegalArgumentException\n {\n Chronology base;\n if ((base = getBase()) != null) {\n return base.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n }\n long instant;\n instant = iGregorianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant < iCutoverMillis) {\n instant = iJulianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant >= iCutoverMillis) {\n throw new IllegalArgumentException(\"Specified date does not exist\");\n }\n }\n return instant;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,\n int hourOfDay, int minuteOfHour,\n int secondOfMinute, int millisOfSecond)\n throws IllegalArgumentException\n {\n Chronology base;\n if ((base = getBase()) != null) {\n return base.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n }\n long instant;\n instant = iGregorianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant < iCutoverMillis) {\n instant = iJulianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant >= iCutoverMillis) {\n throw new IllegalArgumentException(\"Specified date does not exist\");\n }\n }\n return instant;\n }\n"}, "reference": " public long getDateTimeMillis(int year, int monthOfYear, int dayOfMonth,\n int hourOfDay, int minuteOfHour,\n int secondOfMinute, int millisOfSecond)\n throws IllegalArgumentException\n {\n Chronology base;\n if ((base = getBase()) != null) {\n return base.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n }\n long instant;\n try {\n instant = iGregorianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n } catch (IllegalFieldValueException ex) {\n if (monthOfYear != 2 || dayOfMonth != 29) {\n throw ex;\n }\n instant = iGregorianChronology.getDateTimeMillis\n (year, monthOfYear, 28,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant >= iCutoverMillis) {\n throw ex;\n }\n }\n if (instant < iCutoverMillis) {\n instant = iJulianChronology.getDateTimeMillis\n (year, monthOfYear, dayOfMonth,\n hourOfDay, minuteOfHour, secondOfMinute, millisOfSecond);\n if (instant >= iCutoverMillis) {\n throw new IllegalArgumentException(\"Specified date does not exist\");\n }\n }\n return instant;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-18"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-34", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException\n {\n if (_isInt) {\n visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);\n } else {\n Class h = handledType();\n if (h == BigDecimal.class) {\n visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);\n } else {\n visitor.expectNumberFormat(typeHint);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException\n {\n if (_isInt) {\n visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);\n } else {\n Class h = handledType();\n if (h == BigDecimal.class) {\n visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);\n } else {\n visitor.expectNumberFormat(typeHint);\n }\n }\n }\n"}, "reference": " public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException\n {\n if (_isInt) {\n visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);\n } else {\n Class h = handledType();\n if (h == BigDecimal.class) {\n visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_DECIMAL);\n } else {\n visitor.expectNumberFormat(typeHint);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-34"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-34"}} {"sample_uid": "defects4j_function_repair::Mockito-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void injectMockCandidate(Class awaitingInjectionClazz, Set mocks, Object fieldInstance) {\n for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {\n mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void injectMockCandidate(Class awaitingInjectionClazz, Set mocks, Object fieldInstance) {\n for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {\n mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();\n }\n }\n"}, "reference": " private void injectMockCandidate(Class awaitingInjectionClazz, Set mocks, Object fieldInstance) {\n for(Field field : orderedInstanceFieldsFrom(awaitingInjectionClazz)) {\n Object injected = mockCandidateFilter.filterCandidate(mocks, field, fieldInstance).thenInject();\n mocks.remove(injected);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-28"}} {"sample_uid": "defects4j_function_repair::Mockito-29", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void describeTo(Description description) {\n description.appendText(\"same(\");\n appendQuoting(description);\n description.appendText(wanted.toString());\n appendQuoting(description);\n description.appendText(\")\");\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void describeTo(Description description) {\n description.appendText(\"same(\");\n appendQuoting(description);\n description.appendText(wanted.toString());\n appendQuoting(description);\n description.appendText(\")\");\n }\n"}, "reference": " public void describeTo(Description description) {\n description.appendText(\"same(\");\n appendQuoting(description);\n description.appendText(wanted == null ? \"null\" : wanted.toString());\n appendQuoting(description);\n description.appendText(\")\");\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-29"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-29"}} {"sample_uid": "defects4j_function_repair::Lang-52", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz;\n sz = str.length();\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n if (ch > 0xfff) {\n out.write(\"\\\\u\" + hex(ch));\n } else if (ch > 0xff) {\n out.write(\"\\\\u0\" + hex(ch));\n } else if (ch > 0x7f) {\n out.write(\"\\\\u00\" + hex(ch));\n } else if (ch < 32) {\n switch (ch) {\n case '\\b':\n out.write('\\\\');\n out.write('b');\n break;\n case '\\n':\n out.write('\\\\');\n out.write('n');\n break;\n case '\\t':\n out.write('\\\\');\n out.write('t');\n break;\n case '\\f':\n out.write('\\\\');\n out.write('f');\n break;\n case '\\r':\n out.write('\\\\');\n out.write('r');\n break;\n default :\n if (ch > 0xf) {\n out.write(\"\\\\u00\" + hex(ch));\n } else {\n out.write(\"\\\\u000\" + hex(ch));\n }\n break;\n }\n } else {\n switch (ch) {\n case '\\'':\n if (escapeSingleQuote) {\n out.write('\\\\');\n }\n out.write('\\'');\n break;\n case '\"':\n out.write('\\\\');\n out.write('\"');\n break;\n case '\\\\':\n out.write('\\\\');\n out.write('\\\\');\n break;\n default :\n out.write(ch);\n break;\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz;\n sz = str.length();\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n if (ch > 0xfff) {\n out.write(\"\\\\u\" + hex(ch));\n } else if (ch > 0xff) {\n out.write(\"\\\\u0\" + hex(ch));\n } else if (ch > 0x7f) {\n out.write(\"\\\\u00\" + hex(ch));\n } else if (ch < 32) {\n switch (ch) {\n case '\\b':\n out.write('\\\\');\n out.write('b');\n break;\n case '\\n':\n out.write('\\\\');\n out.write('n');\n break;\n case '\\t':\n out.write('\\\\');\n out.write('t');\n break;\n case '\\f':\n out.write('\\\\');\n out.write('f');\n break;\n case '\\r':\n out.write('\\\\');\n out.write('r');\n break;\n default :\n if (ch > 0xf) {\n out.write(\"\\\\u00\" + hex(ch));\n } else {\n out.write(\"\\\\u000\" + hex(ch));\n }\n break;\n }\n } else {\n switch (ch) {\n case '\\'':\n if (escapeSingleQuote) {\n out.write('\\\\');\n }\n out.write('\\'');\n break;\n case '\"':\n out.write('\\\\');\n out.write('\"');\n break;\n case '\\\\':\n out.write('\\\\');\n out.write('\\\\');\n break;\n default :\n out.write(ch);\n break;\n }\n }\n }\n }\n"}, "reference": " private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (str == null) {\n return;\n }\n int sz;\n sz = str.length();\n for (int i = 0; i < sz; i++) {\n char ch = str.charAt(i);\n if (ch > 0xfff) {\n out.write(\"\\\\u\" + hex(ch));\n } else if (ch > 0xff) {\n out.write(\"\\\\u0\" + hex(ch));\n } else if (ch > 0x7f) {\n out.write(\"\\\\u00\" + hex(ch));\n } else if (ch < 32) {\n switch (ch) {\n case '\\b':\n out.write('\\\\');\n out.write('b');\n break;\n case '\\n':\n out.write('\\\\');\n out.write('n');\n break;\n case '\\t':\n out.write('\\\\');\n out.write('t');\n break;\n case '\\f':\n out.write('\\\\');\n out.write('f');\n break;\n case '\\r':\n out.write('\\\\');\n out.write('r');\n break;\n default :\n if (ch > 0xf) {\n out.write(\"\\\\u00\" + hex(ch));\n } else {\n out.write(\"\\\\u000\" + hex(ch));\n }\n break;\n }\n } else {\n switch (ch) {\n case '\\'':\n if (escapeSingleQuote) {\n out.write('\\\\');\n }\n out.write('\\'');\n break;\n case '\"':\n out.write('\\\\');\n out.write('\"');\n break;\n case '\\\\':\n out.write('\\\\');\n out.write('\\\\');\n break;\n case '/':\n out.write('\\\\');\n out.write('/');\n break;\n default :\n out.write(ch);\n break;\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-52"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-52"}} {"sample_uid": "defects4j_function_repair::Jsoup-34", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n int nextIndexOf(CharSequence seq) {\n char startChar = seq.charAt(0);\n for (int offset = pos; offset < length; offset++) {\n if (startChar != input[offset])\n while(++offset < length && startChar != input[offset]);\n int i = offset + 1;\n int last = i + seq.length()-1;\n if (offset < length) {\n for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);\n if (i == last) \n return offset - pos;\n }\n }\n return -1;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " int nextIndexOf(CharSequence seq) {\n char startChar = seq.charAt(0);\n for (int offset = pos; offset < length; offset++) {\n if (startChar != input[offset])\n while(++offset < length && startChar != input[offset]);\n int i = offset + 1;\n int last = i + seq.length()-1;\n if (offset < length) {\n for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);\n if (i == last) \n return offset - pos;\n }\n }\n return -1;\n }\n"}, "reference": " int nextIndexOf(CharSequence seq) {\n char startChar = seq.charAt(0);\n for (int offset = pos; offset < length; offset++) {\n if (startChar != input[offset])\n while(++offset < length && startChar != input[offset]);\n int i = offset + 1;\n int last = i + seq.length()-1;\n if (offset < length && last <= length) {\n for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);\n if (i == last) \n return offset - pos;\n }\n }\n return -1;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-34"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-34"}} {"sample_uid": "defects4j_function_repair::Closure-86", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean evaluatesToLocalValue(Node value, Predicate locals) {\n switch (value.getType()) {\n case Token.ASSIGN:\n return NodeUtil.isImmutableValue(value.getLastChild())\n || (locals.apply(value)\n && evaluatesToLocalValue(value.getLastChild(), locals));\n case Token.COMMA:\n return evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.AND:\n case Token.OR:\n return evaluatesToLocalValue(value.getFirstChild(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.HOOK:\n return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.INC:\n case Token.DEC:\n if (value.getBooleanProp(Node.INCRDECR_PROP)) {\n return evaluatesToLocalValue(value.getFirstChild(), locals);\n } else {\n return true;\n }\n case Token.THIS:\n return locals.apply(value);\n case Token.NAME:\n return isImmutableValue(value) || locals.apply(value);\n case Token.GETELEM:\n case Token.GETPROP:\n return locals.apply(value);\n case Token.CALL:\n return callHasLocalResult(value)\n || isToStringMethodCall(value)\n || locals.apply(value);\n case Token.NEW:\n return true;\n case Token.FUNCTION:\n case Token.REGEXP:\n case Token.ARRAYLIT:\n case Token.OBJECTLIT:\n return true;\n case Token.IN:\n return true;\n default:\n if (isAssignmentOp(value)\n || isSimpleOperator(value)\n || isImmutableValue(value)) {\n return true;\n }\n throw new IllegalStateException(\n \"Unexpected expression node\" + value +\n \"\\n parent:\" + value.getParent());\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean evaluatesToLocalValue(Node value, Predicate locals) {\n switch (value.getType()) {\n case Token.ASSIGN:\n return NodeUtil.isImmutableValue(value.getLastChild())\n || (locals.apply(value)\n && evaluatesToLocalValue(value.getLastChild(), locals));\n case Token.COMMA:\n return evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.AND:\n case Token.OR:\n return evaluatesToLocalValue(value.getFirstChild(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.HOOK:\n return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.INC:\n case Token.DEC:\n if (value.getBooleanProp(Node.INCRDECR_PROP)) {\n return evaluatesToLocalValue(value.getFirstChild(), locals);\n } else {\n return true;\n }\n case Token.THIS:\n return locals.apply(value);\n case Token.NAME:\n return isImmutableValue(value) || locals.apply(value);\n case Token.GETELEM:\n case Token.GETPROP:\n return locals.apply(value);\n case Token.CALL:\n return callHasLocalResult(value)\n || isToStringMethodCall(value)\n || locals.apply(value);\n case Token.NEW:\n return true;\n case Token.FUNCTION:\n case Token.REGEXP:\n case Token.ARRAYLIT:\n case Token.OBJECTLIT:\n return true;\n case Token.IN:\n return true;\n default:\n if (isAssignmentOp(value)\n || isSimpleOperator(value)\n || isImmutableValue(value)) {\n return true;\n }\n throw new IllegalStateException(\n \"Unexpected expression node\" + value +\n \"\\n parent:\" + value.getParent());\n }\n }\n"}, "reference": " static boolean evaluatesToLocalValue(Node value, Predicate locals) {\n switch (value.getType()) {\n case Token.ASSIGN:\n return NodeUtil.isImmutableValue(value.getLastChild())\n || (locals.apply(value)\n && evaluatesToLocalValue(value.getLastChild(), locals));\n case Token.COMMA:\n return evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.AND:\n case Token.OR:\n return evaluatesToLocalValue(value.getFirstChild(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.HOOK:\n return evaluatesToLocalValue(value.getFirstChild().getNext(), locals)\n && evaluatesToLocalValue(value.getLastChild(), locals);\n case Token.INC:\n case Token.DEC:\n if (value.getBooleanProp(Node.INCRDECR_PROP)) {\n return evaluatesToLocalValue(value.getFirstChild(), locals);\n } else {\n return true;\n }\n case Token.THIS:\n return locals.apply(value);\n case Token.NAME:\n return isImmutableValue(value) || locals.apply(value);\n case Token.GETELEM:\n case Token.GETPROP:\n return locals.apply(value);\n case Token.CALL:\n return callHasLocalResult(value)\n || isToStringMethodCall(value)\n || locals.apply(value);\n case Token.NEW:\n return false;\n case Token.FUNCTION:\n case Token.REGEXP:\n case Token.ARRAYLIT:\n case Token.OBJECTLIT:\n return true;\n case Token.IN:\n return true;\n default:\n if (isAssignmentOp(value)\n || isSimpleOperator(value)\n || isImmutableValue(value)) {\n return true;\n }\n throw new IllegalStateException(\n \"Unexpected expression node\" + value +\n \"\\n parent:\" + value.getParent());\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-86"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-86"}} {"sample_uid": "defects4j_function_repair::Jsoup-32", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Element clone() {\n Element clone = (Element) super.clone();\n clone.classNames();\n return clone;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Element clone() {\n Element clone = (Element) super.clone();\n clone.classNames();\n return clone;\n }\n"}, "reference": " public Element clone() {\n Element clone = (Element) super.clone();\n clone.classNames = null; \n return clone;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-32"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-32"}} {"sample_uid": "defects4j_function_repair::Jsoup-64", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rawtext);\n tb.markInsertionMode();\n tb.transition(Text);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rawtext);\n tb.markInsertionMode();\n tb.transition(Text);\n }\n"}, "reference": " private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {\n tb.tokeniser.transition(TokeniserState.Rawtext);\n tb.markInsertionMode();\n tb.transition(Text);\n tb.insert(startTag);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-64"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-64"}} {"sample_uid": "defects4j_function_repair::Lang-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (chars != null && chars.length == 0) {\n throw new IllegalArgumentException(\"The chars array must not be empty\");\n }\n if (start == 0 && end == 0) {\n if (chars != null) {\n end = chars.length;\n } else {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (chars != null && chars.length == 0) {\n throw new IllegalArgumentException(\"The chars array must not be empty\");\n }\n if (start == 0 && end == 0) {\n if (chars != null) {\n end = chars.length;\n } else {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n"}, "reference": " public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (chars != null && chars.length == 0) {\n throw new IllegalArgumentException(\"The chars array must not be empty\");\n }\n if (start == 0 && end == 0) {\n if (chars != null) {\n end = chars.length;\n } else {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n } else {\n if (end <= start) {\n throw new IllegalArgumentException(\"Parameter end (\" + end + \") must be greater than start (\" + start + \")\");\n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-11"}} {"sample_uid": "defects4j_function_repair::Jsoup-46", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(c);\n break;\n case '<':\n if (!inAttribute)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(c);\n break;\n case '<':\n if (!inAttribute)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n"}, "reference": " static void escape(StringBuilder accum, String string, Document.OutputSettings out,\n boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {\n boolean lastWasWhite = false;\n boolean reachedNonWhite = false;\n final EscapeMode escapeMode = out.escapeMode();\n final CharsetEncoder encoder = out.encoder();\n final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());\n final Map map = escapeMode.getMap();\n final int length = string.length();\n int codePoint;\n for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {\n codePoint = string.codePointAt(offset);\n if (normaliseWhite) {\n if (StringUtil.isWhitespace(codePoint)) {\n if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)\n continue;\n accum.append(' ');\n lastWasWhite = true;\n continue;\n } else {\n lastWasWhite = false;\n reachedNonWhite = true;\n }\n }\n if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {\n final char c = (char) codePoint;\n switch (c) {\n case '&':\n accum.append(\"&\");\n break;\n case 0xA0:\n if (escapeMode != EscapeMode.xhtml)\n accum.append(\" \");\n else\n accum.append(\" \");\n break;\n case '<':\n if (!inAttribute)\n accum.append(\"<\");\n else\n accum.append(c);\n break;\n case '>':\n if (!inAttribute)\n accum.append(\">\");\n else\n accum.append(c);\n break;\n case '\"':\n if (inAttribute)\n accum.append(\""\");\n else\n accum.append(c);\n break;\n default:\n if (canEncode(coreCharset, c, encoder))\n accum.append(c);\n else if (map.containsKey(c))\n accum.append('&').append(map.get(c)).append(';');\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n } else {\n final String c = new String(Character.toChars(codePoint));\n if (encoder.canEncode(c)) \n accum.append(c);\n else\n accum.append(\"&#x\").append(Integer.toHexString(codePoint)).append(';');\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-46"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-46"}} {"sample_uid": "defects4j_function_repair::Math-58", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double[] fit() {\n final double[] guess = (new ParameterGuesser(getObservations())).guess();\n return fit(new Gaussian.Parametric(), guess);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double[] fit() {\n final double[] guess = (new ParameterGuesser(getObservations())).guess();\n return fit(new Gaussian.Parametric(), guess);\n }\n"}, "reference": " public double[] fit() {\n final double[] guess = (new ParameterGuesser(getObservations())).guess();\n return fit(guess);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-58"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-58"}} {"sample_uid": "defects4j_function_repair::Closure-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JSType caseObjectType(ObjectType type) {\n if (value.equals(\"function\")) {\n JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);\n return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null;\n }\n return matchesExpectation(\"object\") ? type : null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JSType caseObjectType(ObjectType type) {\n if (value.equals(\"function\")) {\n JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);\n return resultEqualsValue && ctorType.isSubtype(type) ? ctorType : null;\n }\n return matchesExpectation(\"object\") ? type : null;\n }\n"}, "reference": " public JSType caseObjectType(ObjectType type) {\n if (value.equals(\"function\")) {\n JSType ctorType = getNativeType(U2U_CONSTRUCTOR_TYPE);\n if (resultEqualsValue) {\n return ctorType.getGreatestSubtype(type);\n } else {\n return type.isSubtype(ctorType) ? null : type;\n }\n }\n return matchesExpectation(\"object\") ? type : null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-7"}} {"sample_uid": "defects4j_function_repair::Closure-73", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c <= 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c <= 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n"}, "reference": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c < 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-73"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-73"}} {"sample_uid": "defects4j_function_repair::Cli-28", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void processProperties(Properties properties)\n {\n if (properties == null)\n {\n return;\n }\n for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)\n {\n String option = e.nextElement().toString();\n if (!cmd.hasOption(option))\n {\n Option opt = getOptions().getOption(option);\n String value = properties.getProperty(option);\n if (opt.hasArg())\n {\n if (opt.getValues() == null || opt.getValues().length == 0)\n {\n try\n {\n opt.addValueForProcessing(value);\n }\n catch (RuntimeException exp)\n {\n }\n }\n }\n else if (!(\"yes\".equalsIgnoreCase(value)\n || \"true\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)))\n {\n break;\n }\n cmd.addOption(opt);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void processProperties(Properties properties)\n {\n if (properties == null)\n {\n return;\n }\n for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)\n {\n String option = e.nextElement().toString();\n if (!cmd.hasOption(option))\n {\n Option opt = getOptions().getOption(option);\n String value = properties.getProperty(option);\n if (opt.hasArg())\n {\n if (opt.getValues() == null || opt.getValues().length == 0)\n {\n try\n {\n opt.addValueForProcessing(value);\n }\n catch (RuntimeException exp)\n {\n }\n }\n }\n else if (!(\"yes\".equalsIgnoreCase(value)\n || \"true\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)))\n {\n break;\n }\n cmd.addOption(opt);\n }\n }\n }\n"}, "reference": " protected void processProperties(Properties properties)\n {\n if (properties == null)\n {\n return;\n }\n for (Enumeration e = properties.propertyNames(); e.hasMoreElements();)\n {\n String option = e.nextElement().toString();\n if (!cmd.hasOption(option))\n {\n Option opt = getOptions().getOption(option);\n String value = properties.getProperty(option);\n if (opt.hasArg())\n {\n if (opt.getValues() == null || opt.getValues().length == 0)\n {\n try\n {\n opt.addValueForProcessing(value);\n }\n catch (RuntimeException exp)\n {\n }\n }\n }\n else if (!(\"yes\".equalsIgnoreCase(value)\n || \"true\".equalsIgnoreCase(value)\n || \"1\".equalsIgnoreCase(value)))\n {\n continue;\n }\n cmd.addOption(opt);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-28"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-28"}} {"sample_uid": "defects4j_function_repair::Closure-77", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c <= 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c <= 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n"}, "reference": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c <= 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-77"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-77"}} {"sample_uid": "defects4j_function_repair::Cli-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static T createValue(final String str, final Class clazz) throws ParseException\n {\n if (PatternOptionBuilder.STRING_VALUE == clazz)\n {\n return (T) str;\n }\n else if (PatternOptionBuilder.OBJECT_VALUE == clazz)\n {\n return (T) createObject(str);\n }\n else if (PatternOptionBuilder.NUMBER_VALUE == clazz)\n {\n return (T) createNumber(str);\n }\n else if (PatternOptionBuilder.DATE_VALUE == clazz)\n {\n return (T) createDate(str);\n }\n else if (PatternOptionBuilder.CLASS_VALUE == clazz)\n {\n return (T) createClass(str);\n }\n else if (PatternOptionBuilder.FILE_VALUE == clazz)\n {\n return (T) createFile(str);\n }\n else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)\n {\n return (T) openFile(str);\n }\n else if (PatternOptionBuilder.FILES_VALUE == clazz)\n {\n return (T) createFiles(str);\n }\n else if (PatternOptionBuilder.URL_VALUE == clazz)\n {\n return (T) createURL(str);\n }\n else\n {\n return null;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static T createValue(final String str, final Class clazz) throws ParseException\n {\n if (PatternOptionBuilder.STRING_VALUE == clazz)\n {\n return (T) str;\n }\n else if (PatternOptionBuilder.OBJECT_VALUE == clazz)\n {\n return (T) createObject(str);\n }\n else if (PatternOptionBuilder.NUMBER_VALUE == clazz)\n {\n return (T) createNumber(str);\n }\n else if (PatternOptionBuilder.DATE_VALUE == clazz)\n {\n return (T) createDate(str);\n }\n else if (PatternOptionBuilder.CLASS_VALUE == clazz)\n {\n return (T) createClass(str);\n }\n else if (PatternOptionBuilder.FILE_VALUE == clazz)\n {\n return (T) createFile(str);\n }\n else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)\n {\n return (T) openFile(str);\n }\n else if (PatternOptionBuilder.FILES_VALUE == clazz)\n {\n return (T) createFiles(str);\n }\n else if (PatternOptionBuilder.URL_VALUE == clazz)\n {\n return (T) createURL(str);\n }\n else\n {\n return null;\n }\n }\n"}, "reference": " public static T createValue(final String str, final Class clazz) throws ParseException\n {\n if (PatternOptionBuilder.STRING_VALUE == clazz)\n {\n return (T) str;\n }\n else if (PatternOptionBuilder.OBJECT_VALUE == clazz)\n {\n return (T) createObject(str);\n }\n else if (PatternOptionBuilder.NUMBER_VALUE == clazz)\n {\n return (T) createNumber(str);\n }\n else if (PatternOptionBuilder.DATE_VALUE == clazz)\n {\n return (T) createDate(str);\n }\n else if (PatternOptionBuilder.CLASS_VALUE == clazz)\n {\n return (T) createClass(str);\n }\n else if (PatternOptionBuilder.FILE_VALUE == clazz)\n {\n return (T) createFile(str);\n }\n else if (PatternOptionBuilder.EXISTING_FILE_VALUE == clazz)\n {\n return (T) openFile(str);\n }\n else if (PatternOptionBuilder.FILES_VALUE == clazz)\n {\n return (T) createFiles(str);\n }\n else if (PatternOptionBuilder.URL_VALUE == clazz)\n {\n return (T) createURL(str);\n }\n else\n {\n throw new ParseException(\"Unable to handle the class: \" + clazz);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-40"}} {"sample_uid": "defects4j_function_repair::Lang-43", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private StringBuffer appendQuotedString(String pattern, ParsePosition pos,\n StringBuffer appendTo, boolean escapingOn) {\n int start = pos.getIndex();\n char[] c = pattern.toCharArray();\n if (escapingOn && c[start] == QUOTE) {\n return appendTo == null ? null : appendTo.append(QUOTE);\n }\n int lastHold = start;\n for (int i = pos.getIndex(); i < pattern.length(); i++) {\n if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) {\n appendTo.append(c, lastHold, pos.getIndex() - lastHold).append(\n QUOTE);\n pos.setIndex(i + ESCAPED_QUOTE.length());\n lastHold = pos.getIndex();\n continue;\n }\n switch (c[pos.getIndex()]) {\n case QUOTE:\n next(pos);\n return appendTo == null ? null : appendTo.append(c, lastHold,\n pos.getIndex() - lastHold);\n default:\n next(pos);\n }\n }\n throw new IllegalArgumentException(\n \"Unterminated quoted string at position \" + start);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private StringBuffer appendQuotedString(String pattern, ParsePosition pos,\n StringBuffer appendTo, boolean escapingOn) {\n int start = pos.getIndex();\n char[] c = pattern.toCharArray();\n if (escapingOn && c[start] == QUOTE) {\n return appendTo == null ? null : appendTo.append(QUOTE);\n }\n int lastHold = start;\n for (int i = pos.getIndex(); i < pattern.length(); i++) {\n if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) {\n appendTo.append(c, lastHold, pos.getIndex() - lastHold).append(\n QUOTE);\n pos.setIndex(i + ESCAPED_QUOTE.length());\n lastHold = pos.getIndex();\n continue;\n }\n switch (c[pos.getIndex()]) {\n case QUOTE:\n next(pos);\n return appendTo == null ? null : appendTo.append(c, lastHold,\n pos.getIndex() - lastHold);\n default:\n next(pos);\n }\n }\n throw new IllegalArgumentException(\n \"Unterminated quoted string at position \" + start);\n }\n"}, "reference": " private StringBuffer appendQuotedString(String pattern, ParsePosition pos,\n StringBuffer appendTo, boolean escapingOn) {\n int start = pos.getIndex();\n char[] c = pattern.toCharArray();\n if (escapingOn && c[start] == QUOTE) {\n next(pos);\n return appendTo == null ? null : appendTo.append(QUOTE);\n }\n int lastHold = start;\n for (int i = pos.getIndex(); i < pattern.length(); i++) {\n if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) {\n appendTo.append(c, lastHold, pos.getIndex() - lastHold).append(\n QUOTE);\n pos.setIndex(i + ESCAPED_QUOTE.length());\n lastHold = pos.getIndex();\n continue;\n }\n switch (c[pos.getIndex()]) {\n case QUOTE:\n next(pos);\n return appendTo == null ? null : appendTo.append(c, lastHold,\n pos.getIndex() - lastHold);\n default:\n next(pos);\n }\n }\n throw new IllegalArgumentException(\n \"Unterminated quoted string at position \" + start);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-43"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-43"}} {"sample_uid": "defects4j_function_repair::Compress-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean isDirectory() {\n if (file != null) {\n return file.isDirectory();\n }\n if (linkFlag == LF_DIR) {\n return true;\n }\n if (getName().endsWith(\"/\")) {\n return true;\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean isDirectory() {\n if (file != null) {\n return file.isDirectory();\n }\n if (linkFlag == LF_DIR) {\n return true;\n }\n if (getName().endsWith(\"/\")) {\n return true;\n }\n return false;\n }\n"}, "reference": " public boolean isDirectory() {\n if (file != null) {\n return file.isDirectory();\n }\n if (linkFlag == LF_DIR) {\n return true;\n }\n if (!isPaxHeader() && !isGlobalPaxHeader() && getName().endsWith(\"/\")) {\n return true;\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-38"}} {"sample_uid": "defects4j_function_repair::Time-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public long adjustOffset(long instant, boolean earlierOrLater) {\n long instantBefore = convertUTCToLocal(instant - 3 * DateTimeConstants.MILLIS_PER_HOUR);\n long instantAfter = convertUTCToLocal(instant + 3 * DateTimeConstants.MILLIS_PER_HOUR);\n if (instantBefore == instantAfter) {\n return instant; \n }\n long local = convertUTCToLocal(instant);\n return convertLocalToUTC(local, false, earlierOrLater ? instantAfter : instantBefore);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public long adjustOffset(long instant, boolean earlierOrLater) {\n long instantBefore = convertUTCToLocal(instant - 3 * DateTimeConstants.MILLIS_PER_HOUR);\n long instantAfter = convertUTCToLocal(instant + 3 * DateTimeConstants.MILLIS_PER_HOUR);\n if (instantBefore == instantAfter) {\n return instant; \n }\n long local = convertUTCToLocal(instant);\n return convertLocalToUTC(local, false, earlierOrLater ? instantAfter : instantBefore);\n }\n"}, "reference": " public long adjustOffset(long instant, boolean earlierOrLater) {\n long instantBefore = instant - 3 * DateTimeConstants.MILLIS_PER_HOUR;\n long instantAfter = instant + 3 * DateTimeConstants.MILLIS_PER_HOUR;\n long offsetBefore = getOffset(instantBefore);\n long offsetAfter = getOffset(instantAfter);\n if (offsetBefore <= offsetAfter) {\n return instant; \n }\n long diff = offsetBefore - offsetAfter;\n long transition = nextTransition(instantBefore);\n long overlapStart = transition - diff;\n long overlapEnd = transition + diff;\n if (instant < overlapStart || instant >= overlapEnd) {\n return instant; \n }\n long afterStart = instant - overlapStart;\n if (afterStart >= diff) {\n return earlierOrLater ? instant : instant - diff;\n } else {\n return earlierOrLater ? instant + diff : instant;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-17"}} {"sample_uid": "defects4j_function_repair::Math-45", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public OpenMapRealMatrix(int rowDimension, int columnDimension) {\n super(rowDimension, columnDimension);\n this.rows = rowDimension;\n this.columns = columnDimension;\n this.entries = new OpenIntToDoubleHashMap(0.0);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public OpenMapRealMatrix(int rowDimension, int columnDimension) {\n super(rowDimension, columnDimension);\n this.rows = rowDimension;\n this.columns = columnDimension;\n this.entries = new OpenIntToDoubleHashMap(0.0);\n }\n"}, "reference": " public OpenMapRealMatrix(int rowDimension, int columnDimension) {\n super(rowDimension, columnDimension);\n long lRow = (long) rowDimension;\n long lCol = (long) columnDimension;\n if (lRow * lCol >= (long) Integer.MAX_VALUE) {\n throw new NumberIsTooLargeException(lRow * lCol, Integer.MAX_VALUE, false);\n }\n this.rows = rowDimension;\n this.columns = columnDimension;\n this.entries = new OpenIntToDoubleHashMap(0.0);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-45"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-45"}} {"sample_uid": "defects4j_function_repair::Codec-9", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {\n if (binaryData == null || binaryData.length == 0) {\n return binaryData;\n }\n long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR);\n if (len > maxResultSize) {\n throw new IllegalArgumentException(\"Input array too big, the output array would be bigger (\" +\n len +\n \") than the specified maxium size of \" +\n maxResultSize);\n }\n Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);\n return b64.encode(binaryData);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {\n if (binaryData == null || binaryData.length == 0) {\n return binaryData;\n }\n long len = getEncodeLength(binaryData, MIME_CHUNK_SIZE, CHUNK_SEPARATOR);\n if (len > maxResultSize) {\n throw new IllegalArgumentException(\"Input array too big, the output array would be bigger (\" +\n len +\n \") than the specified maxium size of \" +\n maxResultSize);\n }\n Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);\n return b64.encode(binaryData);\n }\n"}, "reference": " public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {\n if (binaryData == null || binaryData.length == 0) {\n return binaryData;\n }\n long len = getEncodeLength(binaryData, isChunked ? MIME_CHUNK_SIZE : 0, CHUNK_SEPARATOR);\n if (len > maxResultSize) {\n throw new IllegalArgumentException(\"Input array too big, the output array would be bigger (\" +\n len +\n \") than the specified maxium size of \" +\n maxResultSize);\n }\n Base64 b64 = isChunked ? new Base64(urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);\n return b64.encode(binaryData);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-9"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-9"}} {"sample_uid": "defects4j_function_repair::Math-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void dropPhase1Objective() {\n if (getNumObjectiveFunctions() == 1) {\n return;\n }\n List columnsToDrop = new ArrayList();\n columnsToDrop.add(0);\n for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) {\n final double entry = tableau.getEntry(0, i);\n if (Precision.compareTo(entry, 0d, maxUlps) > 0) {\n columnsToDrop.add(i);\n }\n }\n for (int i = 0; i < getNumArtificialVariables(); i++) {\n int col = i + getArtificialVariableOffset();\n if (getBasicRow(col) == null) {\n columnsToDrop.add(col);\n }\n }\n double[][] matrix = new double[getHeight() - 1][getWidth() - columnsToDrop.size()];\n for (int i = 1; i < getHeight(); i++) {\n int col = 0;\n for (int j = 0; j < getWidth(); j++) {\n if (!columnsToDrop.contains(j)) {\n matrix[i - 1][col++] = tableau.getEntry(i, j);\n }\n }\n }\n for (int i = columnsToDrop.size() - 1; i >= 0; i--) {\n columnLabels.remove((int) columnsToDrop.get(i));\n }\n this.tableau = new Array2DRowRealMatrix(matrix);\n this.numArtificialVariables = 0;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void dropPhase1Objective() {\n if (getNumObjectiveFunctions() == 1) {\n return;\n }\n List columnsToDrop = new ArrayList();\n columnsToDrop.add(0);\n for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) {\n final double entry = tableau.getEntry(0, i);\n if (Precision.compareTo(entry, 0d, maxUlps) > 0) {\n columnsToDrop.add(i);\n }\n }\n for (int i = 0; i < getNumArtificialVariables(); i++) {\n int col = i + getArtificialVariableOffset();\n if (getBasicRow(col) == null) {\n columnsToDrop.add(col);\n }\n }\n double[][] matrix = new double[getHeight() - 1][getWidth() - columnsToDrop.size()];\n for (int i = 1; i < getHeight(); i++) {\n int col = 0;\n for (int j = 0; j < getWidth(); j++) {\n if (!columnsToDrop.contains(j)) {\n matrix[i - 1][col++] = tableau.getEntry(i, j);\n }\n }\n }\n for (int i = columnsToDrop.size() - 1; i >= 0; i--) {\n columnLabels.remove((int) columnsToDrop.get(i));\n }\n this.tableau = new Array2DRowRealMatrix(matrix);\n this.numArtificialVariables = 0;\n }\n"}, "reference": " protected void dropPhase1Objective() {\n if (getNumObjectiveFunctions() == 1) {\n return;\n }\n List columnsToDrop = new ArrayList();\n columnsToDrop.add(0);\n for (int i = getNumObjectiveFunctions(); i < getArtificialVariableOffset(); i++) {\n final double entry = tableau.getEntry(0, i);\n if (Precision.compareTo(entry, 0d, epsilon) > 0) {\n columnsToDrop.add(i);\n }\n }\n for (int i = 0; i < getNumArtificialVariables(); i++) {\n int col = i + getArtificialVariableOffset();\n if (getBasicRow(col) == null) {\n columnsToDrop.add(col);\n }\n }\n double[][] matrix = new double[getHeight() - 1][getWidth() - columnsToDrop.size()];\n for (int i = 1; i < getHeight(); i++) {\n int col = 0;\n for (int j = 0; j < getWidth(); j++) {\n if (!columnsToDrop.contains(j)) {\n matrix[i - 1][col++] = tableau.getEntry(i, j);\n }\n }\n }\n for (int i = columnsToDrop.size() - 1; i >= 0; i--) {\n columnLabels.remove((int) columnsToDrop.get(i));\n }\n this.tableau = new Array2DRowRealMatrix(matrix);\n this.numArtificialVariables = 0;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-33"}} {"sample_uid": "defects4j_function_repair::Jsoup-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void read(Tokeniser t, CharacterReader r) {\n if (r.matchesLetter()) {\n String name = r.consumeLetterSequence();\n t.tagPending.appendTagName(name.toLowerCase());\n t.dataBuffer.append(name);\n r.advance();\n return;\n }\n if (t.isAppropriateEndTagToken() && !r.isEmpty()) {\n char c = r.consume();\n switch (c) {\n case '\\t':\n case '\\n':\n case '\\f':\n case ' ':\n t.transition(BeforeAttributeName);\n break;\n case '/':\n t.transition(SelfClosingStartTag);\n break;\n case '>':\n t.emitTagPending();\n t.transition(Data);\n break;\n default:\n t.dataBuffer.append(c);\n anythingElse(t, r);\n break;\n }\n } else {\n anythingElse(t, r);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void read(Tokeniser t, CharacterReader r) {\n if (r.matchesLetter()) {\n String name = r.consumeLetterSequence();\n t.tagPending.appendTagName(name.toLowerCase());\n t.dataBuffer.append(name);\n r.advance();\n return;\n }\n if (t.isAppropriateEndTagToken() && !r.isEmpty()) {\n char c = r.consume();\n switch (c) {\n case '\\t':\n case '\\n':\n case '\\f':\n case ' ':\n t.transition(BeforeAttributeName);\n break;\n case '/':\n t.transition(SelfClosingStartTag);\n break;\n case '>':\n t.emitTagPending();\n t.transition(Data);\n break;\n default:\n t.dataBuffer.append(c);\n anythingElse(t, r);\n break;\n }\n } else {\n anythingElse(t, r);\n }\n }\n"}, "reference": " void read(Tokeniser t, CharacterReader r) {\n if (r.matchesLetter()) {\n String name = r.consumeLetterSequence();\n t.tagPending.appendTagName(name.toLowerCase());\n t.dataBuffer.append(name);\n return;\n }\n if (t.isAppropriateEndTagToken() && !r.isEmpty()) {\n char c = r.consume();\n switch (c) {\n case '\\t':\n case '\\n':\n case '\\f':\n case ' ':\n t.transition(BeforeAttributeName);\n break;\n case '/':\n t.transition(SelfClosingStartTag);\n break;\n case '>':\n t.emitTagPending();\n t.transition(Data);\n break;\n default:\n t.dataBuffer.append(c);\n anythingElse(t, r);\n break;\n }\n } else {\n anythingElse(t, r);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-24"}} {"sample_uid": "defects4j_function_repair::JacksonXml-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String nextTextValue() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n if (t == JsonToken.VALUE_STRING) {\n return _currText;\n }\n _updateState(t);\n return null;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n return null;\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n _currToken = JsonToken.FIELD_NAME;\n return null;\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _currToken = JsonToken.VALUE_STRING;\n return (_currText = \"\");\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n } else {\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n _currToken = JsonToken.FIELD_NAME;\n }\n break;\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currText = _xmlTokens.getText();\n _currToken = JsonToken.VALUE_STRING;\n break;\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n _currToken = JsonToken.VALUE_STRING;\n return _currText;\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n _currToken = JsonToken.FIELD_NAME;\n break;\n case XmlTokenStream.XML_END:\n _currToken = null;\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String nextTextValue() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n if (t == JsonToken.VALUE_STRING) {\n return _currText;\n }\n _updateState(t);\n return null;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n return null;\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n _currToken = JsonToken.FIELD_NAME;\n return null;\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _currToken = JsonToken.VALUE_STRING;\n return (_currText = \"\");\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n } else {\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n _currToken = JsonToken.FIELD_NAME;\n }\n break;\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currText = _xmlTokens.getText();\n _currToken = JsonToken.VALUE_STRING;\n break;\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n _currToken = JsonToken.VALUE_STRING;\n return _currText;\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n _currToken = JsonToken.FIELD_NAME;\n break;\n case XmlTokenStream.XML_END:\n _currToken = null;\n }\n return null;\n }\n"}, "reference": " public String nextTextValue() throws IOException\n {\n _binaryValue = null;\n if (_nextToken != null) {\n JsonToken t = _nextToken;\n _currToken = t;\n _nextToken = null;\n if (t == JsonToken.VALUE_STRING) {\n return _currText;\n }\n _updateState(t);\n return null;\n }\n int token = _xmlTokens.next();\n while (token == XmlTokenStream.XML_START_ELEMENT) {\n if (_mayBeLeaf) {\n _nextToken = JsonToken.FIELD_NAME;\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n return null;\n }\n if (_parsingContext.inArray()) {\n token = _xmlTokens.next();\n _mayBeLeaf = true;\n continue;\n }\n String name = _xmlTokens.getLocalName();\n _parsingContext.setCurrentName(name);\n if (_namesToWrap != null && _namesToWrap.contains(name)) {\n _xmlTokens.repeatStartElement();\n }\n _mayBeLeaf = true;\n _currToken = JsonToken.FIELD_NAME;\n return null;\n }\n switch (token) {\n case XmlTokenStream.XML_END_ELEMENT:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _currToken = JsonToken.VALUE_STRING;\n return (_currText = \"\");\n }\n _currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;\n _parsingContext = _parsingContext.getParent();\n _namesToWrap = _parsingContext.getNamesToWrap();\n break;\n case XmlTokenStream.XML_ATTRIBUTE_NAME:\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _nextToken = JsonToken.FIELD_NAME;\n _currText = _xmlTokens.getText();\n _parsingContext = _parsingContext.createChildObjectContext(-1, -1);\n _currToken = JsonToken.START_OBJECT;\n } else {\n _parsingContext.setCurrentName(_xmlTokens.getLocalName());\n _currToken = JsonToken.FIELD_NAME;\n }\n break;\n case XmlTokenStream.XML_ATTRIBUTE_VALUE:\n _currToken = JsonToken.VALUE_STRING;\n return (_currText = _xmlTokens.getText());\n case XmlTokenStream.XML_TEXT:\n _currText = _xmlTokens.getText();\n if (_mayBeLeaf) {\n _mayBeLeaf = false;\n _xmlTokens.skipEndElement();\n _currToken = JsonToken.VALUE_STRING;\n return _currText;\n }\n _parsingContext.setCurrentName(_cfgNameForTextElement);\n _nextToken = JsonToken.VALUE_STRING;\n _currToken = JsonToken.FIELD_NAME;\n break;\n case XmlTokenStream.XML_END:\n _currToken = null;\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonXml-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonXml-3"}} {"sample_uid": "defects4j_function_repair::Chart-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String generateToolTipFragment(String toolTipText) {\n return \" title=\\\"\" + toolTipText\n + \"\\\" alt=\\\"\\\"\";\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String generateToolTipFragment(String toolTipText) {\n return \" title=\\\"\" + toolTipText\n + \"\\\" alt=\\\"\\\"\";\n }\n"}, "reference": " public String generateToolTipFragment(String toolTipText) {\n return \" title=\\\"\" + ImageMapUtilities.htmlEscape(toolTipText) \n + \"\\\" alt=\\\"\\\"\";\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-10"}} {"sample_uid": "defects4j_function_repair::Closure-102", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void process(Node externs, Node root) {\n NodeTraversal.traverse(compiler, root, this);\n if (MAKE_LOCAL_NAMES_UNIQUE) {\n MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();\n NodeTraversal t = new NodeTraversal(compiler, renamer);\n t.traverseRoots(externs, root);\n }\n removeDuplicateDeclarations(root);\n new PropogateConstantAnnotations(compiler, assertOnChange)\n .process(externs, root);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void process(Node externs, Node root) {\n NodeTraversal.traverse(compiler, root, this);\n if (MAKE_LOCAL_NAMES_UNIQUE) {\n MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();\n NodeTraversal t = new NodeTraversal(compiler, renamer);\n t.traverseRoots(externs, root);\n }\n removeDuplicateDeclarations(root);\n new PropogateConstantAnnotations(compiler, assertOnChange)\n .process(externs, root);\n }\n"}, "reference": " public void process(Node externs, Node root) {\n NodeTraversal.traverse(compiler, root, this);\n removeDuplicateDeclarations(root);\n if (MAKE_LOCAL_NAMES_UNIQUE) {\n MakeDeclaredNamesUnique renamer = new MakeDeclaredNamesUnique();\n NodeTraversal t = new NodeTraversal(compiler, renamer);\n t.traverseRoots(externs, root);\n }\n new PropogateConstantAnnotations(compiler, assertOnChange)\n .process(externs, root);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-102"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-102"}} {"sample_uid": "defects4j_function_repair::Closure-71", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void checkPropertyVisibility(NodeTraversal t,\n Node getprop, Node parent) {\n ObjectType objectType =\n ObjectType.cast(dereference(getprop.getFirstChild().getJSType()));\n String propertyName = getprop.getLastChild().getString();\n if (objectType != null) {\n boolean isOverride = t.inGlobalScope() &&\n parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == getprop;\n if (isOverride) {\n objectType = objectType.getImplicitPrototype();\n }\n JSDocInfo docInfo = null;\n for (; objectType != null;\n objectType = objectType.getImplicitPrototype()) {\n docInfo = objectType.getOwnPropertyJSDocInfo(propertyName);\n if (docInfo != null &&\n docInfo.getVisibility() != Visibility.INHERITED) {\n break;\n }\n }\n if (objectType == null) {\n return;\n }\n boolean sameInput =\n t.getInput().getName().equals(docInfo.getSourceName());\n Visibility visibility = docInfo.getVisibility();\n JSType ownerType = normalizeClassType(objectType);\n if (isOverride) {\n JSDocInfo overridingInfo = parent.getJSDocInfo();\n Visibility overridingVisibility = overridingInfo == null ?\n Visibility.INHERITED : overridingInfo.getVisibility();\n if (visibility == Visibility.PRIVATE && !sameInput) {\n compiler.report(\n t.makeError(getprop, PRIVATE_OVERRIDE,\n objectType.toString()));\n } else if (overridingVisibility != Visibility.INHERITED &&\n overridingVisibility != visibility) {\n compiler.report(\n t.makeError(getprop, VISIBILITY_MISMATCH,\n visibility.name(), objectType.toString(),\n overridingVisibility.name()));\n }\n } else {\n if (sameInput) {\n return;\n } else if (visibility == Visibility.PRIVATE &&\n (currentClass == null || ownerType.differsFrom(currentClass))) {\n if (docInfo.isConstructor() &&\n isValidPrivateConstructorAccess(parent)) {\n return;\n }\n compiler.report(\n t.makeError(getprop,\n BAD_PRIVATE_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n } else if (visibility == Visibility.PROTECTED) {\n if (currentClass == null || !currentClass.isSubtype(ownerType)) {\n compiler.report(\n t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n }\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void checkPropertyVisibility(NodeTraversal t,\n Node getprop, Node parent) {\n ObjectType objectType =\n ObjectType.cast(dereference(getprop.getFirstChild().getJSType()));\n String propertyName = getprop.getLastChild().getString();\n if (objectType != null) {\n boolean isOverride = t.inGlobalScope() &&\n parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == getprop;\n if (isOverride) {\n objectType = objectType.getImplicitPrototype();\n }\n JSDocInfo docInfo = null;\n for (; objectType != null;\n objectType = objectType.getImplicitPrototype()) {\n docInfo = objectType.getOwnPropertyJSDocInfo(propertyName);\n if (docInfo != null &&\n docInfo.getVisibility() != Visibility.INHERITED) {\n break;\n }\n }\n if (objectType == null) {\n return;\n }\n boolean sameInput =\n t.getInput().getName().equals(docInfo.getSourceName());\n Visibility visibility = docInfo.getVisibility();\n JSType ownerType = normalizeClassType(objectType);\n if (isOverride) {\n JSDocInfo overridingInfo = parent.getJSDocInfo();\n Visibility overridingVisibility = overridingInfo == null ?\n Visibility.INHERITED : overridingInfo.getVisibility();\n if (visibility == Visibility.PRIVATE && !sameInput) {\n compiler.report(\n t.makeError(getprop, PRIVATE_OVERRIDE,\n objectType.toString()));\n } else if (overridingVisibility != Visibility.INHERITED &&\n overridingVisibility != visibility) {\n compiler.report(\n t.makeError(getprop, VISIBILITY_MISMATCH,\n visibility.name(), objectType.toString(),\n overridingVisibility.name()));\n }\n } else {\n if (sameInput) {\n return;\n } else if (visibility == Visibility.PRIVATE &&\n (currentClass == null || ownerType.differsFrom(currentClass))) {\n if (docInfo.isConstructor() &&\n isValidPrivateConstructorAccess(parent)) {\n return;\n }\n compiler.report(\n t.makeError(getprop,\n BAD_PRIVATE_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n } else if (visibility == Visibility.PROTECTED) {\n if (currentClass == null || !currentClass.isSubtype(ownerType)) {\n compiler.report(\n t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n }\n }\n }\n }\n }\n"}, "reference": " private void checkPropertyVisibility(NodeTraversal t,\n Node getprop, Node parent) {\n ObjectType objectType =\n ObjectType.cast(dereference(getprop.getFirstChild().getJSType()));\n String propertyName = getprop.getLastChild().getString();\n if (objectType != null) {\n boolean isOverride = parent.getJSDocInfo() != null &&\n parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == getprop;\n if (isOverride) {\n objectType = objectType.getImplicitPrototype();\n }\n JSDocInfo docInfo = null;\n for (; objectType != null;\n objectType = objectType.getImplicitPrototype()) {\n docInfo = objectType.getOwnPropertyJSDocInfo(propertyName);\n if (docInfo != null &&\n docInfo.getVisibility() != Visibility.INHERITED) {\n break;\n }\n }\n if (objectType == null) {\n return;\n }\n boolean sameInput =\n t.getInput().getName().equals(docInfo.getSourceName());\n Visibility visibility = docInfo.getVisibility();\n JSType ownerType = normalizeClassType(objectType);\n if (isOverride) {\n JSDocInfo overridingInfo = parent.getJSDocInfo();\n Visibility overridingVisibility = overridingInfo == null ?\n Visibility.INHERITED : overridingInfo.getVisibility();\n if (visibility == Visibility.PRIVATE && !sameInput) {\n compiler.report(\n t.makeError(getprop, PRIVATE_OVERRIDE,\n objectType.toString()));\n } else if (overridingVisibility != Visibility.INHERITED &&\n overridingVisibility != visibility) {\n compiler.report(\n t.makeError(getprop, VISIBILITY_MISMATCH,\n visibility.name(), objectType.toString(),\n overridingVisibility.name()));\n }\n } else {\n if (sameInput) {\n return;\n } else if (visibility == Visibility.PRIVATE &&\n (currentClass == null || ownerType.differsFrom(currentClass))) {\n if (docInfo.isConstructor() &&\n isValidPrivateConstructorAccess(parent)) {\n return;\n }\n compiler.report(\n t.makeError(getprop,\n BAD_PRIVATE_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n } else if (visibility == Visibility.PROTECTED) {\n if (currentClass == null || !currentClass.isSubtype(ownerType)) {\n compiler.report(\n t.makeError(getprop, BAD_PROTECTED_PROPERTY_ACCESS,\n propertyName,\n validator.getReadableJSTypeName(\n getprop.getFirstChild(), true)));\n }\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-71"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-71"}} {"sample_uid": "defects4j_function_repair::Closure-42", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Node processForInLoop(ForInLoop loopNode) {\n return newNode(\n Token.FOR,\n transform(loopNode.getIterator()),\n transform(loopNode.getIteratedObject()),\n transformBlock(loopNode.getBody()));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Node processForInLoop(ForInLoop loopNode) {\n return newNode(\n Token.FOR,\n transform(loopNode.getIterator()),\n transform(loopNode.getIteratedObject()),\n transformBlock(loopNode.getBody()));\n }\n"}, "reference": " Node processForInLoop(ForInLoop loopNode) {\n if (loopNode.isForEach()) {\n errorReporter.error(\n \"unsupported language extension: for each\",\n sourceName,\n loopNode.getLineno(), \"\", 0);\n return newNode(Token.EXPR_RESULT, Node.newNumber(0));\n }\n return newNode(\n Token.FOR,\n transform(loopNode.getIterator()),\n transform(loopNode.getIteratedObject()),\n transformBlock(loopNode.getBody()));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-42"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-42"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-45", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property != null) {\n JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());\n if (format != null) {\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.getShape() == JsonFormat.Shape.STRING) {\n TimeZone tz = format.getTimeZone();\n final String pattern = format.hasPattern()\n ? format.getPattern()\n : StdDateFormat.DATE_FORMAT_STR_ISO8601;\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(pattern, loc);\n if (tz == null) {\n tz = serializers.getTimeZone();\n }\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n }\n }\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property != null) {\n JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());\n if (format != null) {\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.getShape() == JsonFormat.Shape.STRING) {\n TimeZone tz = format.getTimeZone();\n final String pattern = format.hasPattern()\n ? format.getPattern()\n : StdDateFormat.DATE_FORMAT_STR_ISO8601;\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(pattern, loc);\n if (tz == null) {\n tz = serializers.getTimeZone();\n }\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n }\n }\n return this;\n }\n"}, "reference": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property != null) {\n JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());\n if (format != null) {\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()\n || format.hasLocale() || format.hasTimeZone()) {\n TimeZone tz = format.getTimeZone();\n final String pattern = format.hasPattern()\n ? format.getPattern()\n : StdDateFormat.DATE_FORMAT_STR_ISO8601;\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(pattern, loc);\n if (tz == null) {\n tz = serializers.getTimeZone();\n }\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n }\n }\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-45"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-45"}} {"sample_uid": "defects4j_function_repair::Compress-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n InputStream decode(final InputStream in, final Coder coder,\n byte[] password) throws IOException {\n byte propsByte = coder.properties[0];\n long dictSize = coder.properties[1];\n for (int i = 1; i < 4; i++) {\n dictSize |= (coder.properties[i + 1] << (8 * i));\n }\n if (dictSize > LZMAInputStream.DICT_SIZE_MAX) {\n throw new IOException(\"Dictionary larger than 4GiB maximum size\");\n }\n return new LZMAInputStream(in, -1, propsByte, (int) dictSize);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " InputStream decode(final InputStream in, final Coder coder,\n byte[] password) throws IOException {\n byte propsByte = coder.properties[0];\n long dictSize = coder.properties[1];\n for (int i = 1; i < 4; i++) {\n dictSize |= (coder.properties[i + 1] << (8 * i));\n }\n if (dictSize > LZMAInputStream.DICT_SIZE_MAX) {\n throw new IOException(\"Dictionary larger than 4GiB maximum size\");\n }\n return new LZMAInputStream(in, -1, propsByte, (int) dictSize);\n }\n"}, "reference": " InputStream decode(final InputStream in, final Coder coder,\n byte[] password) throws IOException {\n byte propsByte = coder.properties[0];\n long dictSize = coder.properties[1];\n for (int i = 1; i < 4; i++) {\n dictSize |= (coder.properties[i + 1] & 0xffl) << (8 * i);\n }\n if (dictSize > LZMAInputStream.DICT_SIZE_MAX) {\n throw new IOException(\"Dictionary larger than 4GiB maximum size\");\n }\n return new LZMAInputStream(in, -1, propsByte, (int) dictSize);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-23"}} {"sample_uid": "defects4j_function_repair::Cli-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void setSelected(Option option) throws AlreadySelectedException\n {\n if (option == null)\n {\n selected = null;\n return;\n }\n if (selected == null || selected.equals(option.getOpt()))\n {\n selected = option.getOpt();\n }\n else\n {\n throw new AlreadySelectedException(this, option);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void setSelected(Option option) throws AlreadySelectedException\n {\n if (option == null)\n {\n selected = null;\n return;\n }\n if (selected == null || selected.equals(option.getOpt()))\n {\n selected = option.getOpt();\n }\n else\n {\n throw new AlreadySelectedException(this, option);\n }\n }\n"}, "reference": " public void setSelected(Option option) throws AlreadySelectedException\n {\n if (option == null)\n {\n selected = null;\n return;\n }\n if (selected == null || selected.equals(option.getKey()))\n {\n selected = option.getKey();\n }\n else\n {\n throw new AlreadySelectedException(this, option);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-27"}} {"sample_uid": "defects4j_function_repair::Closure-29", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isInlinableObject(List refs) {\n boolean ret = false;\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isInlinableObject(List refs) {\n boolean ret = false;\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n"}, "reference": " private boolean isInlinableObject(List refs) {\n boolean ret = false;\n Set validProperties = Sets.newHashSet();\n for (Reference ref : refs) {\n Node name = ref.getNode();\n Node parent = ref.getParent();\n Node gramps = ref.getGrandparent();\n if (parent.isGetProp()) {\n Preconditions.checkState(parent.getFirstChild() == name);\n if (gramps.isCall()\n && gramps.getFirstChild() == parent) {\n return false;\n }\n String propName = parent.getLastChild().getString();\n if (!validProperties.contains(propName)) {\n if (NodeUtil.isVarOrSimpleAssignLhs(parent, gramps)) {\n validProperties.add(propName);\n } else {\n return false;\n }\n }\n continue;\n }\n if (!isVarOrAssignExprLhs(name)) {\n return false;\n }\n Node val = ref.getAssignedValue();\n if (val == null) {\n continue;\n }\n if (!val.isObjectLit()) {\n return false;\n }\n for (Node child = val.getFirstChild(); child != null;\n child = child.getNext()) {\n if (child.isGetterDef() ||\n child.isSetterDef()) {\n return false;\n }\n validProperties.add(child.getString());\n Node childVal = child.getFirstChild();\n for (Reference t : refs) {\n Node refNode = t.getParent();\n while (!NodeUtil.isStatementBlock(refNode)) {\n if (refNode == childVal) {\n return false;\n }\n refNode = refNode.getParent();\n }\n }\n }\n ret = true;\n }\n return ret;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-29"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-29"}} {"sample_uid": "defects4j_function_repair::Math-70", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double solve(final UnivariateRealFunction f, double min, double max, double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n return solve(min, max);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double solve(final UnivariateRealFunction f, double min, double max, double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n return solve(min, max);\n }\n"}, "reference": " public double solve(final UnivariateRealFunction f, double min, double max, double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n return solve(f, min, max);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-70"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-70"}} {"sample_uid": "defects4j_function_repair::Compress-16", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n if (signatureLength >= 512) {\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n tais.getNextEntry();\n return new TarArchiveInputStream(in);\n } catch (Exception e) { \n }\n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n if (signatureLength >= 512) {\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n tais.getNextEntry();\n return new TarArchiveInputStream(in);\n } catch (Exception e) { \n }\n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n"}, "reference": " public ArchiveInputStream createArchiveInputStream(final InputStream in)\n throws ArchiveException {\n if (in == null) {\n throw new IllegalArgumentException(\"Stream must not be null.\");\n }\n if (!in.markSupported()) {\n throw new IllegalArgumentException(\"Mark is not supported.\");\n }\n final byte[] signature = new byte[12];\n in.mark(signature.length);\n try {\n int signatureLength = in.read(signature);\n in.reset();\n if (ZipArchiveInputStream.matches(signature, signatureLength)) {\n return new ZipArchiveInputStream(in);\n } else if (JarArchiveInputStream.matches(signature, signatureLength)) {\n return new JarArchiveInputStream(in);\n } else if (ArArchiveInputStream.matches(signature, signatureLength)) {\n return new ArArchiveInputStream(in);\n } else if (CpioArchiveInputStream.matches(signature, signatureLength)) {\n return new CpioArchiveInputStream(in);\n }\n final byte[] dumpsig = new byte[32];\n in.mark(dumpsig.length);\n signatureLength = in.read(dumpsig);\n in.reset();\n if (DumpArchiveInputStream.matches(dumpsig, signatureLength)) {\n return new DumpArchiveInputStream(in);\n }\n final byte[] tarheader = new byte[512];\n in.mark(tarheader.length);\n signatureLength = in.read(tarheader);\n in.reset();\n if (TarArchiveInputStream.matches(tarheader, signatureLength)) {\n return new TarArchiveInputStream(in);\n }\n if (signatureLength >= 512) {\n try {\n TarArchiveInputStream tais = new TarArchiveInputStream(new ByteArrayInputStream(tarheader));\n if (tais.getNextTarEntry().isCheckSumOK()) {\n return new TarArchiveInputStream(in);\n }\n } catch (Exception e) { \n }\n }\n } catch (IOException e) {\n throw new ArchiveException(\"Could not use reset and mark operations.\", e);\n }\n throw new ArchiveException(\"No Archiver found for the stream signature\");\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-16"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-16"}} {"sample_uid": "defects4j_function_repair::Math-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return current;\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return current;\n }\n ++iter;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return current;\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return current;\n }\n ++iter;\n }\n }\n"}, "reference": " protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return best(current, previous, isMinim);\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return best(current, previous, isMinim);\n }\n ++iter;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-24"}} {"sample_uid": "defects4j_function_repair::Lang-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean containsIgnoreCase(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return contains(str.toUpperCase(), searchStr.toUpperCase());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean containsIgnoreCase(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n return contains(str.toUpperCase(), searchStr.toUpperCase());\n }\n"}, "reference": " public static boolean containsIgnoreCase(String str, String searchStr) {\n if (str == null || searchStr == null) {\n return false;\n }\n int len = searchStr.length();\n int max = str.length() - len;\n for (int i = 0; i <= max; i++) {\n if (str.regionMatches(true, i, searchStr, 0, len)) {\n return true;\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-40"}} {"sample_uid": "defects4j_function_repair::Jsoup-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.DdDt)) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), Constants.DdDt)) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n return tb.process(startTag.name(\"img\")); \n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.DdDt)) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), Constants.DdDt)) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n return tb.process(startTag.name(\"img\")); \n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n"}, "reference": " boolean process(Token t, HtmlTreeBuilder tb) {\n switch (t.type) {\n case Character: {\n Token.Character c = t.asCharacter();\n if (c.getData().equals(nullString)) {\n tb.error(this);\n return false;\n } else if (isWhitespace(c)) {\n tb.reconstructFormattingElements();\n tb.insert(c);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(c);\n tb.framesetOk(false);\n }\n break;\n }\n case Comment: {\n tb.insert(t.asComment());\n break;\n }\n case Doctype: {\n tb.error(this);\n return false;\n }\n case StartTag:\n Token.StartTag startTag = t.asStartTag();\n String name = startTag.name();\n if (name.equals(\"html\")) {\n tb.error(this);\n Element html = tb.getStack().getFirst();\n for (Attribute attribute : startTag.getAttributes()) {\n if (!html.hasAttr(attribute.getKey()))\n html.attributes().put(attribute);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartToHead)) {\n return tb.process(t, InHead);\n } else if (name.equals(\"body\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else {\n tb.framesetOk(false);\n Element body = stack.get(1);\n for (Attribute attribute : startTag.getAttributes()) {\n if (!body.hasAttr(attribute.getKey()))\n body.attributes().put(attribute);\n }\n }\n } else if (name.equals(\"frameset\")) {\n tb.error(this);\n LinkedList stack = tb.getStack();\n if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals(\"body\"))) {\n return false; \n } else if (!tb.framesetOk()) {\n return false; \n } else {\n Element second = stack.get(1);\n if (second.parent() != null)\n second.remove();\n while (stack.size() > 1)\n stack.removeLast();\n tb.insert(startTag);\n tb.transition(InFrameset);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartPClosers)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) {\n tb.error(this);\n tb.pop();\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartPreListing)) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"form\")) {\n if (tb.getFormElement() != null) {\n tb.error(this);\n return false;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertForm(startTag, true);\n } else if (name.equals(\"li\")) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (el.nodeName().equals(\"li\")) {\n tb.process(new Token.EndTag(\"li\"));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.DdDt)) {\n tb.framesetOk(false);\n LinkedList stack = tb.getStack();\n for (int i = stack.size() - 1; i > 0; i--) {\n Element el = stack.get(i);\n if (StringUtil.in(el.nodeName(), Constants.DdDt)) {\n tb.process(new Token.EndTag(el.nodeName()));\n break;\n }\n if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))\n break;\n }\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n } else if (name.equals(\"plaintext\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.PLAINTEXT); \n } else if (name.equals(\"button\")) {\n if (tb.inButtonScope(\"button\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"button\"));\n tb.process(startTag);\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n }\n } else if (name.equals(\"a\")) {\n if (tb.getActiveFormattingElement(\"a\") != null) {\n tb.error(this);\n tb.process(new Token.EndTag(\"a\"));\n Element remainingA = tb.getFromStack(\"a\");\n if (remainingA != null) {\n tb.removeFromActiveFormattingElements(remainingA);\n tb.removeFromStack(remainingA);\n }\n }\n tb.reconstructFormattingElements();\n Element a = tb.insert(startTag);\n tb.pushActiveFormattingElements(a);\n } else if (StringUtil.in(name, Constants.Formatters)) {\n tb.reconstructFormattingElements();\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (name.equals(\"nobr\")) {\n tb.reconstructFormattingElements();\n if (tb.inScope(\"nobr\")) {\n tb.error(this);\n tb.process(new Token.EndTag(\"nobr\"));\n tb.reconstructFormattingElements();\n }\n Element el = tb.insert(startTag);\n tb.pushActiveFormattingElements(el);\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.insertMarkerToFormattingElements();\n tb.framesetOk(false);\n } else if (name.equals(\"table\")) {\n if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insert(startTag);\n tb.framesetOk(false);\n tb.transition(InTable);\n } else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) {\n tb.reconstructFormattingElements();\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"input\")) {\n tb.reconstructFormattingElements();\n Element el = tb.insertEmpty(startTag);\n if (!el.attr(\"type\").equalsIgnoreCase(\"hidden\"))\n tb.framesetOk(false);\n } else if (StringUtil.in(name, Constants.InBodyStartMedia)) {\n tb.insertEmpty(startTag);\n } else if (name.equals(\"hr\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.insertEmpty(startTag);\n tb.framesetOk(false);\n } else if (name.equals(\"image\")) {\n if (tb.getFromStack(\"svg\") == null)\n return tb.process(startTag.name(\"img\")); \n else\n tb.insert(startTag);\n } else if (name.equals(\"isindex\")) {\n tb.error(this);\n if (tb.getFormElement() != null)\n return false;\n tb.tokeniser.acknowledgeSelfClosingFlag();\n tb.process(new Token.StartTag(\"form\"));\n if (startTag.attributes.hasKey(\"action\")) {\n Element form = tb.getFormElement();\n form.attr(\"action\", startTag.attributes.get(\"action\"));\n }\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.StartTag(\"label\"));\n String prompt = startTag.attributes.hasKey(\"prompt\") ?\n startTag.attributes.get(\"prompt\") :\n \"This is a searchable index. Enter search keywords: \";\n tb.process(new Token.Character(prompt));\n Attributes inputAttribs = new Attributes();\n for (Attribute attr : startTag.attributes) {\n if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs))\n inputAttribs.put(attr);\n }\n inputAttribs.put(\"name\", \"isindex\");\n tb.process(new Token.StartTag(\"input\", inputAttribs));\n tb.process(new Token.EndTag(\"label\"));\n tb.process(new Token.StartTag(\"hr\"));\n tb.process(new Token.EndTag(\"form\"));\n } else if (name.equals(\"textarea\")) {\n tb.insert(startTag);\n tb.tokeniser.transition(TokeniserState.Rcdata);\n tb.markInsertionMode();\n tb.framesetOk(false);\n tb.transition(Text);\n } else if (name.equals(\"xmp\")) {\n if (tb.inButtonScope(\"p\")) {\n tb.process(new Token.EndTag(\"p\"));\n }\n tb.reconstructFormattingElements();\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"iframe\")) {\n tb.framesetOk(false);\n handleRawtext(startTag, tb);\n } else if (name.equals(\"noembed\")) {\n handleRawtext(startTag, tb);\n } else if (name.equals(\"select\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.framesetOk(false);\n HtmlTreeBuilderState state = tb.state();\n if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))\n tb.transition(InSelectInTable);\n else\n tb.transition(InSelect);\n } else if (StringUtil.in(name, Constants.InBodyStartOptions)) {\n if (tb.currentElement().nodeName().equals(\"option\"))\n tb.process(new Token.EndTag(\"option\"));\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n } else if (StringUtil.in(name, Constants.InBodyStartRuby)) {\n if (tb.inScope(\"ruby\")) {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(\"ruby\")) {\n tb.error(this);\n tb.popStackToBefore(\"ruby\"); \n }\n tb.insert(startTag);\n }\n } else if (name.equals(\"math\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (name.equals(\"svg\")) {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n tb.tokeniser.acknowledgeSelfClosingFlag();\n } else if (StringUtil.in(name, Constants.InBodyStartDrop)) {\n tb.error(this);\n return false;\n } else {\n tb.reconstructFormattingElements();\n tb.insert(startTag);\n }\n break;\n case EndTag:\n Token.EndTag endTag = t.asEndTag();\n name = endTag.name();\n if (name.equals(\"body\")) {\n if (!tb.inScope(\"body\")) {\n tb.error(this);\n return false;\n } else {\n tb.transition(AfterBody);\n }\n } else if (name.equals(\"html\")) {\n boolean notIgnored = tb.process(new Token.EndTag(\"body\"));\n if (notIgnored)\n return tb.process(endTag);\n } else if (StringUtil.in(name, Constants.InBodyEndClosers)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"form\")) {\n Element currentForm = tb.getFormElement();\n tb.setFormElement(null);\n if (currentForm == null || !tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.removeFromStack(currentForm);\n }\n } else if (name.equals(\"p\")) {\n if (!tb.inButtonScope(name)) {\n tb.error(this);\n tb.process(new Token.StartTag(name)); \n return tb.process(endTag);\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (name.equals(\"li\")) {\n if (!tb.inListItemScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.DdDt)) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n }\n } else if (StringUtil.in(name, Constants.Headings)) {\n if (!tb.inScope(Constants.Headings)) {\n tb.error(this);\n return false;\n } else {\n tb.generateImpliedEndTags(name);\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(Constants.Headings);\n }\n } else if (name.equals(\"sarcasm\")) {\n return anyOtherEndTag(t, tb);\n } else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) {\n OUTER:\n for (int i = 0; i < 8; i++) {\n Element formatEl = tb.getActiveFormattingElement(name);\n if (formatEl == null)\n return anyOtherEndTag(t, tb);\n else if (!tb.onStack(formatEl)) {\n tb.error(this);\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n } else if (!tb.inScope(formatEl.nodeName())) {\n tb.error(this);\n return false;\n } else if (tb.currentElement() != formatEl)\n tb.error(this);\n Element furthestBlock = null;\n Element commonAncestor = null;\n boolean seenFormattingElement = false;\n LinkedList stack = tb.getStack();\n final int stackSize = stack.size();\n for (int si = 0; si < stackSize && si < 64; si++) {\n Element el = stack.get(si);\n if (el == formatEl) {\n commonAncestor = stack.get(si - 1);\n seenFormattingElement = true;\n } else if (seenFormattingElement && tb.isSpecial(el)) {\n furthestBlock = el;\n break;\n }\n }\n if (furthestBlock == null) {\n tb.popStackToClose(formatEl.nodeName());\n tb.removeFromActiveFormattingElements(formatEl);\n return true;\n }\n Element node = furthestBlock;\n Element lastNode = furthestBlock;\n INNER:\n for (int j = 0; j < 3; j++) {\n if (tb.onStack(node))\n node = tb.aboveOnStack(node);\n if (!tb.isInActiveFormattingElements(node)) { \n tb.removeFromStack(node);\n continue INNER;\n } else if (node == formatEl)\n break INNER;\n Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());\n tb.replaceActiveFormattingElement(node, replacement);\n tb.replaceOnStack(node, replacement);\n node = replacement;\n if (lastNode == furthestBlock) {\n }\n if (lastNode.parent() != null)\n lastNode.remove();\n node.appendChild(lastNode);\n lastNode = node;\n }\n if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {\n if (lastNode.parent() != null)\n lastNode.remove();\n tb.insertInFosterParent(lastNode);\n } else {\n if (lastNode.parent() != null)\n lastNode.remove();\n commonAncestor.appendChild(lastNode);\n }\n Element adopter = new Element(formatEl.tag(), tb.getBaseUri());\n adopter.attributes().addAll(formatEl.attributes());\n Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);\n for (Node childNode : childNodes) {\n adopter.appendChild(childNode); \n }\n furthestBlock.appendChild(adopter);\n tb.removeFromActiveFormattingElements(formatEl);\n tb.removeFromStack(formatEl);\n tb.insertOnStackAfter(furthestBlock, adopter);\n }\n } else if (StringUtil.in(name, Constants.InBodyStartApplets)) {\n if (!tb.inScope(\"name\")) {\n if (!tb.inScope(name)) {\n tb.error(this);\n return false;\n }\n tb.generateImpliedEndTags();\n if (!tb.currentElement().nodeName().equals(name))\n tb.error(this);\n tb.popStackToClose(name);\n tb.clearFormattingElementsToLastMarker();\n }\n } else if (name.equals(\"br\")) {\n tb.error(this);\n tb.process(new Token.StartTag(\"br\"));\n return false;\n } else {\n return anyOtherEndTag(t, tb);\n }\n break;\n case EOF:\n break;\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-38"}} {"sample_uid": "defects4j_function_repair::Math-20", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double[] repairAndDecode(final double[] x) {\n return\n decode(x);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double[] repairAndDecode(final double[] x) {\n return\n decode(x);\n }\n"}, "reference": " public double[] repairAndDecode(final double[] x) {\n return boundaries != null && isRepairMode ?\n decode(repair(x)) :\n decode(x);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-20"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-20"}} {"sample_uid": "defects4j_function_repair::Mockito-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void readTypeVariables() {\n for (Type type : typeVariable.getBounds()) {\n registerTypeVariablesOn(type);\n }\n registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void readTypeVariables() {\n for (Type type : typeVariable.getBounds()) {\n registerTypeVariablesOn(type);\n }\n registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));\n }\n"}, "reference": " private void readTypeVariables() {\n for (Type type : typeVariable.getBounds()) {\n registerTypeVariablesOn(type);\n }\n registerTypeParametersOn(new TypeVariable[] { typeVariable });\n registerTypeVariablesOn(getActualTypeArgumentFor(typeVariable));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-7"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)\n throws Exception\n {\n Object value = get(bean);\n if (value == null) { \n if (_nullSerializer != null) {\n _nullSerializer.serialize(null, jgen, prov);\n } else { \n jgen.writeNull();\n }\n }\n JsonSerializer ser = _serializer;\n if (ser == null) {\n Class cls = value.getClass();\n PropertySerializerMap map = _dynamicSerializers;\n ser = map.serializerFor(cls);\n if (ser == null) {\n ser = _findAndAddDynamic(map, cls, prov);\n }\n }\n if (_suppressableValue != null) {\n if (MARKER_FOR_EMPTY == _suppressableValue) {\n if (ser.isEmpty(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n } else if (_suppressableValue.equals(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n }\n if (value == bean) {\n _handleSelfReference(bean, ser);\n }\n if (_typeSerializer == null) {\n ser.serialize(value, jgen, prov);\n } else {\n ser.serializeWithType(value, jgen, prov, _typeSerializer);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)\n throws Exception\n {\n Object value = get(bean);\n if (value == null) { \n if (_nullSerializer != null) {\n _nullSerializer.serialize(null, jgen, prov);\n } else { \n jgen.writeNull();\n }\n }\n JsonSerializer ser = _serializer;\n if (ser == null) {\n Class cls = value.getClass();\n PropertySerializerMap map = _dynamicSerializers;\n ser = map.serializerFor(cls);\n if (ser == null) {\n ser = _findAndAddDynamic(map, cls, prov);\n }\n }\n if (_suppressableValue != null) {\n if (MARKER_FOR_EMPTY == _suppressableValue) {\n if (ser.isEmpty(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n } else if (_suppressableValue.equals(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n }\n if (value == bean) {\n _handleSelfReference(bean, ser);\n }\n if (_typeSerializer == null) {\n ser.serialize(value, jgen, prov);\n } else {\n ser.serializeWithType(value, jgen, prov, _typeSerializer);\n }\n }\n"}, "reference": " public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)\n throws Exception\n {\n Object value = get(bean);\n if (value == null) { \n if (_nullSerializer != null) {\n _nullSerializer.serialize(null, jgen, prov);\n } else { \n jgen.writeNull();\n }\n return;\n }\n JsonSerializer ser = _serializer;\n if (ser == null) {\n Class cls = value.getClass();\n PropertySerializerMap map = _dynamicSerializers;\n ser = map.serializerFor(cls);\n if (ser == null) {\n ser = _findAndAddDynamic(map, cls, prov);\n }\n }\n if (_suppressableValue != null) {\n if (MARKER_FOR_EMPTY == _suppressableValue) {\n if (ser.isEmpty(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n } else if (_suppressableValue.equals(value)) { \n serializeAsPlaceholder(bean, jgen, prov);\n return;\n }\n }\n if (value == bean) {\n _handleSelfReference(bean, ser);\n }\n if (_typeSerializer == null) {\n ser.serialize(value, jgen, prov);\n } else {\n ser.serializeWithType(value, jgen, prov, _typeSerializer);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-1"}} {"sample_uid": "defects4j_function_repair::Mockito-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Class getGenericType(Field field) { \n Type generic = field.getGenericType();\n if (generic != null && generic instanceof ParameterizedType) {\n Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];\n return (Class) actual;\n }\n return Object.class;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Class getGenericType(Field field) { \n Type generic = field.getGenericType();\n if (generic != null && generic instanceof ParameterizedType) {\n Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];\n return (Class) actual;\n }\n return Object.class;\n }\n"}, "reference": " public Class getGenericType(Field field) { \n Type generic = field.getGenericType();\n if (generic != null && generic instanceof ParameterizedType) {\n Type actual = ((ParameterizedType) generic).getActualTypeArguments()[0];\n if (actual instanceof Class) {\n return (Class) actual;\n } else if (actual instanceof ParameterizedType) {\n return (Class) ((ParameterizedType) actual).getRawType();\n }\n }\n return Object.class;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-12"}} {"sample_uid": "defects4j_function_repair::Codec-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private int handleG(String value, \n DoubleMetaphoneResult result, \n int index, \n boolean slavoGermanic) {\n if (charAt(value, index + 1) == 'H') {\n index = handleGH(value, result, index);\n } else if (charAt(value, index + 1) == 'N') {\n if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) {\n result.append(\"KN\", \"N\");\n } else if (!contains(value, index + 2, 2, \"EY\") && \n charAt(value, index + 1) != 'Y' && !slavoGermanic) {\n result.append(\"N\", \"KN\");\n } else {\n result.append(\"KN\");\n }\n index = index + 2;\n } else if (contains(value, index + 1, 2, \"LI\") && !slavoGermanic) {\n result.append(\"KL\", \"L\");\n index += 2;\n } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) {\n result.append('K', 'J');\n index += 2;\n } else if ((contains(value, index + 1, 2, \"ER\") || \n charAt(value, index + 1) == 'Y') &&\n !contains(value, 0, 6, \"DANGER\", \"RANGER\", \"MANGER\") &&\n !contains(value, index - 1, 1, \"E\", \"I\") && \n !contains(value, index - 1, 3, \"RGY\", \"OGY\")) {\n result.append('K', 'J');\n index += 2;\n } else if (contains(value, index + 1, 1, \"E\", \"I\", \"Y\") || \n contains(value, index - 1, 4, \"AGGI\", \"OGGI\")) {\n if ((contains(value, 0 ,4, \"VAN \", \"VON \") || contains(value, 0, 3, \"SCH\")) || contains(value, index + 1, 2, \"ET\")) {\n result.append('K');\n } else if (contains(value, index + 1, 4, \"IER\")) {\n result.append('J');\n } else {\n result.append('J', 'K');\n }\n index += 2;\n } else if (charAt(value, index + 1) == 'G') {\n index += 2;\n result.append('K');\n } else {\n index++;\n result.append('K');\n }\n return index;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private int handleG(String value, \n DoubleMetaphoneResult result, \n int index, \n boolean slavoGermanic) {\n if (charAt(value, index + 1) == 'H') {\n index = handleGH(value, result, index);\n } else if (charAt(value, index + 1) == 'N') {\n if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) {\n result.append(\"KN\", \"N\");\n } else if (!contains(value, index + 2, 2, \"EY\") && \n charAt(value, index + 1) != 'Y' && !slavoGermanic) {\n result.append(\"N\", \"KN\");\n } else {\n result.append(\"KN\");\n }\n index = index + 2;\n } else if (contains(value, index + 1, 2, \"LI\") && !slavoGermanic) {\n result.append(\"KL\", \"L\");\n index += 2;\n } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) {\n result.append('K', 'J');\n index += 2;\n } else if ((contains(value, index + 1, 2, \"ER\") || \n charAt(value, index + 1) == 'Y') &&\n !contains(value, 0, 6, \"DANGER\", \"RANGER\", \"MANGER\") &&\n !contains(value, index - 1, 1, \"E\", \"I\") && \n !contains(value, index - 1, 3, \"RGY\", \"OGY\")) {\n result.append('K', 'J');\n index += 2;\n } else if (contains(value, index + 1, 1, \"E\", \"I\", \"Y\") || \n contains(value, index - 1, 4, \"AGGI\", \"OGGI\")) {\n if ((contains(value, 0 ,4, \"VAN \", \"VON \") || contains(value, 0, 3, \"SCH\")) || contains(value, index + 1, 2, \"ET\")) {\n result.append('K');\n } else if (contains(value, index + 1, 4, \"IER\")) {\n result.append('J');\n } else {\n result.append('J', 'K');\n }\n index += 2;\n } else if (charAt(value, index + 1) == 'G') {\n index += 2;\n result.append('K');\n } else {\n index++;\n result.append('K');\n }\n return index;\n }\n"}, "reference": " private int handleG(String value, \n DoubleMetaphoneResult result, \n int index, \n boolean slavoGermanic) {\n if (charAt(value, index + 1) == 'H') {\n index = handleGH(value, result, index);\n } else if (charAt(value, index + 1) == 'N') {\n if (index == 1 && isVowel(charAt(value, 0)) && !slavoGermanic) {\n result.append(\"KN\", \"N\");\n } else if (!contains(value, index + 2, 2, \"EY\") && \n charAt(value, index + 1) != 'Y' && !slavoGermanic) {\n result.append(\"N\", \"KN\");\n } else {\n result.append(\"KN\");\n }\n index = index + 2;\n } else if (contains(value, index + 1, 2, \"LI\") && !slavoGermanic) {\n result.append(\"KL\", \"L\");\n index += 2;\n } else if (index == 0 && (charAt(value, index + 1) == 'Y' || contains(value, index + 1, 2, ES_EP_EB_EL_EY_IB_IL_IN_IE_EI_ER))) {\n result.append('K', 'J');\n index += 2;\n } else if ((contains(value, index + 1, 2, \"ER\") || \n charAt(value, index + 1) == 'Y') &&\n !contains(value, 0, 6, \"DANGER\", \"RANGER\", \"MANGER\") &&\n !contains(value, index - 1, 1, \"E\", \"I\") && \n !contains(value, index - 1, 3, \"RGY\", \"OGY\")) {\n result.append('K', 'J');\n index += 2;\n } else if (contains(value, index + 1, 1, \"E\", \"I\", \"Y\") || \n contains(value, index - 1, 4, \"AGGI\", \"OGGI\")) {\n if ((contains(value, 0 ,4, \"VAN \", \"VON \") || contains(value, 0, 3, \"SCH\")) || contains(value, index + 1, 2, \"ET\")) {\n result.append('K');\n } else if (contains(value, index + 1, 3, \"IER\")) {\n result.append('J');\n } else {\n result.append('J', 'K');\n }\n index += 2;\n } else if (charAt(value, index + 1) == 'G') {\n index += 2;\n result.append('K');\n } else {\n index++;\n result.append('K');\n }\n return index;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-3"}} {"sample_uid": "defects4j_function_repair::Jsoup-19", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean testValidProtocol(Element el, Attribute attr, Set protocols) {\n String value = el.absUrl(attr.getKey());\n if (!preserveRelativeLinks)\n attr.setValue(value);\n for (Protocol protocol : protocols) {\n String prot = protocol.toString() + \":\";\n if (value.toLowerCase().startsWith(prot)) {\n return true;\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean testValidProtocol(Element el, Attribute attr, Set protocols) {\n String value = el.absUrl(attr.getKey());\n if (!preserveRelativeLinks)\n attr.setValue(value);\n for (Protocol protocol : protocols) {\n String prot = protocol.toString() + \":\";\n if (value.toLowerCase().startsWith(prot)) {\n return true;\n }\n }\n return false;\n }\n"}, "reference": " private boolean testValidProtocol(Element el, Attribute attr, Set protocols) {\n String value = el.absUrl(attr.getKey());\n if (value.length() == 0)\n value = attr.getValue(); \n if (!preserveRelativeLinks)\n attr.setValue(value);\n for (Protocol protocol : protocols) {\n String prot = protocol.toString() + \":\";\n if (value.toLowerCase().startsWith(prot)) {\n return true;\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-19"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-19"}} {"sample_uid": "defects4j_function_repair::Jsoup-89", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String setValue(String val) {\n String oldVal = parent.get(this.key);\n if (parent != null) {\n int i = parent.indexOfKey(this.key);\n if (i != Attributes.NotFound)\n parent.vals[i] = val;\n }\n this.val = val;\n return Attributes.checkNotNull(oldVal);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String setValue(String val) {\n String oldVal = parent.get(this.key);\n if (parent != null) {\n int i = parent.indexOfKey(this.key);\n if (i != Attributes.NotFound)\n parent.vals[i] = val;\n }\n this.val = val;\n return Attributes.checkNotNull(oldVal);\n }\n"}, "reference": " public String setValue(String val) {\n String oldVal = this.val;\n if (parent != null) {\n oldVal = parent.get(this.key); \n int i = parent.indexOfKey(this.key);\n if (i != Attributes.NotFound)\n parent.vals[i] = val;\n }\n this.val = val;\n return Attributes.checkNotNull(oldVal);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-89"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-89"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-44", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n return new SimpleType(subclass, _bindings, this, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n return new SimpleType(subclass, _bindings, this, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n"}, "reference": " protected JavaType _narrow(Class subclass)\n {\n if (_class == subclass) {\n return this;\n }\n if (!_class.isAssignableFrom(subclass)) {\n return new SimpleType(subclass, _bindings, this, _superInterfaces,\n _valueHandler, _typeHandler, _asStatic);\n }\n Class next = subclass.getSuperclass();\n if (next == _class) { \n return new SimpleType(subclass, _bindings, this,\n _superInterfaces, _valueHandler, _typeHandler, _asStatic);\n }\n if ((next != null) && _class.isAssignableFrom(next)) {\n JavaType superb = _narrow(next);\n return new SimpleType(subclass, _bindings, superb,\n null, _valueHandler, _typeHandler, _asStatic);\n }\n Class[] nextI = subclass.getInterfaces();\n for (Class iface : nextI) {\n if (iface == _class) { \n return new SimpleType(subclass, _bindings, null,\n new JavaType[] { this }, _valueHandler, _typeHandler, _asStatic);\n }\n if (_class.isAssignableFrom(iface)) { \n JavaType superb = _narrow(iface);\n return new SimpleType(subclass, _bindings, null,\n new JavaType[] { superb }, _valueHandler, _typeHandler, _asStatic);\n }\n }\n throw new IllegalArgumentException(\"Internal error: Can not resolve sub-type for Class \"+subclass.getName()+\" to \"\n +_class.getName());\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-44"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-44"}} {"sample_uid": "defects4j_function_repair::Closure-62", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private String format(JSError error, boolean warning) {\n SourceExcerptProvider source = getSource();\n String sourceExcerpt = source == null ? null :\n excerpt.get(\n source, error.sourceName, error.lineNumber, excerptFormatter);\n StringBuilder b = new StringBuilder();\n if (error.sourceName != null) {\n b.append(error.sourceName);\n if (error.lineNumber > 0) {\n b.append(':');\n b.append(error.lineNumber);\n }\n b.append(\": \");\n }\n b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR));\n b.append(\" - \");\n b.append(error.description);\n b.append('\\n');\n if (sourceExcerpt != null) {\n b.append(sourceExcerpt);\n b.append('\\n');\n int charno = error.getCharno();\n if (excerpt.equals(LINE)\n && 0 <= charno && charno < sourceExcerpt.length()) {\n for (int i = 0; i < charno; i++) {\n char c = sourceExcerpt.charAt(i);\n if (Character.isWhitespace(c)) {\n b.append(c);\n } else {\n b.append(' ');\n }\n }\n b.append(\"^\\n\");\n }\n }\n return b.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private String format(JSError error, boolean warning) {\n SourceExcerptProvider source = getSource();\n String sourceExcerpt = source == null ? null :\n excerpt.get(\n source, error.sourceName, error.lineNumber, excerptFormatter);\n StringBuilder b = new StringBuilder();\n if (error.sourceName != null) {\n b.append(error.sourceName);\n if (error.lineNumber > 0) {\n b.append(':');\n b.append(error.lineNumber);\n }\n b.append(\": \");\n }\n b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR));\n b.append(\" - \");\n b.append(error.description);\n b.append('\\n');\n if (sourceExcerpt != null) {\n b.append(sourceExcerpt);\n b.append('\\n');\n int charno = error.getCharno();\n if (excerpt.equals(LINE)\n && 0 <= charno && charno < sourceExcerpt.length()) {\n for (int i = 0; i < charno; i++) {\n char c = sourceExcerpt.charAt(i);\n if (Character.isWhitespace(c)) {\n b.append(c);\n } else {\n b.append(' ');\n }\n }\n b.append(\"^\\n\");\n }\n }\n return b.toString();\n }\n"}, "reference": " private String format(JSError error, boolean warning) {\n SourceExcerptProvider source = getSource();\n String sourceExcerpt = source == null ? null :\n excerpt.get(\n source, error.sourceName, error.lineNumber, excerptFormatter);\n StringBuilder b = new StringBuilder();\n if (error.sourceName != null) {\n b.append(error.sourceName);\n if (error.lineNumber > 0) {\n b.append(':');\n b.append(error.lineNumber);\n }\n b.append(\": \");\n }\n b.append(getLevelName(warning ? CheckLevel.WARNING : CheckLevel.ERROR));\n b.append(\" - \");\n b.append(error.description);\n b.append('\\n');\n if (sourceExcerpt != null) {\n b.append(sourceExcerpt);\n b.append('\\n');\n int charno = error.getCharno();\n if (excerpt.equals(LINE)\n && 0 <= charno && charno <= sourceExcerpt.length()) {\n for (int i = 0; i < charno; i++) {\n char c = sourceExcerpt.charAt(i);\n if (Character.isWhitespace(c)) {\n b.append(c);\n } else {\n b.append(' ');\n }\n }\n b.append(\"^\\n\");\n }\n }\n return b.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-62"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-62"}} {"sample_uid": "defects4j_function_repair::Jsoup-93", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public List formData() {\n ArrayList data = new ArrayList<>();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n if (el.hasAttr(\"disabled\")) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (\"select\".equals(el.normalName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val().length() > 0 ? el.val() : \"on\";\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public List formData() {\n ArrayList data = new ArrayList<>();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n if (el.hasAttr(\"disabled\")) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (\"select\".equals(el.normalName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val().length() > 0 ? el.val() : \"on\";\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n"}, "reference": " public List formData() {\n ArrayList data = new ArrayList<>();\n for (Element el: elements) {\n if (!el.tag().isFormSubmittable()) continue; \n if (el.hasAttr(\"disabled\")) continue; \n String name = el.attr(\"name\");\n if (name.length() == 0) continue;\n String type = el.attr(\"type\");\n if (type.equalsIgnoreCase(\"button\")) continue; \n if (\"select\".equals(el.normalName())) {\n Elements options = el.select(\"option[selected]\");\n boolean set = false;\n for (Element option: options) {\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n set = true;\n }\n if (!set) {\n Element option = el.select(\"option\").first();\n if (option != null)\n data.add(HttpConnection.KeyVal.create(name, option.val()));\n }\n } else if (\"checkbox\".equalsIgnoreCase(type) || \"radio\".equalsIgnoreCase(type)) {\n if (el.hasAttr(\"checked\")) {\n final String val = el.val().length() > 0 ? el.val() : \"on\";\n data.add(HttpConnection.KeyVal.create(name, val));\n }\n } else {\n data.add(HttpConnection.KeyVal.create(name, el.val()));\n }\n }\n return data;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-93"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-93"}} {"sample_uid": "defects4j_function_repair::Closure-21", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (n.isExprResult()) {\n return;\n }\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (parent.getType() == Token.COMMA) {\n if (isResultUsed) {\n return;\n }\n if (n == parent.getLastChild()) {\n for (Node an : parent.getAncestors()) {\n int ancestorType = an.getType();\n if (ancestorType == Token.COMMA) continue;\n if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return;\n else break;\n }\n }\n } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {\n if (! (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext()))) {\n return;\n }\n }\n if (\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (n.isExprResult()) {\n return;\n }\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (parent.getType() == Token.COMMA) {\n if (isResultUsed) {\n return;\n }\n if (n == parent.getLastChild()) {\n for (Node an : parent.getAncestors()) {\n int ancestorType = an.getType();\n if (ancestorType == Token.COMMA) continue;\n if (ancestorType != Token.EXPR_RESULT && ancestorType != Token.BLOCK) return;\n else break;\n }\n }\n } else if (parent.getType() != Token.EXPR_RESULT && parent.getType() != Token.BLOCK) {\n if (! (parent.getType() == Token.FOR && parent.getChildCount() == 4 && (n == parent.getFirstChild() || n == parent.getFirstChild().getNext().getNext()))) {\n return;\n }\n }\n if (\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n"}, "reference": " public void visit(NodeTraversal t, Node n, Node parent) {\n if (n.isEmpty() ||\n n.isComma()) {\n return;\n }\n if (parent == null) {\n return;\n }\n if (n.isExprResult() || n.isBlock()) {\n return;\n }\n if (n.isQualifiedName() && n.getJSDocInfo() != null) {\n return;\n }\n boolean isResultUsed = NodeUtil.isExpressionResultUsed(n);\n boolean isSimpleOp = NodeUtil.isSimpleOperatorType(n.getType());\n if (!isResultUsed &&\n (isSimpleOp || !NodeUtil.mayHaveSideEffects(n, t.getCompiler()))) {\n String msg = \"This code lacks side-effects. Is there a bug?\";\n if (n.isString()) {\n msg = \"Is there a missing '+' on the previous line?\";\n } else if (isSimpleOp) {\n msg = \"The result of the '\" + Token.name(n.getType()).toLowerCase() +\n \"' operator is not being used.\";\n }\n t.getCompiler().report(\n t.makeError(n, level, USELESS_CODE_ERROR, msg));\n if (!NodeUtil.isStatement(n)) {\n problemNodes.add(n);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-21"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-21"}} {"sample_uid": "defects4j_function_repair::Math-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public T[] sample(int sampleSize) throws NotStrictlyPositiveException {\n if (sampleSize <= 0) {\n throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,\n sampleSize);\n }\n final T[]out = (T[]) java.lang.reflect.Array.newInstance(singletons.get(0).getClass(), sampleSize);\n for (int i = 0; i < sampleSize; i++) {\n out[i] = sample();\n }\n return out;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public T[] sample(int sampleSize) throws NotStrictlyPositiveException {\n if (sampleSize <= 0) {\n throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,\n sampleSize);\n }\n final T[]out = (T[]) java.lang.reflect.Array.newInstance(singletons.get(0).getClass(), sampleSize);\n for (int i = 0; i < sampleSize; i++) {\n out[i] = sample();\n }\n return out;\n }\n"}, "reference": " public Object[] sample(int sampleSize) throws NotStrictlyPositiveException {\n if (sampleSize <= 0) {\n throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,\n sampleSize);\n }\n final Object[] out = new Object[sampleSize];\n for (int i = 0; i < sampleSize; i++) {\n out[i] = sample();\n }\n return out;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-8"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-46", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public StringBuilder getGenericSignature(StringBuilder sb)\n {\n _classSignature(_class, sb, false);\n sb.append('<');\n sb = _referencedType.getGenericSignature(sb);\n sb.append(';');\n return sb;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public StringBuilder getGenericSignature(StringBuilder sb)\n {\n _classSignature(_class, sb, false);\n sb.append('<');\n sb = _referencedType.getGenericSignature(sb);\n sb.append(';');\n return sb;\n }\n"}, "reference": " public StringBuilder getGenericSignature(StringBuilder sb)\n {\n _classSignature(_class, sb, false);\n sb.append('<');\n sb = _referencedType.getGenericSignature(sb);\n sb.append(\">;\");\n return sb;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-46"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-46"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-91", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean _hasCustomHandlers(JavaType t) {\n if (t.isContainerType()) {\n JavaType ct = t.getContentType();\n if (ct != null) {\n return (ct.getValueHandler() != null) || (ct.getTypeHandler() != null);\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean _hasCustomHandlers(JavaType t) {\n if (t.isContainerType()) {\n JavaType ct = t.getContentType();\n if (ct != null) {\n return (ct.getValueHandler() != null) || (ct.getTypeHandler() != null);\n }\n }\n return false;\n }\n"}, "reference": " private boolean _hasCustomHandlers(JavaType t) {\n if (t.isContainerType()) {\n JavaType ct = t.getContentType();\n if (ct != null) {\n if ((ct.getValueHandler() != null) || (ct.getTypeHandler() != null)) {\n return true;\n }\n }\n if (t.isMapLikeType()) {\n JavaType kt = t.getKeyType();\n if (kt.getValueHandler() != null) {\n return true;\n }\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-91"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-91"}} {"sample_uid": "defects4j_function_repair::Lang-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = input.length();\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n pos+= c.length;\n continue;\n }\n for (int pt = 0; pt < consumed; pt++) {\n pos += Character.charCount(Character.codePointAt(input, pos));\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = input.length();\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n pos+= c.length;\n continue;\n }\n for (int pt = 0; pt < consumed; pt++) {\n pos += Character.charCount(Character.codePointAt(input, pos));\n }\n }\n }\n"}, "reference": " public final void translate(CharSequence input, Writer out) throws IOException {\n if (out == null) {\n throw new IllegalArgumentException(\"The Writer must not be null\");\n }\n if (input == null) {\n return;\n }\n int pos = 0;\n int len = input.length();\n while (pos < len) {\n int consumed = translate(input, pos, out);\n if (consumed == 0) {\n char[] c = Character.toChars(Character.codePointAt(input, pos));\n out.write(c);\n pos+= c.length;\n continue;\n }\n for (int pt = 0; pt < consumed; pt++) {\n pos += Character.charCount(Character.codePointAt(input, pt));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-6"}} {"sample_uid": "defects4j_function_repair::Compress-19", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void reparseCentralDirectoryData(boolean hasUncompressedSize,\n boolean hasCompressedSize,\n boolean hasRelativeHeaderOffset,\n boolean hasDiskStart)\n throws ZipException {\n if (rawCentralDirectoryData != null) {\n int expectedLength = (hasUncompressedSize ? DWORD : 0)\n + (hasCompressedSize ? DWORD : 0)\n + (hasRelativeHeaderOffset ? DWORD : 0)\n + (hasDiskStart ? WORD : 0);\n if (rawCentralDirectoryData.length != expectedLength) {\n throw new ZipException(\"central directory zip64 extended\"\n + \" information extra field's length\"\n + \" doesn't match central directory\"\n + \" data. Expected length \"\n + expectedLength + \" but is \"\n + rawCentralDirectoryData.length);\n }\n int offset = 0;\n if (hasUncompressedSize) {\n size = new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasCompressedSize) {\n compressedSize = new ZipEightByteInteger(rawCentralDirectoryData,\n offset);\n offset += DWORD;\n }\n if (hasRelativeHeaderOffset) {\n relativeHeaderOffset =\n new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasDiskStart) {\n diskStart = new ZipLong(rawCentralDirectoryData, offset);\n offset += WORD;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void reparseCentralDirectoryData(boolean hasUncompressedSize,\n boolean hasCompressedSize,\n boolean hasRelativeHeaderOffset,\n boolean hasDiskStart)\n throws ZipException {\n if (rawCentralDirectoryData != null) {\n int expectedLength = (hasUncompressedSize ? DWORD : 0)\n + (hasCompressedSize ? DWORD : 0)\n + (hasRelativeHeaderOffset ? DWORD : 0)\n + (hasDiskStart ? WORD : 0);\n if (rawCentralDirectoryData.length != expectedLength) {\n throw new ZipException(\"central directory zip64 extended\"\n + \" information extra field's length\"\n + \" doesn't match central directory\"\n + \" data. Expected length \"\n + expectedLength + \" but is \"\n + rawCentralDirectoryData.length);\n }\n int offset = 0;\n if (hasUncompressedSize) {\n size = new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasCompressedSize) {\n compressedSize = new ZipEightByteInteger(rawCentralDirectoryData,\n offset);\n offset += DWORD;\n }\n if (hasRelativeHeaderOffset) {\n relativeHeaderOffset =\n new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasDiskStart) {\n diskStart = new ZipLong(rawCentralDirectoryData, offset);\n offset += WORD;\n }\n }\n }\n"}, "reference": " public void reparseCentralDirectoryData(boolean hasUncompressedSize,\n boolean hasCompressedSize,\n boolean hasRelativeHeaderOffset,\n boolean hasDiskStart)\n throws ZipException {\n if (rawCentralDirectoryData != null) {\n int expectedLength = (hasUncompressedSize ? DWORD : 0)\n + (hasCompressedSize ? DWORD : 0)\n + (hasRelativeHeaderOffset ? DWORD : 0)\n + (hasDiskStart ? WORD : 0);\n if (rawCentralDirectoryData.length < expectedLength) {\n throw new ZipException(\"central directory zip64 extended\"\n + \" information extra field's length\"\n + \" doesn't match central directory\"\n + \" data. Expected length \"\n + expectedLength + \" but is \"\n + rawCentralDirectoryData.length);\n }\n int offset = 0;\n if (hasUncompressedSize) {\n size = new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasCompressedSize) {\n compressedSize = new ZipEightByteInteger(rawCentralDirectoryData,\n offset);\n offset += DWORD;\n }\n if (hasRelativeHeaderOffset) {\n relativeHeaderOffset =\n new ZipEightByteInteger(rawCentralDirectoryData, offset);\n offset += DWORD;\n }\n if (hasDiskStart) {\n diskStart = new ZipLong(rawCentralDirectoryData, offset);\n offset += WORD;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-19"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-19"}} {"sample_uid": "defects4j_function_repair::JacksonCore-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int writeValue() {\n if (_type == TYPE_OBJECT) {\n _gotName = false;\n ++_index;\n return STATUS_OK_AFTER_COLON;\n }\n if (_type == TYPE_ARRAY) {\n int ix = _index;\n ++_index;\n return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;\n }\n ++_index;\n return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int writeValue() {\n if (_type == TYPE_OBJECT) {\n _gotName = false;\n ++_index;\n return STATUS_OK_AFTER_COLON;\n }\n if (_type == TYPE_ARRAY) {\n int ix = _index;\n ++_index;\n return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;\n }\n ++_index;\n return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;\n }\n"}, "reference": " public int writeValue() {\n if (_type == TYPE_OBJECT) {\n if (!_gotName) {\n return STATUS_EXPECT_NAME;\n }\n _gotName = false;\n ++_index;\n return STATUS_OK_AFTER_COLON;\n }\n if (_type == TYPE_ARRAY) {\n int ix = _index;\n ++_index;\n return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;\n }\n ++_index;\n return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-7"}} {"sample_uid": "defects4j_function_repair::Compress-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public int read(byte[] buffer, int start, int length) throws IOException {\n if (closed) {\n throw new IOException(\"The stream is closed\");\n }\n if (inf.finished() || current == null) {\n return -1;\n }\n if (start <= buffer.length && length >= 0 && start >= 0\n && buffer.length - start >= length) {\n if (current.getMethod() == ZipArchiveOutputStream.STORED) {\n int csize = (int) current.getSize();\n if (readBytesOfEntry >= csize) {\n return -1;\n }\n if (offsetInBuffer >= lengthOfLastRead) {\n offsetInBuffer = 0;\n if ((lengthOfLastRead = in.read(buf)) == -1) {\n return -1;\n }\n count(lengthOfLastRead);\n bytesReadFromStream += lengthOfLastRead;\n }\n int toRead = length > lengthOfLastRead\n ? lengthOfLastRead - offsetInBuffer\n : length;\n if ((csize - readBytesOfEntry) < toRead) {\n toRead = csize - readBytesOfEntry;\n }\n System.arraycopy(buf, offsetInBuffer, buffer, start, toRead);\n offsetInBuffer += toRead;\n readBytesOfEntry += toRead;\n crc.update(buffer, start, toRead);\n return toRead;\n }\n if (inf.needsInput()) {\n fill();\n if (lengthOfLastRead > 0) {\n bytesReadFromStream += lengthOfLastRead;\n }\n }\n int read = 0;\n try {\n read = inf.inflate(buffer, start, length);\n } catch (DataFormatException e) {\n throw new ZipException(e.getMessage());\n }\n if (read == 0 && inf.finished()) {\n return -1;\n }\n crc.update(buffer, start, read);\n return read;\n }\n throw new ArrayIndexOutOfBoundsException();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public int read(byte[] buffer, int start, int length) throws IOException {\n if (closed) {\n throw new IOException(\"The stream is closed\");\n }\n if (inf.finished() || current == null) {\n return -1;\n }\n if (start <= buffer.length && length >= 0 && start >= 0\n && buffer.length - start >= length) {\n if (current.getMethod() == ZipArchiveOutputStream.STORED) {\n int csize = (int) current.getSize();\n if (readBytesOfEntry >= csize) {\n return -1;\n }\n if (offsetInBuffer >= lengthOfLastRead) {\n offsetInBuffer = 0;\n if ((lengthOfLastRead = in.read(buf)) == -1) {\n return -1;\n }\n count(lengthOfLastRead);\n bytesReadFromStream += lengthOfLastRead;\n }\n int toRead = length > lengthOfLastRead\n ? lengthOfLastRead - offsetInBuffer\n : length;\n if ((csize - readBytesOfEntry) < toRead) {\n toRead = csize - readBytesOfEntry;\n }\n System.arraycopy(buf, offsetInBuffer, buffer, start, toRead);\n offsetInBuffer += toRead;\n readBytesOfEntry += toRead;\n crc.update(buffer, start, toRead);\n return toRead;\n }\n if (inf.needsInput()) {\n fill();\n if (lengthOfLastRead > 0) {\n bytesReadFromStream += lengthOfLastRead;\n }\n }\n int read = 0;\n try {\n read = inf.inflate(buffer, start, length);\n } catch (DataFormatException e) {\n throw new ZipException(e.getMessage());\n }\n if (read == 0 && inf.finished()) {\n return -1;\n }\n crc.update(buffer, start, read);\n return read;\n }\n throw new ArrayIndexOutOfBoundsException();\n }\n"}, "reference": " public int read(byte[] buffer, int start, int length) throws IOException {\n if (closed) {\n throw new IOException(\"The stream is closed\");\n }\n if (inf.finished() || current == null) {\n return -1;\n }\n if (start <= buffer.length && length >= 0 && start >= 0\n && buffer.length - start >= length) {\n if (current.getMethod() == ZipArchiveOutputStream.STORED) {\n int csize = (int) current.getSize();\n if (readBytesOfEntry >= csize) {\n return -1;\n }\n if (offsetInBuffer >= lengthOfLastRead) {\n offsetInBuffer = 0;\n if ((lengthOfLastRead = in.read(buf)) == -1) {\n return -1;\n }\n count(lengthOfLastRead);\n bytesReadFromStream += lengthOfLastRead;\n }\n int toRead = length > lengthOfLastRead\n ? lengthOfLastRead - offsetInBuffer\n : length;\n if ((csize - readBytesOfEntry) < toRead) {\n toRead = csize - readBytesOfEntry;\n }\n System.arraycopy(buf, offsetInBuffer, buffer, start, toRead);\n offsetInBuffer += toRead;\n readBytesOfEntry += toRead;\n crc.update(buffer, start, toRead);\n return toRead;\n }\n if (inf.needsInput()) {\n fill();\n if (lengthOfLastRead > 0) {\n bytesReadFromStream += lengthOfLastRead;\n }\n }\n int read = 0;\n try {\n read = inf.inflate(buffer, start, length);\n } catch (DataFormatException e) {\n throw new ZipException(e.getMessage());\n }\n if (read == 0) {\n if (inf.finished()) {\n return -1;\n } else if (lengthOfLastRead == -1) {\n throw new IOException(\"Truncated ZIP file\");\n }\n }\n crc.update(buffer, start, read);\n return read;\n }\n throw new ArrayIndexOutOfBoundsException();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-5"}} {"sample_uid": "defects4j_function_repair::JacksonCore-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n char c = str.charAt(i++);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n char c = str.charAt(i++);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n"}, "reference": " private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n char c = str.charAt(i);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-5"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean isCachable() {\n return (_valueTypeDeserializer == null)\n && (_ignorableProperties == null);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean isCachable() {\n return (_valueTypeDeserializer == null)\n && (_ignorableProperties == null);\n }\n"}, "reference": " public boolean isCachable() {\n return (_valueDeserializer == null)\n && (_keyDeserializer == null)\n && (_valueTypeDeserializer == null)\n && (_ignorableProperties == null);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-12"}} {"sample_uid": "defects4j_function_repair::Compress-46", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static ZipLong unixTimeToZipLong(long l) {\n final long TWO_TO_32 = 0x100000000L;\n if (l >= TWO_TO_32) {\n throw new IllegalArgumentException(\"X5455 timestamps must fit in a signed 32 bit integer: \" + l);\n }\n return new ZipLong(l);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static ZipLong unixTimeToZipLong(long l) {\n final long TWO_TO_32 = 0x100000000L;\n if (l >= TWO_TO_32) {\n throw new IllegalArgumentException(\"X5455 timestamps must fit in a signed 32 bit integer: \" + l);\n }\n return new ZipLong(l);\n }\n"}, "reference": " private static ZipLong unixTimeToZipLong(long l) {\n if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {\n throw new IllegalArgumentException(\"X5455 timestamps must fit in a signed 32 bit integer: \" + l);\n }\n return new ZipLong(l);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-46"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-46"}} {"sample_uid": "defects4j_function_repair::JxPath-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean testNode(Node node, NodeTest test) {\n if (test == null) {\n return true;\n }\n if (test instanceof NodeNameTest) {\n if (node.getNodeType() != Node.ELEMENT_NODE) {\n return false;\n }\n NodeNameTest nodeNameTest = (NodeNameTest) test;\n QName testName = nodeNameTest.getNodeName();\n String namespaceURI = nodeNameTest.getNamespaceURI();\n boolean wildcard = nodeNameTest.isWildcard();\n String testPrefix = testName.getPrefix();\n if (wildcard && testPrefix == null) {\n return true;\n }\n if (wildcard\n || testName.getName()\n .equals(DOMNodePointer.getLocalName(node))) {\n String nodeNS = DOMNodePointer.getNamespaceURI(node);\n return equalStrings(namespaceURI, nodeNS);\n }\n return false;\n }\n if (test instanceof NodeTypeTest) {\n int nodeType = node.getNodeType();\n switch (((NodeTypeTest) test).getNodeType()) {\n case Compiler.NODE_TYPE_NODE :\n return nodeType == Node.ELEMENT_NODE\n || nodeType == Node.DOCUMENT_NODE;\n case Compiler.NODE_TYPE_TEXT :\n return nodeType == Node.CDATA_SECTION_NODE\n || nodeType == Node.TEXT_NODE;\n case Compiler.NODE_TYPE_COMMENT :\n return nodeType == Node.COMMENT_NODE;\n case Compiler.NODE_TYPE_PI :\n return nodeType == Node.PROCESSING_INSTRUCTION_NODE;\n }\n return false;\n }\n if (test instanceof ProcessingInstructionTest) {\n if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {\n String testPI = ((ProcessingInstructionTest) test).getTarget();\n String nodePI = ((ProcessingInstruction) node).getTarget();\n return testPI.equals(nodePI);\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean testNode(Node node, NodeTest test) {\n if (test == null) {\n return true;\n }\n if (test instanceof NodeNameTest) {\n if (node.getNodeType() != Node.ELEMENT_NODE) {\n return false;\n }\n NodeNameTest nodeNameTest = (NodeNameTest) test;\n QName testName = nodeNameTest.getNodeName();\n String namespaceURI = nodeNameTest.getNamespaceURI();\n boolean wildcard = nodeNameTest.isWildcard();\n String testPrefix = testName.getPrefix();\n if (wildcard && testPrefix == null) {\n return true;\n }\n if (wildcard\n || testName.getName()\n .equals(DOMNodePointer.getLocalName(node))) {\n String nodeNS = DOMNodePointer.getNamespaceURI(node);\n return equalStrings(namespaceURI, nodeNS);\n }\n return false;\n }\n if (test instanceof NodeTypeTest) {\n int nodeType = node.getNodeType();\n switch (((NodeTypeTest) test).getNodeType()) {\n case Compiler.NODE_TYPE_NODE :\n return nodeType == Node.ELEMENT_NODE\n || nodeType == Node.DOCUMENT_NODE;\n case Compiler.NODE_TYPE_TEXT :\n return nodeType == Node.CDATA_SECTION_NODE\n || nodeType == Node.TEXT_NODE;\n case Compiler.NODE_TYPE_COMMENT :\n return nodeType == Node.COMMENT_NODE;\n case Compiler.NODE_TYPE_PI :\n return nodeType == Node.PROCESSING_INSTRUCTION_NODE;\n }\n return false;\n }\n if (test instanceof ProcessingInstructionTest) {\n if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {\n String testPI = ((ProcessingInstructionTest) test).getTarget();\n String nodePI = ((ProcessingInstruction) node).getTarget();\n return testPI.equals(nodePI);\n }\n }\n return false;\n }\n"}, "reference": " public static boolean testNode(Node node, NodeTest test) {\n if (test == null) {\n return true;\n }\n if (test instanceof NodeNameTest) {\n if (node.getNodeType() != Node.ELEMENT_NODE) {\n return false;\n }\n NodeNameTest nodeNameTest = (NodeNameTest) test;\n QName testName = nodeNameTest.getNodeName();\n String namespaceURI = nodeNameTest.getNamespaceURI();\n boolean wildcard = nodeNameTest.isWildcard();\n String testPrefix = testName.getPrefix();\n if (wildcard && testPrefix == null) {\n return true;\n }\n if (wildcard\n || testName.getName()\n .equals(DOMNodePointer.getLocalName(node))) {\n String nodeNS = DOMNodePointer.getNamespaceURI(node);\n return equalStrings(namespaceURI, nodeNS) || nodeNS == null\n && equalStrings(testPrefix, getPrefix(node));\n }\n return false;\n }\n if (test instanceof NodeTypeTest) {\n int nodeType = node.getNodeType();\n switch (((NodeTypeTest) test).getNodeType()) {\n case Compiler.NODE_TYPE_NODE :\n return nodeType == Node.ELEMENT_NODE\n || nodeType == Node.DOCUMENT_NODE;\n case Compiler.NODE_TYPE_TEXT :\n return nodeType == Node.CDATA_SECTION_NODE\n || nodeType == Node.TEXT_NODE;\n case Compiler.NODE_TYPE_COMMENT :\n return nodeType == Node.COMMENT_NODE;\n case Compiler.NODE_TYPE_PI :\n return nodeType == Node.PROCESSING_INSTRUCTION_NODE;\n }\n return false;\n }\n if (test instanceof ProcessingInstructionTest) {\n if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {\n String testPI = ((ProcessingInstructionTest) test).getTarget();\n String nodePI = ((ProcessingInstruction) node).getTarget();\n return testPI.equals(nodePI);\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JxPath-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JxPath-12"}} {"sample_uid": "defects4j_function_repair::Math-63", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean equals(double x, double y) {\n return (Double.isNaN(x) && Double.isNaN(y)) || x == y;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean equals(double x, double y) {\n return (Double.isNaN(x) && Double.isNaN(y)) || x == y;\n }\n"}, "reference": " public static boolean equals(double x, double y) {\n return equals(x, y, 1);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-63"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-63"}} {"sample_uid": "defects4j_function_repair::Math-60", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double cumulativeProbability(double x) throws MathException {\n final double dev = x - mean;\n try {\n return 0.5 * (1.0 + Erf.erf((dev) /\n (standardDeviation * FastMath.sqrt(2.0))));\n } catch (MaxIterationsExceededException ex) {\n if (x < (mean - 20 * standardDeviation)) { \n return 0;\n } else if (x > (mean + 20 * standardDeviation)) {\n return 1;\n } else {\n throw ex;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double cumulativeProbability(double x) throws MathException {\n final double dev = x - mean;\n try {\n return 0.5 * (1.0 + Erf.erf((dev) /\n (standardDeviation * FastMath.sqrt(2.0))));\n } catch (MaxIterationsExceededException ex) {\n if (x < (mean - 20 * standardDeviation)) { \n return 0;\n } else if (x > (mean + 20 * standardDeviation)) {\n return 1;\n } else {\n throw ex;\n }\n }\n }\n"}, "reference": " public double cumulativeProbability(double x) throws MathException {\n final double dev = x - mean;\n if (FastMath.abs(dev) > 40 * standardDeviation) { \n return dev < 0 ? 0.0d : 1.0d;\n }\n return 0.5 * (1.0 + Erf.erf((dev) /\n (standardDeviation * FastMath.sqrt(2.0))));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-60"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-60"}} {"sample_uid": "defects4j_function_repair::Lang-29", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static float toJavaVersionInt(String version) {\n return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static float toJavaVersionInt(String version) {\n return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));\n }\n"}, "reference": " static int toJavaVersionInt(String version) {\n return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-29"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-29"}} {"sample_uid": "defects4j_function_repair::JxPath-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private int compareNodePointers(\n NodePointer p1,\n int depth1,\n NodePointer p2,\n int depth2) \n {\n if (depth1 < depth2) {\n int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);\n return r == 0 ? -1 : r;\n }\n if (depth1 > depth2) {\n int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2);\n return r == 0 ? 1 : r;\n }\n if (p1 == null && p2 == null) {\n return 0;\n }\n if (p1 != null && p1.equals(p2)) {\n return 0;\n }\n if (depth1 == 1) {\n throw new JXPathException(\n \"Cannot compare pointers that do not belong to the same tree: '\"\n + p1 + \"' and '\" + p2 + \"'\");\n }\n int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1);\n if (r != 0) {\n return r;\n }\n return p1.parent.compareChildNodePointers(p1, p2);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private int compareNodePointers(\n NodePointer p1,\n int depth1,\n NodePointer p2,\n int depth2) \n {\n if (depth1 < depth2) {\n int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);\n return r == 0 ? -1 : r;\n }\n if (depth1 > depth2) {\n int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2);\n return r == 0 ? 1 : r;\n }\n if (p1 == null && p2 == null) {\n return 0;\n }\n if (p1 != null && p1.equals(p2)) {\n return 0;\n }\n if (depth1 == 1) {\n throw new JXPathException(\n \"Cannot compare pointers that do not belong to the same tree: '\"\n + p1 + \"' and '\" + p2 + \"'\");\n }\n int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1);\n if (r != 0) {\n return r;\n }\n return p1.parent.compareChildNodePointers(p1, p2);\n }\n"}, "reference": " private int compareNodePointers(\n NodePointer p1,\n int depth1,\n NodePointer p2,\n int depth2) \n {\n if (depth1 < depth2) {\n int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);\n return r == 0 ? -1 : r;\n }\n if (depth1 > depth2) {\n int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2);\n return r == 0 ? 1 : r;\n }\n if (p1 == null && p2 == null) {\n return 0;\n }\n if (p1 != null && p1.equals(p2)) {\n return 0;\n }\n if (depth1 == 1) {\n return 0;\n }\n int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1);\n if (r != 0) {\n return r;\n }\n return p1.parent.compareChildNodePointers(p1, p2);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JxPath-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JxPath-5"}} {"sample_uid": "defects4j_function_repair::Math-59", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static float max(final float a, final float b) {\n return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : b);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static float max(final float a, final float b) {\n return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : b);\n }\n"}, "reference": " public static float max(final float a, final float b) {\n return (a <= b) ? b : (Float.isNaN(a + b) ? Float.NaN : a);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-59"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-59"}} {"sample_uid": "defects4j_function_repair::Lang-33", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Class[] toClass(Object[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CLASS_ARRAY;\n }\n Class[] classes = new Class[array.length];\n for (int i = 0; i < array.length; i++) {\n classes[i] = array[i].getClass();\n }\n return classes;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Class[] toClass(Object[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CLASS_ARRAY;\n }\n Class[] classes = new Class[array.length];\n for (int i = 0; i < array.length; i++) {\n classes[i] = array[i].getClass();\n }\n return classes;\n }\n"}, "reference": " public static Class[] toClass(Object[] array) {\n if (array == null) {\n return null;\n } else if (array.length == 0) {\n return ArrayUtils.EMPTY_CLASS_ARRAY;\n }\n Class[] classes = new Class[array.length];\n for (int i = 0; i < array.length; i++) {\n classes[i] = array[i] == null ? null : array[i].getClass();\n }\n return classes;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-33"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-33"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-74", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,\n TokenBuffer tb) throws IOException\n {\n JsonDeserializer deser = _findDefaultImplDeserializer(ctxt);\n if (deser != null) {\n if (tb != null) {\n tb.writeEndObject();\n p = tb.asParser(p);\n p.nextToken();\n }\n return deser.deserialize(p, ctxt);\n }\n Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);\n if (result != null) {\n return result;\n }\n if (p.getCurrentToken() == JsonToken.START_ARRAY) {\n return super.deserializeTypedFromAny(p, ctxt);\n }\n ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,\n \"missing property '\"+_typePropertyName+\"' that is to contain type id (for class \"+baseTypeName()+\")\");\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,\n TokenBuffer tb) throws IOException\n {\n JsonDeserializer deser = _findDefaultImplDeserializer(ctxt);\n if (deser != null) {\n if (tb != null) {\n tb.writeEndObject();\n p = tb.asParser(p);\n p.nextToken();\n }\n return deser.deserialize(p, ctxt);\n }\n Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);\n if (result != null) {\n return result;\n }\n if (p.getCurrentToken() == JsonToken.START_ARRAY) {\n return super.deserializeTypedFromAny(p, ctxt);\n }\n ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,\n \"missing property '\"+_typePropertyName+\"' that is to contain type id (for class \"+baseTypeName()+\")\");\n return null;\n }\n"}, "reference": " protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,\n TokenBuffer tb) throws IOException\n {\n JsonDeserializer deser = _findDefaultImplDeserializer(ctxt);\n if (deser != null) {\n if (tb != null) {\n tb.writeEndObject();\n p = tb.asParser(p);\n p.nextToken();\n }\n return deser.deserialize(p, ctxt);\n }\n Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);\n if (result != null) {\n return result;\n }\n if (p.getCurrentToken() == JsonToken.START_ARRAY) {\n return super.deserializeTypedFromAny(p, ctxt);\n } else if (p.getCurrentToken() == JsonToken.VALUE_STRING) {\n if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {\n String str = p.getText().trim();\n if (str.isEmpty()) {\n return null;\n }\n }\n }\n ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,\n \"missing property '\"+_typePropertyName+\"' that is to contain type id (for class \"+baseTypeName()+\")\");\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-74"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-74"}} {"sample_uid": "defects4j_function_repair::Compress-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ZipArchiveEntry other = (ZipArchiveEntry) obj;\n String myName = getName();\n String otherName = other.getName();\n if (myName == null) {\n if (otherName != null) {\n return false;\n }\n } else if (!myName.equals(otherName)) {\n return false;\n }\n String myComment = getComment();\n String otherComment = other.getComment();\n if (myComment == null) {\n if (otherComment != null) {\n return false;\n }\n } else if (!myComment.equals(otherComment)) {\n return false;\n }\n return getTime() == other.getTime()\n && getInternalAttributes() == other.getInternalAttributes()\n && getPlatform() == other.getPlatform()\n && getExternalAttributes() == other.getExternalAttributes()\n && getMethod() == other.getMethod()\n && getSize() == other.getSize()\n && getCrc() == other.getCrc()\n && getCompressedSize() == other.getCompressedSize()\n && Arrays.equals(getCentralDirectoryExtra(),\n other.getCentralDirectoryExtra())\n && Arrays.equals(getLocalFileDataExtra(),\n other.getLocalFileDataExtra())\n && gpb.equals(other.gpb);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ZipArchiveEntry other = (ZipArchiveEntry) obj;\n String myName = getName();\n String otherName = other.getName();\n if (myName == null) {\n if (otherName != null) {\n return false;\n }\n } else if (!myName.equals(otherName)) {\n return false;\n }\n String myComment = getComment();\n String otherComment = other.getComment();\n if (myComment == null) {\n if (otherComment != null) {\n return false;\n }\n } else if (!myComment.equals(otherComment)) {\n return false;\n }\n return getTime() == other.getTime()\n && getInternalAttributes() == other.getInternalAttributes()\n && getPlatform() == other.getPlatform()\n && getExternalAttributes() == other.getExternalAttributes()\n && getMethod() == other.getMethod()\n && getSize() == other.getSize()\n && getCrc() == other.getCrc()\n && getCompressedSize() == other.getCompressedSize()\n && Arrays.equals(getCentralDirectoryExtra(),\n other.getCentralDirectoryExtra())\n && Arrays.equals(getLocalFileDataExtra(),\n other.getLocalFileDataExtra())\n && gpb.equals(other.gpb);\n }\n"}, "reference": " public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n ZipArchiveEntry other = (ZipArchiveEntry) obj;\n String myName = getName();\n String otherName = other.getName();\n if (myName == null) {\n if (otherName != null) {\n return false;\n }\n } else if (!myName.equals(otherName)) {\n return false;\n }\n String myComment = getComment();\n String otherComment = other.getComment();\n if (myComment == null) {\n myComment = \"\";\n }\n if (otherComment == null) {\n otherComment = \"\";\n }\n return getTime() == other.getTime()\n && myComment.equals(otherComment)\n && getInternalAttributes() == other.getInternalAttributes()\n && getPlatform() == other.getPlatform()\n && getExternalAttributes() == other.getExternalAttributes()\n && getMethod() == other.getMethod()\n && getSize() == other.getSize()\n && getCrc() == other.getCrc()\n && getCompressedSize() == other.getCompressedSize()\n && Arrays.equals(getCentralDirectoryExtra(),\n other.getCentralDirectoryExtra())\n && Arrays.equals(getLocalFileDataExtra(),\n other.getLocalFileDataExtra())\n && gpb.equals(other.gpb);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-15"}} {"sample_uid": "defects4j_function_repair::Closure-31", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement() &&\n !options.skipAllPasses &&\n options.closurePass) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (n.getJSDocInfo() != null) {\n JSDocInfo info = n.getJSDocInfo();\n if (info.isExterns()) {\n externsRoot.addChildToBack(n);\n input.setIsExtern(true);\n input.getModule().remove(input);\n externs.add(input);\n staleInputs = true;\n } else if (info.isNoCompile()) {\n input.getModule().remove(input);\n staleInputs = true;\n }\n }\n }\n if (staleInputs) {\n fillEmptyModules(modules);\n rebuildInputsFromModules();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement() &&\n !options.skipAllPasses &&\n options.closurePass) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (n.getJSDocInfo() != null) {\n JSDocInfo info = n.getJSDocInfo();\n if (info.isExterns()) {\n externsRoot.addChildToBack(n);\n input.setIsExtern(true);\n input.getModule().remove(input);\n externs.add(input);\n staleInputs = true;\n } else if (info.isNoCompile()) {\n input.getModule().remove(input);\n staleInputs = true;\n }\n }\n }\n if (staleInputs) {\n fillEmptyModules(modules);\n rebuildInputsFromModules();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n"}, "reference": " Node parseInputs() {\n boolean devMode = options.devMode != DevMode.OFF;\n if (externsRoot != null) {\n externsRoot.detachChildren();\n }\n if (jsRoot != null) {\n jsRoot.detachChildren();\n }\n jsRoot = IR.block();\n jsRoot.setIsSyntheticBlock(true);\n externsRoot = IR.block();\n externsRoot.setIsSyntheticBlock(true);\n externAndJsRoot = IR.block(externsRoot, jsRoot);\n externAndJsRoot.setIsSyntheticBlock(true);\n if (options.tracer.isOn()) {\n tracker = new PerformanceTracker(jsRoot, options.tracer);\n addChangeHandler(tracker.getCodeChangeHandler());\n }\n Tracer tracer = newTracer(\"parseInputs\");\n try {\n for (CompilerInput input : externs) {\n Node n = input.getAstRoot(this);\n if (hasErrors()) {\n return null;\n }\n externsRoot.addChildToBack(n);\n }\n if (options.transformAMDToCJSModules || options.processCommonJSModules) {\n processAMDAndCommonJSModules();\n }\n boolean staleInputs = false;\n if (options.dependencyOptions.needsManagement() &&\n options.closurePass) {\n for (CompilerInput input : inputs) {\n for (String provide : input.getProvides()) {\n getTypeRegistry().forwardDeclareType(provide);\n }\n }\n try {\n inputs =\n (moduleGraph == null ? new JSModuleGraph(modules) : moduleGraph)\n .manageDependencies(options.dependencyOptions, inputs);\n staleInputs = true;\n } catch (CircularDependencyException e) {\n report(JSError.make(\n JSModule.CIRCULAR_DEPENDENCY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n } catch (MissingProvideException e) {\n report(JSError.make(\n MISSING_ENTRY_ERROR, e.getMessage()));\n if (hasErrors()) {\n return null;\n }\n }\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (n.getJSDocInfo() != null) {\n JSDocInfo info = n.getJSDocInfo();\n if (info.isExterns()) {\n externsRoot.addChildToBack(n);\n input.setIsExtern(true);\n input.getModule().remove(input);\n externs.add(input);\n staleInputs = true;\n } else if (info.isNoCompile()) {\n input.getModule().remove(input);\n staleInputs = true;\n }\n }\n }\n if (staleInputs) {\n fillEmptyModules(modules);\n rebuildInputsFromModules();\n }\n for (CompilerInput input : inputs) {\n Node n = input.getAstRoot(this);\n if (n == null) {\n continue;\n }\n if (devMode) {\n runSanityCheck();\n if (hasErrors()) {\n return null;\n }\n }\n if (options.sourceMapOutputPath != null ||\n options.nameReferenceReportPath != null) {\n SourceInformationAnnotator sia =\n new SourceInformationAnnotator(\n input.getName(), options.devMode != DevMode.OFF);\n NodeTraversal.traverse(this, n, sia);\n }\n jsRoot.addChildToBack(n);\n }\n if (hasErrors()) {\n return null;\n }\n return externAndJsRoot;\n } finally {\n stopTracer(tracer, \"parseInputs\");\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-31"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-31"}} {"sample_uid": "defects4j_function_repair::Lang-57", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean isAvailableLocale(Locale locale) {\n return cAvailableLocaleSet.contains(locale);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean isAvailableLocale(Locale locale) {\n return cAvailableLocaleSet.contains(locale);\n }\n"}, "reference": " public static boolean isAvailableLocale(Locale locale) {\n return availableLocaleList().contains(locale);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-57"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-57"}} {"sample_uid": "defects4j_function_repair::Jsoup-75", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {\n final int sz = size;\n for (int i = 0; i < sz; i++) {\n final String key = keys[i];\n final String val = vals[i];\n accum.append(' ').append(key);\n if (!(out.syntax() == Document.OutputSettings.Syntax.html\n && (val == null || val.equals(key) && Attribute.isBooleanAttribute(key)))) {\n accum.append(\"=\\\"\");\n Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false);\n accum.append('\"');\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {\n final int sz = size;\n for (int i = 0; i < sz; i++) {\n final String key = keys[i];\n final String val = vals[i];\n accum.append(' ').append(key);\n if (!(out.syntax() == Document.OutputSettings.Syntax.html\n && (val == null || val.equals(key) && Attribute.isBooleanAttribute(key)))) {\n accum.append(\"=\\\"\");\n Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false);\n accum.append('\"');\n }\n }\n }\n"}, "reference": " final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {\n final int sz = size;\n for (int i = 0; i < sz; i++) {\n final String key = keys[i];\n final String val = vals[i];\n accum.append(' ').append(key);\n if (!Attribute.shouldCollapseAttribute(key, val, out)) {\n accum.append(\"=\\\"\");\n Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false);\n accum.append('\"');\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-75"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-75"}} {"sample_uid": "defects4j_function_repair::Lang-51", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean toBoolean(String str) {\n if (str == \"true\") {\n return true;\n }\n if (str == null) {\n return false;\n }\n switch (str.length()) {\n case 2: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n return \n (ch0 == 'o' || ch0 == 'O') &&\n (ch1 == 'n' || ch1 == 'N');\n }\n case 3: {\n char ch = str.charAt(0);\n if (ch == 'y') {\n return \n (str.charAt(1) == 'e' || str.charAt(1) == 'E') &&\n (str.charAt(2) == 's' || str.charAt(2) == 'S');\n }\n if (ch == 'Y') {\n return \n (str.charAt(1) == 'E' || str.charAt(1) == 'e') &&\n (str.charAt(2) == 'S' || str.charAt(2) == 's');\n }\n }\n case 4: {\n char ch = str.charAt(0);\n if (ch == 't') {\n return \n (str.charAt(1) == 'r' || str.charAt(1) == 'R') &&\n (str.charAt(2) == 'u' || str.charAt(2) == 'U') &&\n (str.charAt(3) == 'e' || str.charAt(3) == 'E');\n }\n if (ch == 'T') {\n return \n (str.charAt(1) == 'R' || str.charAt(1) == 'r') &&\n (str.charAt(2) == 'U' || str.charAt(2) == 'u') &&\n (str.charAt(3) == 'E' || str.charAt(3) == 'e');\n }\n }\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean toBoolean(String str) {\n if (str == \"true\") {\n return true;\n }\n if (str == null) {\n return false;\n }\n switch (str.length()) {\n case 2: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n return \n (ch0 == 'o' || ch0 == 'O') &&\n (ch1 == 'n' || ch1 == 'N');\n }\n case 3: {\n char ch = str.charAt(0);\n if (ch == 'y') {\n return \n (str.charAt(1) == 'e' || str.charAt(1) == 'E') &&\n (str.charAt(2) == 's' || str.charAt(2) == 'S');\n }\n if (ch == 'Y') {\n return \n (str.charAt(1) == 'E' || str.charAt(1) == 'e') &&\n (str.charAt(2) == 'S' || str.charAt(2) == 's');\n }\n }\n case 4: {\n char ch = str.charAt(0);\n if (ch == 't') {\n return \n (str.charAt(1) == 'r' || str.charAt(1) == 'R') &&\n (str.charAt(2) == 'u' || str.charAt(2) == 'U') &&\n (str.charAt(3) == 'e' || str.charAt(3) == 'E');\n }\n if (ch == 'T') {\n return \n (str.charAt(1) == 'R' || str.charAt(1) == 'r') &&\n (str.charAt(2) == 'U' || str.charAt(2) == 'u') &&\n (str.charAt(3) == 'E' || str.charAt(3) == 'e');\n }\n }\n }\n return false;\n }\n"}, "reference": " public static boolean toBoolean(String str) {\n if (str == \"true\") {\n return true;\n }\n if (str == null) {\n return false;\n }\n switch (str.length()) {\n case 2: {\n char ch0 = str.charAt(0);\n char ch1 = str.charAt(1);\n return \n (ch0 == 'o' || ch0 == 'O') &&\n (ch1 == 'n' || ch1 == 'N');\n }\n case 3: {\n char ch = str.charAt(0);\n if (ch == 'y') {\n return \n (str.charAt(1) == 'e' || str.charAt(1) == 'E') &&\n (str.charAt(2) == 's' || str.charAt(2) == 'S');\n }\n if (ch == 'Y') {\n return \n (str.charAt(1) == 'E' || str.charAt(1) == 'e') &&\n (str.charAt(2) == 'S' || str.charAt(2) == 's');\n }\n return false;\n }\n case 4: {\n char ch = str.charAt(0);\n if (ch == 't') {\n return \n (str.charAt(1) == 'r' || str.charAt(1) == 'R') &&\n (str.charAt(2) == 'u' || str.charAt(2) == 'U') &&\n (str.charAt(3) == 'e' || str.charAt(3) == 'E');\n }\n if (ch == 'T') {\n return \n (str.charAt(1) == 'R' || str.charAt(1) == 'r') &&\n (str.charAt(2) == 'U' || str.charAt(2) == 'u') &&\n (str.charAt(3) == 'E' || str.charAt(3) == 'e');\n }\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-51"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-51"}} {"sample_uid": "defects4j_function_repair::Closure-126", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void tryMinimizeExits(Node n, int exitType, String labelName) {\n if (matchingExitNode(n, exitType, labelName)) {\n NodeUtil.removeChild(n.getParent(), n);\n compiler.reportCodeChange();\n return;\n }\n if (n.isIf()) {\n Node ifBlock = n.getFirstChild().getNext();\n tryMinimizeExits(ifBlock, exitType, labelName);\n Node elseBlock = ifBlock.getNext();\n if (elseBlock != null) {\n tryMinimizeExits(elseBlock, exitType, labelName);\n }\n return;\n }\n if (n.isTry()) {\n Node tryBlock = n.getFirstChild();\n tryMinimizeExits(tryBlock, exitType, labelName);\n Node allCatchNodes = NodeUtil.getCatchBlock(n);\n if (NodeUtil.hasCatchHandler(allCatchNodes)) {\n Preconditions.checkState(allCatchNodes.hasOneChild());\n Node catchNode = allCatchNodes.getFirstChild();\n Node catchCodeBlock = catchNode.getLastChild();\n tryMinimizeExits(catchCodeBlock, exitType, labelName);\n }\n if (NodeUtil.hasFinally(n)) {\n Node finallyBlock = n.getLastChild();\n tryMinimizeExits(finallyBlock, exitType, labelName);\n }\n }\n if (n.isLabel()) {\n Node labelBlock = n.getLastChild();\n tryMinimizeExits(labelBlock, exitType, labelName);\n }\n if (!n.isBlock() || n.getLastChild() == null) {\n return;\n }\n for (Node c : n.children()) {\n if (c.isIf()) {\n Node ifTree = c;\n Node trueBlock, falseBlock;\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n tryMinimizeIfBlockExits(trueBlock, falseBlock,\n ifTree, exitType, labelName);\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n if (falseBlock != null) {\n tryMinimizeIfBlockExits(falseBlock, trueBlock,\n ifTree, exitType, labelName);\n }\n }\n if (c == n.getLastChild()) {\n break;\n }\n }\n for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) {\n tryMinimizeExits(c, exitType, labelName);\n if (c == n.getLastChild()) {\n break;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void tryMinimizeExits(Node n, int exitType, String labelName) {\n if (matchingExitNode(n, exitType, labelName)) {\n NodeUtil.removeChild(n.getParent(), n);\n compiler.reportCodeChange();\n return;\n }\n if (n.isIf()) {\n Node ifBlock = n.getFirstChild().getNext();\n tryMinimizeExits(ifBlock, exitType, labelName);\n Node elseBlock = ifBlock.getNext();\n if (elseBlock != null) {\n tryMinimizeExits(elseBlock, exitType, labelName);\n }\n return;\n }\n if (n.isTry()) {\n Node tryBlock = n.getFirstChild();\n tryMinimizeExits(tryBlock, exitType, labelName);\n Node allCatchNodes = NodeUtil.getCatchBlock(n);\n if (NodeUtil.hasCatchHandler(allCatchNodes)) {\n Preconditions.checkState(allCatchNodes.hasOneChild());\n Node catchNode = allCatchNodes.getFirstChild();\n Node catchCodeBlock = catchNode.getLastChild();\n tryMinimizeExits(catchCodeBlock, exitType, labelName);\n }\n if (NodeUtil.hasFinally(n)) {\n Node finallyBlock = n.getLastChild();\n tryMinimizeExits(finallyBlock, exitType, labelName);\n }\n }\n if (n.isLabel()) {\n Node labelBlock = n.getLastChild();\n tryMinimizeExits(labelBlock, exitType, labelName);\n }\n if (!n.isBlock() || n.getLastChild() == null) {\n return;\n }\n for (Node c : n.children()) {\n if (c.isIf()) {\n Node ifTree = c;\n Node trueBlock, falseBlock;\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n tryMinimizeIfBlockExits(trueBlock, falseBlock,\n ifTree, exitType, labelName);\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n if (falseBlock != null) {\n tryMinimizeIfBlockExits(falseBlock, trueBlock,\n ifTree, exitType, labelName);\n }\n }\n if (c == n.getLastChild()) {\n break;\n }\n }\n for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) {\n tryMinimizeExits(c, exitType, labelName);\n if (c == n.getLastChild()) {\n break;\n }\n }\n }\n"}, "reference": " void tryMinimizeExits(Node n, int exitType, String labelName) {\n if (matchingExitNode(n, exitType, labelName)) {\n NodeUtil.removeChild(n.getParent(), n);\n compiler.reportCodeChange();\n return;\n }\n if (n.isIf()) {\n Node ifBlock = n.getFirstChild().getNext();\n tryMinimizeExits(ifBlock, exitType, labelName);\n Node elseBlock = ifBlock.getNext();\n if (elseBlock != null) {\n tryMinimizeExits(elseBlock, exitType, labelName);\n }\n return;\n }\n if (n.isTry()) {\n Node tryBlock = n.getFirstChild();\n tryMinimizeExits(tryBlock, exitType, labelName);\n Node allCatchNodes = NodeUtil.getCatchBlock(n);\n if (NodeUtil.hasCatchHandler(allCatchNodes)) {\n Preconditions.checkState(allCatchNodes.hasOneChild());\n Node catchNode = allCatchNodes.getFirstChild();\n Node catchCodeBlock = catchNode.getLastChild();\n tryMinimizeExits(catchCodeBlock, exitType, labelName);\n }\n }\n if (n.isLabel()) {\n Node labelBlock = n.getLastChild();\n tryMinimizeExits(labelBlock, exitType, labelName);\n }\n if (!n.isBlock() || n.getLastChild() == null) {\n return;\n }\n for (Node c : n.children()) {\n if (c.isIf()) {\n Node ifTree = c;\n Node trueBlock, falseBlock;\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n tryMinimizeIfBlockExits(trueBlock, falseBlock,\n ifTree, exitType, labelName);\n trueBlock = ifTree.getFirstChild().getNext();\n falseBlock = trueBlock.getNext();\n if (falseBlock != null) {\n tryMinimizeIfBlockExits(falseBlock, trueBlock,\n ifTree, exitType, labelName);\n }\n }\n if (c == n.getLastChild()) {\n break;\n }\n }\n for (Node c = n.getLastChild(); c != null; c = n.getLastChild()) {\n tryMinimizeExits(c, exitType, labelName);\n if (c == n.getLastChild()) {\n break;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-126"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-126"}} {"sample_uid": "defects4j_function_repair::Lang-58", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && isDigits(numeric.substring(1))\n && (numeric.charAt(0) == '-' || Character.isDigit(numeric.charAt(0)))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && isDigits(numeric.substring(1))\n && (numeric.charAt(0) == '-' || Character.isDigit(numeric.charAt(0)))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n"}, "reference": " public static Number createNumber(String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n } \n if (str.startsWith(\"--\")) {\n return null;\n }\n if (str.startsWith(\"0x\") || str.startsWith(\"-0x\")) {\n return createInteger(str);\n } \n char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n int decPos = str.indexOf('.');\n int expPos = str.indexOf('e') + str.indexOf('E') + 1;\n if (decPos > -1) {\n if (expPos > -1) {\n if (expPos < decPos) {\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n } else {\n if (expPos > -1) {\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar)) {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n String numeric = str.substring(0, str.length() - 1);\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n case 'd' :\n case 'D' :\n try {\n Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n return createBigDecimal(numeric);\n } catch (NumberFormatException e) {\n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n } else {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) {\n try {\n return createInteger(str);\n } catch (NumberFormatException nfe) {\n }\n try {\n return createLong(str);\n } catch (NumberFormatException nfe) {\n }\n return createBigInteger(str);\n } else {\n boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (NumberFormatException nfe) {\n }\n try {\n Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (NumberFormatException nfe) {\n }\n return createBigDecimal(str);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-58"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-58"}} {"sample_uid": "defects4j_function_repair::Lang-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1) {\n if (chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; \n }\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9')\n && (chars[i] < 'a' || chars[i] > 'f')\n && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n }\n sz--; \n int i = start;\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n if (hasExp) {\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; \n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n return false;\n }\n if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n return foundDigit;\n }\n if (!allowSigns\n && (chars[i] == 'd'\n || chars[i] == 'D'\n || chars[i] == 'f'\n || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l'\n || chars[i] == 'L') {\n return foundDigit && !hasExp;\n }\n return false;\n }\n return !allowSigns && foundDigit;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1) {\n if (chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; \n }\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9')\n && (chars[i] < 'a' || chars[i] > 'f')\n && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n }\n sz--; \n int i = start;\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n if (hasExp) {\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; \n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n return false;\n }\n if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n return foundDigit;\n }\n if (!allowSigns\n && (chars[i] == 'd'\n || chars[i] == 'D'\n || chars[i] == 'f'\n || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l'\n || chars[i] == 'L') {\n return foundDigit && !hasExp;\n }\n return false;\n }\n return !allowSigns && foundDigit;\n }\n"}, "reference": " public static boolean isNumber(String str) {\n if (StringUtils.isEmpty(str)) {\n return false;\n }\n char[] chars = str.toCharArray();\n int sz = chars.length;\n boolean hasExp = false;\n boolean hasDecPoint = false;\n boolean allowSigns = false;\n boolean foundDigit = false;\n int start = (chars[0] == '-') ? 1 : 0;\n if (sz > start + 1) {\n if (chars[start] == '0' && chars[start + 1] == 'x') {\n int i = start + 2;\n if (i == sz) {\n return false; \n }\n for (; i < chars.length; i++) {\n if ((chars[i] < '0' || chars[i] > '9')\n && (chars[i] < 'a' || chars[i] > 'f')\n && (chars[i] < 'A' || chars[i] > 'F')) {\n return false;\n }\n }\n return true;\n }\n }\n sz--; \n int i = start;\n while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n foundDigit = true;\n allowSigns = false;\n } else if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n hasDecPoint = true;\n } else if (chars[i] == 'e' || chars[i] == 'E') {\n if (hasExp) {\n return false;\n }\n if (!foundDigit) {\n return false;\n }\n hasExp = true;\n allowSigns = true;\n } else if (chars[i] == '+' || chars[i] == '-') {\n if (!allowSigns) {\n return false;\n }\n allowSigns = false;\n foundDigit = false; \n } else {\n return false;\n }\n i++;\n }\n if (i < chars.length) {\n if (chars[i] >= '0' && chars[i] <= '9') {\n return true;\n }\n if (chars[i] == 'e' || chars[i] == 'E') {\n return false;\n }\n if (chars[i] == '.') {\n if (hasDecPoint || hasExp) {\n return false;\n }\n return foundDigit;\n }\n if (!allowSigns\n && (chars[i] == 'd'\n || chars[i] == 'D'\n || chars[i] == 'f'\n || chars[i] == 'F')) {\n return foundDigit;\n }\n if (chars[i] == 'l'\n || chars[i] == 'L') {\n return foundDigit && !hasExp && !hasDecPoint;\n }\n return false;\n }\n return !allowSigns && foundDigit;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-24"}} {"sample_uid": "defects4j_function_repair::Csv-10", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException {\n Assertions.notNull(out, \"out\");\n Assertions.notNull(format, \"format\");\n this.out = out;\n this.format = format;\n this.format.validate();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException {\n Assertions.notNull(out, \"out\");\n Assertions.notNull(format, \"format\");\n this.out = out;\n this.format = format;\n this.format.validate();\n }\n"}, "reference": " public CSVPrinter(final Appendable out, final CSVFormat format) throws IOException {\n Assertions.notNull(out, \"out\");\n Assertions.notNull(format, \"format\");\n this.out = out;\n this.format = format;\n this.format.validate();\n if (format.getHeader() != null) {\n this.printRecord((Object[]) format.getHeader());\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-10"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-10"}} {"sample_uid": "defects4j_function_repair::Mockito-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void captureArgumentsFrom(Invocation invocation) {\n if (invocation.getMethod().isVarArgs()) {\n int indexOfVararg = invocation.getRawArguments().length - 1;\n throw new UnsupportedOperationException();\n } else {\n for (int position = 0; position < matchers.size(); position++) {\n Matcher m = matchers.get(position);\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void captureArgumentsFrom(Invocation invocation) {\n if (invocation.getMethod().isVarArgs()) {\n int indexOfVararg = invocation.getRawArguments().length - 1;\n throw new UnsupportedOperationException();\n } else {\n for (int position = 0; position < matchers.size(); position++) {\n Matcher m = matchers.get(position);\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));\n }\n }\n }\n }\n"}, "reference": " public void captureArgumentsFrom(Invocation invocation) {\n if (invocation.getMethod().isVarArgs()) {\n int indexOfVararg = invocation.getRawArguments().length - 1;\n for (int position = 0; position < indexOfVararg; position++) {\n Matcher m = matchers.get(position);\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));\n }\n }\n for (int position = indexOfVararg; position < matchers.size(); position++) {\n Matcher m = matchers.get(position);\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(invocation.getRawArguments()[position - indexOfVararg]);\n }\n }\n } else {\n for (int position = 0; position < matchers.size(); position++) {\n Matcher m = matchers.get(position);\n if (m instanceof CapturesArguments) {\n ((CapturesArguments) m).captureFrom(invocation.getArgumentAt(position, Object.class));\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Mockito-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Mockito-1"}} {"sample_uid": "defects4j_function_repair::Math-7", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MaxCountExceededException, DimensionMismatchException, NoBracketingException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState().clone();\n currentEvent.stepAccepted(eventT, eventY);\n isLastStep = currentEvent.stop();\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n boolean needReset = currentEvent.reset(eventT, eventY);\n if (needReset) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MaxCountExceededException, DimensionMismatchException, NoBracketingException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState().clone();\n currentEvent.stepAccepted(eventT, eventY);\n isLastStep = currentEvent.stop();\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n boolean needReset = currentEvent.reset(eventT, eventY);\n if (needReset) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n for (final EventState remaining : occuringEvents) {\n remaining.stepAccepted(eventT, eventY);\n }\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n"}, "reference": " protected double acceptStep(final AbstractStepInterpolator interpolator,\n final double[] y, final double[] yDot, final double tEnd)\n throws MaxCountExceededException, DimensionMismatchException, NoBracketingException {\n double previousT = interpolator.getGlobalPreviousTime();\n final double currentT = interpolator.getGlobalCurrentTime();\n if (! statesInitialized) {\n for (EventState state : eventsStates) {\n state.reinitializeBegin(interpolator);\n }\n statesInitialized = true;\n }\n final int orderingSign = interpolator.isForward() ? +1 : -1;\n SortedSet occuringEvents = new TreeSet(new Comparator() {\n public int compare(EventState es0, EventState es1) {\n return orderingSign * Double.compare(es0.getEventTime(), es1.getEventTime());\n }\n });\n for (final EventState state : eventsStates) {\n if (state.evaluateStep(interpolator)) {\n occuringEvents.add(state);\n }\n }\n while (!occuringEvents.isEmpty()) {\n final Iterator iterator = occuringEvents.iterator();\n final EventState currentEvent = iterator.next();\n iterator.remove();\n final double eventT = currentEvent.getEventTime();\n interpolator.setSoftPreviousTime(previousT);\n interpolator.setSoftCurrentTime(eventT);\n interpolator.setInterpolatedTime(eventT);\n final double[] eventY = interpolator.getInterpolatedState().clone();\n for (final EventState state : eventsStates) {\n state.stepAccepted(eventT, eventY);\n isLastStep = isLastStep || state.stop();\n }\n for (final StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n if (isLastStep) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n return eventT;\n }\n boolean needReset = false;\n for (final EventState state : eventsStates) {\n needReset = needReset || state.reset(eventT, eventY);\n }\n if (needReset) {\n System.arraycopy(eventY, 0, y, 0, y.length);\n computeDerivatives(eventT, y, yDot);\n resetOccurred = true;\n return eventT;\n }\n previousT = eventT;\n interpolator.setSoftPreviousTime(eventT);\n interpolator.setSoftCurrentTime(currentT);\n if (currentEvent.evaluateStep(interpolator)) {\n occuringEvents.add(currentEvent);\n }\n }\n interpolator.setInterpolatedTime(currentT);\n final double[] currentY = interpolator.getInterpolatedState();\n for (final EventState state : eventsStates) {\n state.stepAccepted(currentT, currentY);\n isLastStep = isLastStep || state.stop();\n }\n isLastStep = isLastStep || Precision.equals(currentT, tEnd, 1);\n for (StepHandler handler : stepHandlers) {\n handler.handleStep(interpolator, isLastStep);\n }\n return currentT;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-7"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-7"}} {"sample_uid": "defects4j_function_repair::Closure-114", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {\n Node nameNode = n.getFirstChild();\n Node parent = n.getParent();\n NameInformation ns = createNameInformation(t, nameNode);\n if (ns != null) {\n if (parent.isFor() && !NodeUtil.isForIn(parent)) {\n if (parent.getFirstChild().getNext() != n) {\n recordDepScope(recordNode, ns);\n } else {\n recordDepScope(nameNode, ns);\n }\n } else {\n recordDepScope(recordNode, ns);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {\n Node nameNode = n.getFirstChild();\n Node parent = n.getParent();\n NameInformation ns = createNameInformation(t, nameNode);\n if (ns != null) {\n if (parent.isFor() && !NodeUtil.isForIn(parent)) {\n if (parent.getFirstChild().getNext() != n) {\n recordDepScope(recordNode, ns);\n } else {\n recordDepScope(nameNode, ns);\n }\n } else {\n recordDepScope(recordNode, ns);\n }\n }\n }\n"}, "reference": " private void recordAssignment(NodeTraversal t, Node n, Node recordNode) {\n Node nameNode = n.getFirstChild();\n Node parent = n.getParent();\n NameInformation ns = createNameInformation(t, nameNode);\n if (ns != null) {\n if (parent.isFor() && !NodeUtil.isForIn(parent)) {\n if (parent.getFirstChild().getNext() != n) {\n recordDepScope(recordNode, ns);\n } else {\n recordDepScope(nameNode, ns);\n }\n } else if (!(parent.isCall() && parent.getFirstChild() == n)) {\n recordDepScope(recordNode, ns);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-114"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-114"}} {"sample_uid": "defects4j_function_repair::JacksonCore-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void feedInput(byte[] buf, int start, int end) throws IOException\n {\n if (_inputPtr < _inputEnd) {\n _reportError(\"Still have %d undecoded bytes, should not call 'feedInput'\", _inputEnd - _inputPtr);\n }\n if (end < start) {\n _reportError(\"Input end (%d) may not be before start (%d)\", end, start);\n }\n if (_endOfInput) {\n _reportError(\"Already closed, can not feed more input\");\n }\n _currInputProcessed += _origBufferLen;\n _currInputRowStart = start - (_inputEnd - _currInputRowStart);\n _inputBuffer = buf;\n _inputPtr = start;\n _inputEnd = end;\n _origBufferLen = end - start;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void feedInput(byte[] buf, int start, int end) throws IOException\n {\n if (_inputPtr < _inputEnd) {\n _reportError(\"Still have %d undecoded bytes, should not call 'feedInput'\", _inputEnd - _inputPtr);\n }\n if (end < start) {\n _reportError(\"Input end (%d) may not be before start (%d)\", end, start);\n }\n if (_endOfInput) {\n _reportError(\"Already closed, can not feed more input\");\n }\n _currInputProcessed += _origBufferLen;\n _currInputRowStart = start - (_inputEnd - _currInputRowStart);\n _inputBuffer = buf;\n _inputPtr = start;\n _inputEnd = end;\n _origBufferLen = end - start;\n }\n"}, "reference": " public void feedInput(byte[] buf, int start, int end) throws IOException\n {\n if (_inputPtr < _inputEnd) {\n _reportError(\"Still have %d undecoded bytes, should not call 'feedInput'\", _inputEnd - _inputPtr);\n }\n if (end < start) {\n _reportError(\"Input end (%d) may not be before start (%d)\", end, start);\n }\n if (_endOfInput) {\n _reportError(\"Already closed, can not feed more input\");\n }\n _currInputProcessed += _origBufferLen;\n _currInputRowStart = start - (_inputEnd - _currInputRowStart);\n _currBufferStart = start;\n _inputBuffer = buf;\n _inputPtr = start;\n _inputEnd = end;\n _origBufferLen = end - start;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-26"}} {"sample_uid": "defects4j_function_repair::Math-43", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void addValue(double value) {\n sumImpl.increment(value);\n sumsqImpl.increment(value);\n minImpl.increment(value);\n maxImpl.increment(value);\n sumLogImpl.increment(value);\n secondMoment.increment(value);\n if (!(meanImpl instanceof Mean)) {\n meanImpl.increment(value);\n }\n if (!(varianceImpl instanceof Variance)) {\n varianceImpl.increment(value);\n }\n if (!(geoMeanImpl instanceof GeometricMean)) {\n geoMeanImpl.increment(value);\n }\n n++;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void addValue(double value) {\n sumImpl.increment(value);\n sumsqImpl.increment(value);\n minImpl.increment(value);\n maxImpl.increment(value);\n sumLogImpl.increment(value);\n secondMoment.increment(value);\n if (!(meanImpl instanceof Mean)) {\n meanImpl.increment(value);\n }\n if (!(varianceImpl instanceof Variance)) {\n varianceImpl.increment(value);\n }\n if (!(geoMeanImpl instanceof GeometricMean)) {\n geoMeanImpl.increment(value);\n }\n n++;\n }\n"}, "reference": " public void addValue(double value) {\n sumImpl.increment(value);\n sumsqImpl.increment(value);\n minImpl.increment(value);\n maxImpl.increment(value);\n sumLogImpl.increment(value);\n secondMoment.increment(value);\n if (meanImpl != mean) {\n meanImpl.increment(value);\n }\n if (varianceImpl != variance) {\n varianceImpl.increment(value);\n }\n if (geoMeanImpl != geoMean) {\n geoMeanImpl.increment(value);\n }\n n++;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-43"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-43"}} {"sample_uid": "defects4j_function_repair::Closure-11", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void visitGetProp(NodeTraversal t, Node n, Node parent) {\n Node property = n.getLastChild();\n Node objNode = n.getFirstChild();\n JSType childType = getJSType(objNode);\n if (childType.isDict()) {\n report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, \"'.'\", \"dict\");\n } else if (n.getJSType() != null && parent.isAssign()) {\n return;\n } else if (validator.expectNotNullOrUndefined(t, n, childType,\n \"No properties on this expression\", getNativeType(OBJECT_TYPE))) {\n checkPropertyAccess(childType, property.getString(), t, n);\n }\n ensureTyped(t, n);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void visitGetProp(NodeTraversal t, Node n, Node parent) {\n Node property = n.getLastChild();\n Node objNode = n.getFirstChild();\n JSType childType = getJSType(objNode);\n if (childType.isDict()) {\n report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, \"'.'\", \"dict\");\n } else if (n.getJSType() != null && parent.isAssign()) {\n return;\n } else if (validator.expectNotNullOrUndefined(t, n, childType,\n \"No properties on this expression\", getNativeType(OBJECT_TYPE))) {\n checkPropertyAccess(childType, property.getString(), t, n);\n }\n ensureTyped(t, n);\n }\n"}, "reference": " private void visitGetProp(NodeTraversal t, Node n, Node parent) {\n Node property = n.getLastChild();\n Node objNode = n.getFirstChild();\n JSType childType = getJSType(objNode);\n if (childType.isDict()) {\n report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, \"'.'\", \"dict\");\n } else if (validator.expectNotNullOrUndefined(t, n, childType,\n \"No properties on this expression\", getNativeType(OBJECT_TYPE))) {\n checkPropertyAccess(childType, property.getString(), t, n);\n }\n ensureTyped(t, n);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-11"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-11"}} {"sample_uid": "defects4j_function_repair::Lang-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String format(Date date) {\n Calendar c = new GregorianCalendar(mTimeZone);\n c.setTime(date);\n return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String format(Date date) {\n Calendar c = new GregorianCalendar(mTimeZone);\n c.setTime(date);\n return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();\n }\n"}, "reference": " public String format(Date date) {\n Calendar c = new GregorianCalendar(mTimeZone, mLocale);\n c.setTime(date);\n return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-26"}} {"sample_uid": "defects4j_function_repair::Codec-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private char getMappingCode(final String str, final int index) {\n final char mappedChar = this.map(str.charAt(index));\n if (index > 1 && mappedChar != '0') {\n final char hwChar = str.charAt(index - 1);\n if ('H' == hwChar || 'W' == hwChar) {\n final char preHWChar = str.charAt(index - 2);\n final char firstCode = this.map(preHWChar);\n if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) {\n return 0;\n }\n }\n }\n return mappedChar;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private char getMappingCode(final String str, final int index) {\n final char mappedChar = this.map(str.charAt(index));\n if (index > 1 && mappedChar != '0') {\n final char hwChar = str.charAt(index - 1);\n if ('H' == hwChar || 'W' == hwChar) {\n final char preHWChar = str.charAt(index - 2);\n final char firstCode = this.map(preHWChar);\n if (firstCode == mappedChar || 'H' == preHWChar || 'W' == preHWChar) {\n return 0;\n }\n }\n }\n return mappedChar;\n }\n"}, "reference": " private char getMappingCode(final String str, final int index) {\n final char mappedChar = this.map(str.charAt(index));\n if (index > 1 && mappedChar != '0') {\n for (int i=index-1 ; i>=0 ; i--) {\n final char prevChar = str.charAt(i);\n if (this.map(prevChar)==mappedChar) {\n return 0;\n }\n if ('H'!=prevChar && 'W'!=prevChar) {\n break;\n }\n }\n }\n return mappedChar;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Codec-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Codec-15"}} {"sample_uid": "defects4j_function_repair::Math-84", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void iterateSimplex(final Comparator comparator)\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n while (true) {\n incrementIterationsCounter();\n final RealPointValuePair[] original = simplex;\n final RealPointValuePair best = original[0];\n final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);\n if (comparator.compare(reflected, best) < 0) {\n final RealPointValuePair[] reflectedSimplex = simplex;\n final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);\n if (comparator.compare(reflected, expanded) <= 0) {\n simplex = reflectedSimplex;\n }\n return;\n }\n final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);\n if (comparator.compare(contracted, best) < 0) {\n return;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void iterateSimplex(final Comparator comparator)\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n while (true) {\n incrementIterationsCounter();\n final RealPointValuePair[] original = simplex;\n final RealPointValuePair best = original[0];\n final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);\n if (comparator.compare(reflected, best) < 0) {\n final RealPointValuePair[] reflectedSimplex = simplex;\n final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);\n if (comparator.compare(reflected, expanded) <= 0) {\n simplex = reflectedSimplex;\n }\n return;\n }\n final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);\n if (comparator.compare(contracted, best) < 0) {\n return;\n }\n }\n }\n"}, "reference": " protected void iterateSimplex(final Comparator comparator)\n throws FunctionEvaluationException, OptimizationException, IllegalArgumentException {\n final RealConvergenceChecker checker = getConvergenceChecker();\n while (true) {\n incrementIterationsCounter();\n final RealPointValuePair[] original = simplex;\n final RealPointValuePair best = original[0];\n final RealPointValuePair reflected = evaluateNewSimplex(original, 1.0, comparator);\n if (comparator.compare(reflected, best) < 0) {\n final RealPointValuePair[] reflectedSimplex = simplex;\n final RealPointValuePair expanded = evaluateNewSimplex(original, khi, comparator);\n if (comparator.compare(reflected, expanded) <= 0) {\n simplex = reflectedSimplex;\n }\n return;\n }\n final RealPointValuePair contracted = evaluateNewSimplex(original, gamma, comparator);\n if (comparator.compare(contracted, best) < 0) {\n return;\n }\n final int iter = getIterations();\n boolean converged = true;\n for (int i = 0; i < simplex.length; ++i) {\n converged &= checker.converged(iter, original[i], simplex[i]);\n }\n if (converged) {\n return;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-84"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-84"}} {"sample_uid": "defects4j_function_repair::Lang-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean equals(CharSequence cs1, CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n return cs1.equals(cs2);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean equals(CharSequence cs1, CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n return cs1.equals(cs2);\n }\n"}, "reference": " public static boolean equals(CharSequence cs1, CharSequence cs2) {\n if (cs1 == cs2) {\n return true;\n }\n if (cs1 == null || cs2 == null) {\n return false;\n }\n if (cs1 instanceof String && cs2 instanceof String) {\n return cs1.equals(cs2);\n }\n return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-14"}} {"sample_uid": "defects4j_function_repair::Chart-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Object clone() throws CloneNotSupportedException {\n Object clone = createCopy(0, getItemCount() - 1);\n return clone;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Object clone() throws CloneNotSupportedException {\n Object clone = createCopy(0, getItemCount() - 1);\n return clone;\n }\n"}, "reference": " public Object clone() throws CloneNotSupportedException {\n TimeSeries clone = (TimeSeries) super.clone();\n clone.data = (List) ObjectUtilities.deepClone(this.data);\n return clone;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-17"}} {"sample_uid": "defects4j_function_repair::Jsoup-85", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Attribute(String key, String val, Attributes parent) {\n Validate.notNull(key);\n this.key = key.trim();\n Validate.notEmpty(key); \n this.val = val;\n this.parent = parent;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Attribute(String key, String val, Attributes parent) {\n Validate.notNull(key);\n this.key = key.trim();\n Validate.notEmpty(key); \n this.val = val;\n this.parent = parent;\n }\n"}, "reference": " public Attribute(String key, String val, Attributes parent) {\n Validate.notNull(key);\n key = key.trim();\n Validate.notEmpty(key); \n this.key = key;\n this.val = val;\n this.parent = parent;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-85"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-85"}} {"sample_uid": "defects4j_function_repair::Math-94", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static int gcd(int u, int v) {\n if (u * v == 0) {\n return (Math.abs(u) + Math.abs(v));\n }\n if (u > 0) {\n u = -u;\n } \n if (v > 0) {\n v = -v;\n } \n int k = 0;\n while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { \n u /= 2;\n v /= 2;\n k++; \n }\n if (k == 31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u & 1) == 1) ? v : -(u / 2);\n do {\n while ((t & 1) == 0) { \n t /= 2; \n }\n if (t > 0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u) / 2;\n } while (t != 0);\n return -u * (1 << k); \n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static int gcd(int u, int v) {\n if (u * v == 0) {\n return (Math.abs(u) + Math.abs(v));\n }\n if (u > 0) {\n u = -u;\n } \n if (v > 0) {\n v = -v;\n } \n int k = 0;\n while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { \n u /= 2;\n v /= 2;\n k++; \n }\n if (k == 31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u & 1) == 1) ? v : -(u / 2);\n do {\n while ((t & 1) == 0) { \n t /= 2; \n }\n if (t > 0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u) / 2;\n } while (t != 0);\n return -u * (1 << k); \n }\n"}, "reference": " public static int gcd(int u, int v) {\n if ((u == 0) || (v == 0)) {\n return (Math.abs(u) + Math.abs(v));\n }\n if (u > 0) {\n u = -u;\n } \n if (v > 0) {\n v = -v;\n } \n int k = 0;\n while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { \n u /= 2;\n v /= 2;\n k++; \n }\n if (k == 31) {\n throw new ArithmeticException(\"overflow: gcd is 2^31\");\n }\n int t = ((u & 1) == 1) ? v : -(u / 2);\n do {\n while ((t & 1) == 0) { \n t /= 2; \n }\n if (t > 0) {\n u = -t;\n } else {\n v = t;\n }\n t = (v - u) / 2;\n } while (t != 0);\n return -u * (1 << k); \n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-94"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-94"}} {"sample_uid": "defects4j_function_repair::Compress-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n if (start == end) {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, trailer));\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n if (start == end) {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, trailer));\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n"}, "reference": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-27"}} {"sample_uid": "defects4j_function_repair::Closure-58", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void computeGenKill(Node n, BitSet gen, BitSet kill,\n boolean conditional) {\n switch (n.getType()) {\n case Token.SCRIPT:\n case Token.BLOCK:\n case Token.FUNCTION:\n return;\n case Token.WHILE:\n case Token.DO:\n case Token.IF:\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n return;\n case Token.FOR:\n if (!NodeUtil.isForIn(n)) {\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n } else {\n Node lhs = n.getFirstChild();\n Node rhs = lhs.getNext();\n if (NodeUtil.isVar(lhs)) {\n lhs = lhs.getLastChild();\n }\n addToSetIfLocal(lhs, kill);\n addToSetIfLocal(lhs, gen);\n computeGenKill(rhs, gen, kill, conditional);\n }\n return;\n case Token.VAR:\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (c.hasChildren()) {\n computeGenKill(c.getFirstChild(), gen, kill, conditional);\n if (!conditional) {\n addToSetIfLocal(c, kill);\n }\n }\n }\n return;\n case Token.AND:\n case Token.OR:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.HOOK:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getFirstChild().getNext(), gen, kill, true);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.NAME:\n if (isArgumentsName(n)) {\n markAllParametersEscaped();\n } else {\n addToSetIfLocal(n, gen);\n }\n return;\n default:\n if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) {\n Node lhs = n.getFirstChild();\n if (!conditional) {\n addToSetIfLocal(lhs, kill);\n }\n if (!NodeUtil.isAssign(n)) {\n addToSetIfLocal(lhs, gen);\n }\n computeGenKill(lhs.getNext(), gen, kill, conditional);\n } else {\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n computeGenKill(c, gen, kill, conditional);\n }\n }\n return;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void computeGenKill(Node n, BitSet gen, BitSet kill,\n boolean conditional) {\n switch (n.getType()) {\n case Token.SCRIPT:\n case Token.BLOCK:\n case Token.FUNCTION:\n return;\n case Token.WHILE:\n case Token.DO:\n case Token.IF:\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n return;\n case Token.FOR:\n if (!NodeUtil.isForIn(n)) {\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n } else {\n Node lhs = n.getFirstChild();\n Node rhs = lhs.getNext();\n if (NodeUtil.isVar(lhs)) {\n lhs = lhs.getLastChild();\n }\n addToSetIfLocal(lhs, kill);\n addToSetIfLocal(lhs, gen);\n computeGenKill(rhs, gen, kill, conditional);\n }\n return;\n case Token.VAR:\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (c.hasChildren()) {\n computeGenKill(c.getFirstChild(), gen, kill, conditional);\n if (!conditional) {\n addToSetIfLocal(c, kill);\n }\n }\n }\n return;\n case Token.AND:\n case Token.OR:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.HOOK:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getFirstChild().getNext(), gen, kill, true);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.NAME:\n if (isArgumentsName(n)) {\n markAllParametersEscaped();\n } else {\n addToSetIfLocal(n, gen);\n }\n return;\n default:\n if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) {\n Node lhs = n.getFirstChild();\n if (!conditional) {\n addToSetIfLocal(lhs, kill);\n }\n if (!NodeUtil.isAssign(n)) {\n addToSetIfLocal(lhs, gen);\n }\n computeGenKill(lhs.getNext(), gen, kill, conditional);\n } else {\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n computeGenKill(c, gen, kill, conditional);\n }\n }\n return;\n }\n }\n"}, "reference": " private void computeGenKill(Node n, BitSet gen, BitSet kill,\n boolean conditional) {\n switch (n.getType()) {\n case Token.SCRIPT:\n case Token.BLOCK:\n case Token.FUNCTION:\n return;\n case Token.WHILE:\n case Token.DO:\n case Token.IF:\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n return;\n case Token.FOR:\n if (!NodeUtil.isForIn(n)) {\n computeGenKill(NodeUtil.getConditionExpression(n), gen, kill,\n conditional);\n } else {\n Node lhs = n.getFirstChild();\n Node rhs = lhs.getNext();\n if (NodeUtil.isVar(lhs)) {\n lhs = lhs.getLastChild();\n }\n if (NodeUtil.isName(lhs)) {\n addToSetIfLocal(lhs, kill);\n addToSetIfLocal(lhs, gen);\n } else {\n computeGenKill(lhs, gen, kill, conditional);\n }\n computeGenKill(rhs, gen, kill, conditional);\n }\n return;\n case Token.VAR:\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n if (c.hasChildren()) {\n computeGenKill(c.getFirstChild(), gen, kill, conditional);\n if (!conditional) {\n addToSetIfLocal(c, kill);\n }\n }\n }\n return;\n case Token.AND:\n case Token.OR:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.HOOK:\n computeGenKill(n.getFirstChild(), gen, kill, conditional);\n computeGenKill(n.getFirstChild().getNext(), gen, kill, true);\n computeGenKill(n.getLastChild(), gen, kill, true);\n return;\n case Token.NAME:\n if (isArgumentsName(n)) {\n markAllParametersEscaped();\n } else {\n addToSetIfLocal(n, gen);\n }\n return;\n default:\n if (NodeUtil.isAssignmentOp(n) && NodeUtil.isName(n.getFirstChild())) {\n Node lhs = n.getFirstChild();\n if (!conditional) {\n addToSetIfLocal(lhs, kill);\n }\n if (!NodeUtil.isAssign(n)) {\n addToSetIfLocal(lhs, gen);\n }\n computeGenKill(lhs.getNext(), gen, kill, conditional);\n } else {\n for (Node c = n.getFirstChild(); c != null; c = c.getNext()) {\n computeGenKill(c, gen, kill, conditional);\n }\n }\n return;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-58"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-58"}} {"sample_uid": "defects4j_function_repair::Lang-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16) { \n return createBigInteger(str);\n }\n if (hexDigits > 8) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n if(numDecimals <= 7){\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n if(numDecimals <= 16){\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16) { \n return createBigInteger(str);\n }\n if (hexDigits > 8) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n if(numDecimals <= 7){\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n if(numDecimals <= 16){\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n"}, "reference": " public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n char firstSigDigit = 0; \n for(int i = pfxLen; i < str.length(); i++) {\n firstSigDigit = str.charAt(i);\n if (firstSigDigit == '0') { \n pfxLen++;\n } else {\n break;\n }\n }\n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16 || (hexDigits == 16 && firstSigDigit > '7')) { \n return createBigInteger(str);\n }\n if (hexDigits > 8 || (hexDigits == 8 && firstSigDigit > '7')) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n if(numDecimals <= 7){\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n if(numDecimals <= 16){\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-1"}} {"sample_uid": "defects4j_function_repair::Collections-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Object readResolve() {\n calculateHashCode(keys);\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Object readResolve() {\n calculateHashCode(keys);\n return this;\n }\n"}, "reference": " protected Object readResolve() {\n calculateHashCode(keys);\n return this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Collections-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Collections-26"}} {"sample_uid": "defects4j_function_repair::JacksonCore-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonToken nextToken() throws IOException\n {\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n return (_currToken = t);\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonToken nextToken() throws IOException\n {\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n return (_currToken = t);\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n"}, "reference": " public JsonToken nextToken() throws IOException\n {\n \tif(!_allowMultipleMatches && _currToken != null && _exposedContext == null){\n \t\tif((_currToken.isStructEnd() && _headContext.isStartHandled()) ){\n \t\t\treturn (_currToken = null);\n \t\t}\n \t\telse if(_currToken.isScalarValue() && !_headContext.isStartHandled() && !_includePath \n \t\t\t\t&& _itemFilter == TokenFilter.INCLUDE_ALL) {\n \t\t\treturn (_currToken = null);\n \t\t}\n \t}\n TokenFilterContext ctxt = _exposedContext;\n if (ctxt != null) {\n while (true) {\n JsonToken t = ctxt.nextTokenToRead();\n if (t != null) {\n _currToken = t;\n return t;\n }\n if (ctxt == _headContext) {\n _exposedContext = null;\n if (ctxt.inArray()) {\n t = delegate.getCurrentToken();\n _currToken = t;\n return t;\n }\n break;\n }\n ctxt = _headContext.findChildOf(ctxt);\n _exposedContext = ctxt;\n if (ctxt == null) { \n throw _constructError(\"Unexpected problem: chain of filtered context broken\");\n }\n }\n }\n JsonToken t = delegate.nextToken();\n if (t == null) {\n return (_currToken = t);\n }\n TokenFilter f;\n switch (t.id()) {\n case ID_START_ARRAY:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartArray();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildArrayContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildArrayContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_START_OBJECT:\n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n if (f == null) { \n delegate.skipChildren();\n break;\n }\n f = _headContext.checkValue(f);\n if (f == null) {\n delegate.skipChildren();\n break;\n }\n if (f != TokenFilter.INCLUDE_ALL) {\n f = f.filterStartObject();\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n _headContext = _headContext.createChildObjectContext(f, true);\n return (_currToken = t);\n }\n _headContext = _headContext.createChildObjectContext(f, false);\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n case ID_END_ARRAY:\n case ID_END_OBJECT:\n {\n boolean returnEnd = _headContext.isStartHandled();\n f = _headContext.getFilter();\n if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {\n f.filterFinishArray();\n }\n _headContext = _headContext.getParent();\n _itemFilter = _headContext.getFilter();\n if (returnEnd) {\n return (_currToken = t);\n }\n }\n break;\n case ID_FIELD_NAME:\n {\n final String name = delegate.getCurrentName();\n f = _headContext.setFieldName(name);\n if (f == TokenFilter.INCLUDE_ALL) {\n _itemFilter = f;\n if (!_includePath) {\n if (_includeImmediateParent && !_headContext.isStartHandled()) {\n t = _headContext.nextTokenToRead(); \n _exposedContext = _headContext;\n }\n }\n return (_currToken = t);\n }\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n f = f.includeProperty(name);\n if (f == null) {\n delegate.nextToken();\n delegate.skipChildren();\n break;\n }\n _itemFilter = f;\n if (f == TokenFilter.INCLUDE_ALL) {\n if (_includePath) {\n return (_currToken = t);\n }\n }\n if (_includePath) {\n t = _nextTokenWithBuffering(_headContext);\n if (t != null) {\n _currToken = t;\n return t;\n }\n }\n break;\n }\n default: \n f = _itemFilter;\n if (f == TokenFilter.INCLUDE_ALL) {\n return (_currToken = t);\n }\n if (f != null) {\n f = _headContext.checkValue(f);\n if ((f == TokenFilter.INCLUDE_ALL)\n || ((f != null) && f.includeValue(delegate))) {\n return (_currToken = t);\n }\n }\n break;\n }\n return _nextToken2();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-15"}} {"sample_uid": "defects4j_function_repair::Gson-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n @Override public void skipValue() throws IOException {\n if (peek() == JsonToken.NAME) {\n nextName();\n pathNames[stackSize - 2] = \"null\";\n } else {\n popStack();\n pathNames[stackSize - 1] = \"null\";\n }\n pathIndices[stackSize - 1]++;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " @Override public void skipValue() throws IOException {\n if (peek() == JsonToken.NAME) {\n nextName();\n pathNames[stackSize - 2] = \"null\";\n } else {\n popStack();\n pathNames[stackSize - 1] = \"null\";\n }\n pathIndices[stackSize - 1]++;\n }\n"}, "reference": " @Override public void skipValue() throws IOException {\n if (peek() == JsonToken.NAME) {\n nextName();\n pathNames[stackSize - 2] = \"null\";\n } else {\n popStack();\n if (stackSize > 0) {\n pathNames[stackSize - 1] = \"null\";\n }\n }\n if (stackSize > 0) {\n pathIndices[stackSize - 1]++;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-12"}} {"sample_uid": "defects4j_function_repair::Math-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return best(current, previous, isMinim);\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return\n best(current,\n previous,\n isMinim);\n }\n ++iter;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return best(current, previous, isMinim);\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return\n best(current,\n previous,\n isMinim);\n }\n ++iter;\n }\n }\n"}, "reference": " protected UnivariatePointValuePair doOptimize() {\n final boolean isMinim = getGoalType() == GoalType.MINIMIZE;\n final double lo = getMin();\n final double mid = getStartValue();\n final double hi = getMax();\n final ConvergenceChecker checker\n = getConvergenceChecker();\n double a;\n double b;\n if (lo < hi) {\n a = lo;\n b = hi;\n } else {\n a = hi;\n b = lo;\n }\n double x = mid;\n double v = x;\n double w = x;\n double d = 0;\n double e = 0;\n double fx = computeObjectiveValue(x);\n if (!isMinim) {\n fx = -fx;\n }\n double fv = fx;\n double fw = fx;\n UnivariatePointValuePair previous = null;\n UnivariatePointValuePair current\n = new UnivariatePointValuePair(x, isMinim ? fx : -fx);\n UnivariatePointValuePair best = current;\n int iter = 0;\n while (true) {\n final double m = 0.5 * (a + b);\n final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold;\n final double tol2 = 2 * tol1;\n final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a);\n if (!stop) {\n double p = 0;\n double q = 0;\n double r = 0;\n double u = 0;\n if (FastMath.abs(e) > tol1) { \n r = (x - w) * (fx - fv);\n q = (x - v) * (fx - fw);\n p = (x - v) * q - (x - w) * r;\n q = 2 * (q - r);\n if (q > 0) {\n p = -p;\n } else {\n q = -q;\n }\n r = e;\n e = d;\n if (p > q * (a - x) &&\n p < q * (b - x) &&\n FastMath.abs(p) < FastMath.abs(0.5 * q * r)) {\n d = p / q;\n u = x + d;\n if (u - a < tol2 || b - u < tol2) {\n if (x <= m) {\n d = tol1;\n } else {\n d = -tol1;\n }\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n } else {\n if (x < m) {\n e = b - x;\n } else {\n e = a - x;\n }\n d = GOLDEN_SECTION * e;\n }\n if (FastMath.abs(d) < tol1) {\n if (d >= 0) {\n u = x + tol1;\n } else {\n u = x - tol1;\n }\n } else {\n u = x + d;\n }\n double fu = computeObjectiveValue(u);\n if (!isMinim) {\n fu = -fu;\n }\n previous = current;\n current = new UnivariatePointValuePair(u, isMinim ? fu : -fu);\n best = best(best,\n best(current,\n previous,\n isMinim),\n isMinim);\n if (checker != null) {\n if (checker.converged(iter, previous, current)) {\n return best;\n }\n }\n if (fu <= fx) {\n if (u < x) {\n b = x;\n } else {\n a = x;\n }\n v = w;\n fv = fw;\n w = x;\n fw = fx;\n x = u;\n fx = fu;\n } else {\n if (u < x) {\n a = u;\n } else {\n b = u;\n }\n if (fu <= fw ||\n Precision.equals(w, x)) {\n v = w;\n fv = fw;\n w = u;\n fw = fu;\n } else if (fu <= fv ||\n Precision.equals(v, x) ||\n Precision.equals(v, w)) {\n v = u;\n fv = fu;\n }\n }\n } else { \n return best(best,\n best(current,\n previous,\n isMinim),\n isMinim);\n }\n ++iter;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-23"}} {"sample_uid": "defects4j_function_repair::Math-55", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Vector3D crossProduct(final Vector3D v1, final Vector3D v2) {\n return new Vector3D(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Vector3D crossProduct(final Vector3D v1, final Vector3D v2) {\n return new Vector3D(v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x);\n }\n"}, "reference": " public static Vector3D crossProduct(final Vector3D v1, final Vector3D v2) {\n final double n1 = v1.getNormSq();\n final double n2 = v2.getNormSq();\n if ((n1 * n2) < MathUtils.SAFE_MIN) {\n return ZERO;\n }\n final int deltaExp = (FastMath.getExponent(n1) - FastMath.getExponent(n2)) / 4;\n final double x1 = FastMath.scalb(v1.x, -deltaExp);\n final double y1 = FastMath.scalb(v1.y, -deltaExp);\n final double z1 = FastMath.scalb(v1.z, -deltaExp);\n final double x2 = FastMath.scalb(v2.x, deltaExp);\n final double y2 = FastMath.scalb(v2.y, deltaExp);\n final double z2 = FastMath.scalb(v2.z, deltaExp);\n final double ratio = (x1 * x2 + y1 * y2 + z1 * z2) / FastMath.scalb(n2, 2 * deltaExp);\n final double rho = FastMath.rint(256 * ratio) / 256;\n final double x3 = x1 - rho * x2;\n final double y3 = y1 - rho * y2;\n final double z3 = z1 - rho * z2;\n return new Vector3D(y3 * z2 - z3 * y2, z3 * x2 - x3 * z2, x3 * y2 - y3 * x2);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-55"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-55"}} {"sample_uid": "defects4j_function_repair::Gson-16", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static Type resolve(Type context, Class contextRawType, Type toResolve,\n Collection visitedTypeVariables) {\n while (true) {\n if (toResolve instanceof TypeVariable) {\n TypeVariable typeVariable = (TypeVariable) toResolve;\n toResolve = resolveTypeVariable(context, contextRawType, typeVariable);\n if (toResolve == typeVariable) {\n return toResolve;\n }\n } else if (toResolve instanceof Class && ((Class) toResolve).isArray()) {\n Class original = (Class) toResolve;\n Type componentType = original.getComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof GenericArrayType) {\n GenericArrayType original = (GenericArrayType) toResolve;\n Type componentType = original.getGenericComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof ParameterizedType) {\n ParameterizedType original = (ParameterizedType) toResolve;\n Type ownerType = original.getOwnerType();\n Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);\n boolean changed = newOwnerType != ownerType;\n Type[] args = original.getActualTypeArguments();\n for (int t = 0, length = args.length; t < length; t++) {\n Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);\n if (resolvedTypeArgument != args[t]) {\n if (!changed) {\n args = args.clone();\n changed = true;\n }\n args[t] = resolvedTypeArgument;\n }\n }\n return changed\n ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)\n : original;\n } else if (toResolve instanceof WildcardType) {\n WildcardType original = (WildcardType) toResolve;\n Type[] originalLowerBound = original.getLowerBounds();\n Type[] originalUpperBound = original.getUpperBounds();\n if (originalLowerBound.length == 1) {\n Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);\n if (lowerBound != originalLowerBound[0]) {\n return supertypeOf(lowerBound);\n }\n } else if (originalUpperBound.length == 1) {\n Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);\n if (upperBound != originalUpperBound[0]) {\n return subtypeOf(upperBound);\n }\n }\n return original;\n } else {\n return toResolve;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static Type resolve(Type context, Class contextRawType, Type toResolve,\n Collection visitedTypeVariables) {\n while (true) {\n if (toResolve instanceof TypeVariable) {\n TypeVariable typeVariable = (TypeVariable) toResolve;\n toResolve = resolveTypeVariable(context, contextRawType, typeVariable);\n if (toResolve == typeVariable) {\n return toResolve;\n }\n } else if (toResolve instanceof Class && ((Class) toResolve).isArray()) {\n Class original = (Class) toResolve;\n Type componentType = original.getComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof GenericArrayType) {\n GenericArrayType original = (GenericArrayType) toResolve;\n Type componentType = original.getGenericComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof ParameterizedType) {\n ParameterizedType original = (ParameterizedType) toResolve;\n Type ownerType = original.getOwnerType();\n Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);\n boolean changed = newOwnerType != ownerType;\n Type[] args = original.getActualTypeArguments();\n for (int t = 0, length = args.length; t < length; t++) {\n Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);\n if (resolvedTypeArgument != args[t]) {\n if (!changed) {\n args = args.clone();\n changed = true;\n }\n args[t] = resolvedTypeArgument;\n }\n }\n return changed\n ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)\n : original;\n } else if (toResolve instanceof WildcardType) {\n WildcardType original = (WildcardType) toResolve;\n Type[] originalLowerBound = original.getLowerBounds();\n Type[] originalUpperBound = original.getUpperBounds();\n if (originalLowerBound.length == 1) {\n Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);\n if (lowerBound != originalLowerBound[0]) {\n return supertypeOf(lowerBound);\n }\n } else if (originalUpperBound.length == 1) {\n Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);\n if (upperBound != originalUpperBound[0]) {\n return subtypeOf(upperBound);\n }\n }\n return original;\n } else {\n return toResolve;\n }\n }\n }\n"}, "reference": " private static Type resolve(Type context, Class contextRawType, Type toResolve,\n Collection visitedTypeVariables) {\n while (true) {\n if (toResolve instanceof TypeVariable) {\n TypeVariable typeVariable = (TypeVariable) toResolve;\n if (visitedTypeVariables.contains(typeVariable)) {\n return toResolve;\n } else {\n visitedTypeVariables.add(typeVariable);\n }\n toResolve = resolveTypeVariable(context, contextRawType, typeVariable);\n if (toResolve == typeVariable) {\n return toResolve;\n }\n } else if (toResolve instanceof Class && ((Class) toResolve).isArray()) {\n Class original = (Class) toResolve;\n Type componentType = original.getComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof GenericArrayType) {\n GenericArrayType original = (GenericArrayType) toResolve;\n Type componentType = original.getGenericComponentType();\n Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);\n return componentType == newComponentType\n ? original\n : arrayOf(newComponentType);\n } else if (toResolve instanceof ParameterizedType) {\n ParameterizedType original = (ParameterizedType) toResolve;\n Type ownerType = original.getOwnerType();\n Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);\n boolean changed = newOwnerType != ownerType;\n Type[] args = original.getActualTypeArguments();\n for (int t = 0, length = args.length; t < length; t++) {\n Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);\n if (resolvedTypeArgument != args[t]) {\n if (!changed) {\n args = args.clone();\n changed = true;\n }\n args[t] = resolvedTypeArgument;\n }\n }\n return changed\n ? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)\n : original;\n } else if (toResolve instanceof WildcardType) {\n WildcardType original = (WildcardType) toResolve;\n Type[] originalLowerBound = original.getLowerBounds();\n Type[] originalUpperBound = original.getUpperBounds();\n if (originalLowerBound.length == 1) {\n Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);\n if (lowerBound != originalLowerBound[0]) {\n return supertypeOf(lowerBound);\n }\n } else if (originalUpperBound.length == 1) {\n Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);\n if (upperBound != originalUpperBound[0]) {\n return subtypeOf(upperBound);\n }\n }\n return original;\n } else {\n return toResolve;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-16"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-16"}} {"sample_uid": "defects4j_function_repair::Closure-99", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN)) {\n return false;\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n if (lhs.getQualifiedName() != null && lhs.getQualifiedName().contains(\".prototype.\")) {\n return false;\n }\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN)) {\n return false;\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n if (lhs.getQualifiedName() != null && lhs.getQualifiedName().contains(\".prototype.\")) {\n return false;\n }\n }\n }\n return true;\n }\n"}, "reference": " public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.isInterface() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN)) {\n return false;\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (NodeUtil.isGet(lhs)) {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n Node llhs = lhs.getFirstChild();\n if (llhs.getType() == Token.GETPROP &&\n llhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n }\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-99"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-99"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-62", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public CollectionDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegateDeser = null;\n if (_valueInstantiator != null) {\n if (_valueInstantiator.canCreateUsingDelegate()) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n if (delegateType == null) {\n throw new IllegalArgumentException(\"Invalid delegate-creator definition for \"+_collectionType\n +\": value instantiator (\"+_valueInstantiator.getClass().getName()\n +\") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'\");\n }\n delegateDeser = findDeserializer(ctxt, delegateType, property);\n }\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n JsonDeserializer valueDeser = _valueDeserializer;\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n final JavaType vt = _collectionType.getContentType();\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(vt, property);\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);\n }\n TypeDeserializer valueTypeDeser = _valueTypeDeserializer;\n if (valueTypeDeser != null) {\n valueTypeDeser = valueTypeDeser.forProperty(property);\n }\n return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public CollectionDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegateDeser = null;\n if (_valueInstantiator != null) {\n if (_valueInstantiator.canCreateUsingDelegate()) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n if (delegateType == null) {\n throw new IllegalArgumentException(\"Invalid delegate-creator definition for \"+_collectionType\n +\": value instantiator (\"+_valueInstantiator.getClass().getName()\n +\") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'\");\n }\n delegateDeser = findDeserializer(ctxt, delegateType, property);\n }\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n JsonDeserializer valueDeser = _valueDeserializer;\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n final JavaType vt = _collectionType.getContentType();\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(vt, property);\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);\n }\n TypeDeserializer valueTypeDeser = _valueTypeDeserializer;\n if (valueTypeDeser != null) {\n valueTypeDeser = valueTypeDeser.forProperty(property);\n }\n return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);\n }\n"}, "reference": " public CollectionDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegateDeser = null;\n if (_valueInstantiator != null) {\n if (_valueInstantiator.canCreateUsingDelegate()) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n if (delegateType == null) {\n throw new IllegalArgumentException(\"Invalid delegate-creator definition for \"+_collectionType\n +\": value instantiator (\"+_valueInstantiator.getClass().getName()\n +\") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'\");\n }\n delegateDeser = findDeserializer(ctxt, delegateType, property);\n } else if (_valueInstantiator.canCreateUsingArrayDelegate()) {\n JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());\n if (delegateType == null) {\n throw new IllegalArgumentException(\"Invalid array-delegate-creator definition for \"+_collectionType\n +\": value instantiator (\"+_valueInstantiator.getClass().getName()\n +\") returned true for 'canCreateUsingArrayDelegate()', but null for 'getArrayDelegateType()'\");\n }\n delegateDeser = findDeserializer(ctxt, delegateType, property);\n }\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n JsonDeserializer valueDeser = _valueDeserializer;\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n final JavaType vt = _collectionType.getContentType();\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(vt, property);\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);\n }\n TypeDeserializer valueTypeDeser = _valueTypeDeserializer;\n if (valueTypeDeser != null) {\n valueTypeDeser = valueTypeDeser.forProperty(property);\n }\n return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-62"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-62"}} {"sample_uid": "defects4j_function_repair::Cli-38", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isShortOption(String token)\n {\n if (!token.startsWith(\"-\") || token.length() == 1)\n {\n return false;\n }\n int pos = token.indexOf(\"=\");\n String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);\n return options.hasShortOption(optName);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isShortOption(String token)\n {\n if (!token.startsWith(\"-\") || token.length() == 1)\n {\n return false;\n }\n int pos = token.indexOf(\"=\");\n String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);\n return options.hasShortOption(optName);\n }\n"}, "reference": " private boolean isShortOption(String token)\n {\n if (!token.startsWith(\"-\") || token.length() == 1)\n {\n return false;\n }\n int pos = token.indexOf(\"=\");\n String optName = pos == -1 ? token.substring(1) : token.substring(1, pos);\n if (options.hasShortOption(optName))\n {\n return true;\n }\n return optName.length() > 0 && options.hasShortOption(String.valueOf(optName.charAt(0)));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Cli-38"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Cli-38"}} {"sample_uid": "defects4j_function_repair::Time-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static long safeMultiply(long val1, int val2) {\n switch (val2) {\n case -1:\n return -val1;\n case 0:\n return 0L;\n case 1:\n return val1;\n }\n long total = val1 * val2;\n if (total / val2 != val1) {\n throw new ArithmeticException(\"Multiplication overflows a long: \" + val1 + \" * \" + val2);\n }\n return total;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long safeMultiply(long val1, int val2) {\n switch (val2) {\n case -1:\n return -val1;\n case 0:\n return 0L;\n case 1:\n return val1;\n }\n long total = val1 * val2;\n if (total / val2 != val1) {\n throw new ArithmeticException(\"Multiplication overflows a long: \" + val1 + \" * \" + val2);\n }\n return total;\n }\n"}, "reference": " public static long safeMultiply(long val1, int val2) {\n switch (val2) {\n case -1:\n if (val1 == Long.MIN_VALUE) {\n throw new ArithmeticException(\"Multiplication overflows a long: \" + val1 + \" * \" + val2);\n }\n return -val1;\n case 0:\n return 0L;\n case 1:\n return val1;\n }\n long total = val1 * val2;\n if (total / val2 != val1) {\n throw new ArithmeticException(\"Multiplication overflows a long: \" + val1 + \" * \" + val2);\n }\n return total;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-15"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-15"}} {"sample_uid": "defects4j_function_repair::Csv-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n int readEscape() throws IOException {\n final int c = in.read();\n switch (c) {\n case 'r':\n return CR;\n case 'n':\n return LF;\n case 't':\n return TAB;\n case 'b':\n return BACKSPACE;\n case 'f':\n return FF;\n case CR:\n case LF:\n case FF: \n case TAB: \n case BACKSPACE: \n return c;\n case END_OF_STREAM:\n throw new IOException(\"EOF whilst processing escape sequence\");\n default:\n return c;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " int readEscape() throws IOException {\n final int c = in.read();\n switch (c) {\n case 'r':\n return CR;\n case 'n':\n return LF;\n case 't':\n return TAB;\n case 'b':\n return BACKSPACE;\n case 'f':\n return FF;\n case CR:\n case LF:\n case FF: \n case TAB: \n case BACKSPACE: \n return c;\n case END_OF_STREAM:\n throw new IOException(\"EOF whilst processing escape sequence\");\n default:\n return c;\n }\n }\n"}, "reference": " int readEscape() throws IOException {\n final int c = in.read();\n switch (c) {\n case 'r':\n return CR;\n case 'n':\n return LF;\n case 't':\n return TAB;\n case 'b':\n return BACKSPACE;\n case 'f':\n return FF;\n case CR:\n case LF:\n case FF: \n case TAB: \n case BACKSPACE: \n return c;\n case END_OF_STREAM:\n throw new IOException(\"EOF whilst processing escape sequence\");\n default:\n if (isDelimiter(c) || isEscape(c) || isQuoteChar(c) || isCommentStart(c)) {\n return c;\n }\n return END_OF_STREAM;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-3"}} {"sample_uid": "defects4j_function_repair::Closure-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n JSType resolveInternal(ErrorReporter t, StaticScope enclosing) {\n boolean resolved = resolveViaRegistry(t, enclosing);\n if (detectImplicitPrototypeCycle()) {\n handleTypeCycle(t);\n }\n if (resolved) {\n super.resolveInternal(t, enclosing);\n finishPropertyContinuations();\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n resolveViaProperties(t, enclosing);\n if (detectImplicitPrototypeCycle()) {\n handleTypeCycle(t);\n }\n super.resolveInternal(t, enclosing);\n if (isResolved()) {\n finishPropertyContinuations();\n }\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " JSType resolveInternal(ErrorReporter t, StaticScope enclosing) {\n boolean resolved = resolveViaRegistry(t, enclosing);\n if (detectImplicitPrototypeCycle()) {\n handleTypeCycle(t);\n }\n if (resolved) {\n super.resolveInternal(t, enclosing);\n finishPropertyContinuations();\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n resolveViaProperties(t, enclosing);\n if (detectImplicitPrototypeCycle()) {\n handleTypeCycle(t);\n }\n super.resolveInternal(t, enclosing);\n if (isResolved()) {\n finishPropertyContinuations();\n }\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n"}, "reference": " JSType resolveInternal(ErrorReporter t, StaticScope enclosing) {\n boolean resolved = resolveViaRegistry(t, enclosing);\n if (detectInheritanceCycle()) {\n handleTypeCycle(t);\n }\n if (resolved) {\n super.resolveInternal(t, enclosing);\n finishPropertyContinuations();\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n resolveViaProperties(t, enclosing);\n if (detectInheritanceCycle()) {\n handleTypeCycle(t);\n }\n super.resolveInternal(t, enclosing);\n if (isResolved()) {\n finishPropertyContinuations();\n }\n return registry.isLastGeneration() ?\n getReferencedType() : this;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-4"}} {"sample_uid": "defects4j_function_repair::Collections-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": ""}, "reference": " private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {\n is.defaultReadObject();\n if (clazz != null && !Collection.class.isAssignableFrom(clazz)) {\n throw new UnsupportedOperationException();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Collections-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Collections-27"}} {"sample_uid": "defects4j_function_repair::Csv-4", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Map getHeaderMap() {\n return new LinkedHashMap(this.headerMap);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Map getHeaderMap() {\n return new LinkedHashMap(this.headerMap);\n }\n"}, "reference": " public Map getHeaderMap() {\n return this.headerMap == null ? null : new LinkedHashMap(this.headerMap);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-4"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-4"}} {"sample_uid": "defects4j_function_repair::Compress-18", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void writePaxHeaders(String entryName,\n Map headers) throws IOException {\n String name = \"./PaxHeaders.X/\" + stripTo7Bits(entryName);\n if (name.length() >= TarConstants.NAMELEN) {\n name = name.substring(0, TarConstants.NAMELEN - 1);\n }\n TarArchiveEntry pex = new TarArchiveEntry(name,\n TarConstants.LF_PAX_EXTENDED_HEADER_LC);\n StringWriter w = new StringWriter();\n for (Map.Entry h : headers.entrySet()) {\n String key = h.getKey();\n String value = h.getValue();\n int len = key.length() + value.length()\n + 3 \n + 2 ;\n String line = len + \" \" + key + \"=\" + value + \"\\n\";\n int actualLength = line.getBytes(CharsetNames.UTF_8).length;\n while (len != actualLength) {\n len = actualLength;\n line = len + \" \" + key + \"=\" + value + \"\\n\";\n actualLength = line.getBytes(CharsetNames.UTF_8).length;\n }\n w.write(line);\n }\n byte[] data = w.toString().getBytes(CharsetNames.UTF_8);\n pex.setSize(data.length);\n putArchiveEntry(pex);\n write(data);\n closeArchiveEntry();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void writePaxHeaders(String entryName,\n Map headers) throws IOException {\n String name = \"./PaxHeaders.X/\" + stripTo7Bits(entryName);\n if (name.length() >= TarConstants.NAMELEN) {\n name = name.substring(0, TarConstants.NAMELEN - 1);\n }\n TarArchiveEntry pex = new TarArchiveEntry(name,\n TarConstants.LF_PAX_EXTENDED_HEADER_LC);\n StringWriter w = new StringWriter();\n for (Map.Entry h : headers.entrySet()) {\n String key = h.getKey();\n String value = h.getValue();\n int len = key.length() + value.length()\n + 3 \n + 2 ;\n String line = len + \" \" + key + \"=\" + value + \"\\n\";\n int actualLength = line.getBytes(CharsetNames.UTF_8).length;\n while (len != actualLength) {\n len = actualLength;\n line = len + \" \" + key + \"=\" + value + \"\\n\";\n actualLength = line.getBytes(CharsetNames.UTF_8).length;\n }\n w.write(line);\n }\n byte[] data = w.toString().getBytes(CharsetNames.UTF_8);\n pex.setSize(data.length);\n putArchiveEntry(pex);\n write(data);\n closeArchiveEntry();\n }\n"}, "reference": " void writePaxHeaders(String entryName,\n Map headers) throws IOException {\n String name = \"./PaxHeaders.X/\" + stripTo7Bits(entryName);\n while (name.endsWith(\"/\")) {\n name = name.substring(0, name.length() - 1);\n }\n if (name.length() >= TarConstants.NAMELEN) {\n name = name.substring(0, TarConstants.NAMELEN - 1);\n }\n TarArchiveEntry pex = new TarArchiveEntry(name,\n TarConstants.LF_PAX_EXTENDED_HEADER_LC);\n StringWriter w = new StringWriter();\n for (Map.Entry h : headers.entrySet()) {\n String key = h.getKey();\n String value = h.getValue();\n int len = key.length() + value.length()\n + 3 \n + 2 ;\n String line = len + \" \" + key + \"=\" + value + \"\\n\";\n int actualLength = line.getBytes(CharsetNames.UTF_8).length;\n while (len != actualLength) {\n len = actualLength;\n line = len + \" \" + key + \"=\" + value + \"\\n\";\n actualLength = line.getBytes(CharsetNames.UTF_8).length;\n }\n w.write(line);\n }\n byte[] data = w.toString().getBytes(CharsetNames.UTF_8);\n pex.setSize(data.length);\n putArchiveEntry(pex);\n write(data);\n closeArchiveEntry();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-18"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-18"}} {"sample_uid": "defects4j_function_repair::Closure-96", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void visitParameterList(NodeTraversal t, Node call,\n FunctionType functionType) {\n Iterator arguments = call.children().iterator();\n arguments.next(); \n Iterator parameters = functionType.getParameters().iterator();\n int ordinal = 0;\n Node parameter = null;\n Node argument = null;\n while (arguments.hasNext() &&\n parameters.hasNext()) {\n parameter = parameters.next();\n argument = arguments.next();\n ordinal++;\n validator.expectArgumentMatchesParameter(t, argument,\n getJSType(argument), getJSType(parameter), call, ordinal);\n }\n int numArgs = call.getChildCount() - 1;\n int minArgs = functionType.getMinArguments();\n int maxArgs = functionType.getMaxArguments();\n if (minArgs > numArgs || maxArgs < numArgs) {\n report(t, call, WRONG_ARGUMENT_COUNT,\n validator.getReadableJSTypeName(call.getFirstChild(), false),\n String.valueOf(numArgs), String.valueOf(minArgs),\n maxArgs != Integer.MAX_VALUE ?\n \" and no more than \" + maxArgs + \" argument(s)\" : \"\");\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void visitParameterList(NodeTraversal t, Node call,\n FunctionType functionType) {\n Iterator arguments = call.children().iterator();\n arguments.next(); \n Iterator parameters = functionType.getParameters().iterator();\n int ordinal = 0;\n Node parameter = null;\n Node argument = null;\n while (arguments.hasNext() &&\n parameters.hasNext()) {\n parameter = parameters.next();\n argument = arguments.next();\n ordinal++;\n validator.expectArgumentMatchesParameter(t, argument,\n getJSType(argument), getJSType(parameter), call, ordinal);\n }\n int numArgs = call.getChildCount() - 1;\n int minArgs = functionType.getMinArguments();\n int maxArgs = functionType.getMaxArguments();\n if (minArgs > numArgs || maxArgs < numArgs) {\n report(t, call, WRONG_ARGUMENT_COUNT,\n validator.getReadableJSTypeName(call.getFirstChild(), false),\n String.valueOf(numArgs), String.valueOf(minArgs),\n maxArgs != Integer.MAX_VALUE ?\n \" and no more than \" + maxArgs + \" argument(s)\" : \"\");\n }\n }\n"}, "reference": " private void visitParameterList(NodeTraversal t, Node call,\n FunctionType functionType) {\n Iterator arguments = call.children().iterator();\n arguments.next(); \n Iterator parameters = functionType.getParameters().iterator();\n int ordinal = 0;\n Node parameter = null;\n Node argument = null;\n while (arguments.hasNext() &&\n (parameters.hasNext() ||\n parameter != null && parameter.isVarArgs())) {\n if (parameters.hasNext()) {\n parameter = parameters.next();\n }\n argument = arguments.next();\n ordinal++;\n validator.expectArgumentMatchesParameter(t, argument,\n getJSType(argument), getJSType(parameter), call, ordinal);\n }\n int numArgs = call.getChildCount() - 1;\n int minArgs = functionType.getMinArguments();\n int maxArgs = functionType.getMaxArguments();\n if (minArgs > numArgs || maxArgs < numArgs) {\n report(t, call, WRONG_ARGUMENT_COUNT,\n validator.getReadableJSTypeName(call.getFirstChild(), false),\n String.valueOf(numArgs), String.valueOf(minArgs),\n maxArgs != Integer.MAX_VALUE ?\n \" and no more than \" + maxArgs + \" argument(s)\" : \"\");\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-96"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-96"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-97", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException\n {\n if (_value == null) {\n ctxt.defaultSerializeNull(gen);\n } else if (_value instanceof JsonSerializable) {\n ((JsonSerializable) _value).serialize(gen, ctxt);\n } else {\n gen.writeObject(_value);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException\n {\n if (_value == null) {\n ctxt.defaultSerializeNull(gen);\n } else if (_value instanceof JsonSerializable) {\n ((JsonSerializable) _value).serialize(gen, ctxt);\n } else {\n gen.writeObject(_value);\n }\n }\n"}, "reference": " public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException\n {\n if (_value == null) {\n ctxt.defaultSerializeNull(gen);\n } else if (_value instanceof JsonSerializable) {\n ((JsonSerializable) _value).serialize(gen, ctxt);\n } else {\n ctxt.defaultSerializeValue(_value, gen);\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-97"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-97"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-47", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JavaType refineSerializationType(final MapperConfig config,\n final Annotated a, final JavaType baseType) throws JsonMappingException\n {\n JavaType type = baseType;\n final TypeFactory tf = config.getTypeFactory();\n Class serClass = findSerializationType(a);\n if (serClass != null) {\n if (type.hasRawClass(serClass)) {\n type = type.withStaticTyping();\n } else {\n try {\n type = tf.constructGeneralizedType(type, serClass);\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen type %s with annotation (value %s), from '%s': %s\",\n type, serClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n }\n if (type.isMapLikeType()) {\n JavaType keyType = type.getKeyType();\n Class keyClass = findSerializationKeyType(a, keyType);\n if (keyClass != null) {\n if (keyType.hasRawClass(keyClass)) {\n keyType = keyType.withStaticTyping();\n } else {\n Class currRaw = keyType.getRawClass();\n try {\n if (keyClass.isAssignableFrom(currRaw)) { \n keyType = tf.constructGeneralizedType(keyType, keyClass);\n } else if (currRaw.isAssignableFrom(keyClass)) { \n keyType = tf.constructSpecializedType(keyType, keyClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization key type %s into %s; types not related\",\n keyType, keyClass.getName()));\n }\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, keyClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = ((MapLikeType) type).withKeyType(keyType);\n }\n }\n JavaType contentType = type.getContentType();\n if (contentType != null) { \n Class contentClass = findSerializationContentType(a, contentType);\n if (contentClass != null) {\n if (contentType.hasRawClass(contentClass)) {\n contentType = contentType.withStaticTyping();\n } else {\n Class currRaw = contentType.getRawClass();\n try {\n if (contentClass.isAssignableFrom(currRaw)) { \n contentType = tf.constructGeneralizedType(contentType, contentClass);\n } else if (currRaw.isAssignableFrom(contentClass)) { \n contentType = tf.constructSpecializedType(contentType, contentClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization content type %s into %s; types not related\",\n contentType, contentClass.getName()));\n }\n } catch (IllegalArgumentException iae) { \n throw new JsonMappingException(null,\n String.format(\"Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, contentClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = type.withContentType(contentType);\n }\n }\n return type;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JavaType refineSerializationType(final MapperConfig config,\n final Annotated a, final JavaType baseType) throws JsonMappingException\n {\n JavaType type = baseType;\n final TypeFactory tf = config.getTypeFactory();\n Class serClass = findSerializationType(a);\n if (serClass != null) {\n if (type.hasRawClass(serClass)) {\n type = type.withStaticTyping();\n } else {\n try {\n type = tf.constructGeneralizedType(type, serClass);\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen type %s with annotation (value %s), from '%s': %s\",\n type, serClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n }\n if (type.isMapLikeType()) {\n JavaType keyType = type.getKeyType();\n Class keyClass = findSerializationKeyType(a, keyType);\n if (keyClass != null) {\n if (keyType.hasRawClass(keyClass)) {\n keyType = keyType.withStaticTyping();\n } else {\n Class currRaw = keyType.getRawClass();\n try {\n if (keyClass.isAssignableFrom(currRaw)) { \n keyType = tf.constructGeneralizedType(keyType, keyClass);\n } else if (currRaw.isAssignableFrom(keyClass)) { \n keyType = tf.constructSpecializedType(keyType, keyClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization key type %s into %s; types not related\",\n keyType, keyClass.getName()));\n }\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, keyClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = ((MapLikeType) type).withKeyType(keyType);\n }\n }\n JavaType contentType = type.getContentType();\n if (contentType != null) { \n Class contentClass = findSerializationContentType(a, contentType);\n if (contentClass != null) {\n if (contentType.hasRawClass(contentClass)) {\n contentType = contentType.withStaticTyping();\n } else {\n Class currRaw = contentType.getRawClass();\n try {\n if (contentClass.isAssignableFrom(currRaw)) { \n contentType = tf.constructGeneralizedType(contentType, contentClass);\n } else if (currRaw.isAssignableFrom(contentClass)) { \n contentType = tf.constructSpecializedType(contentType, contentClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization content type %s into %s; types not related\",\n contentType, contentClass.getName()));\n }\n } catch (IllegalArgumentException iae) { \n throw new JsonMappingException(null,\n String.format(\"Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, contentClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = type.withContentType(contentType);\n }\n }\n return type;\n }\n"}, "reference": " public JavaType refineSerializationType(final MapperConfig config,\n final Annotated a, final JavaType baseType) throws JsonMappingException\n {\n JavaType type = baseType;\n final TypeFactory tf = config.getTypeFactory();\n Class serClass = findSerializationType(a);\n if (serClass != null) {\n if (type.hasRawClass(serClass)) {\n type = type.withStaticTyping();\n } else {\n Class currRaw = type.getRawClass();\n try {\n if (serClass.isAssignableFrom(currRaw)) { \n type = tf.constructGeneralizedType(type, serClass);\n } else if (currRaw.isAssignableFrom(serClass)) { \n type = tf.constructSpecializedType(type, serClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization type %s into %s; types not related\",\n type, serClass.getName()));\n }\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen type %s with annotation (value %s), from '%s': %s\",\n type, serClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n }\n if (type.isMapLikeType()) {\n JavaType keyType = type.getKeyType();\n Class keyClass = findSerializationKeyType(a, keyType);\n if (keyClass != null) {\n if (keyType.hasRawClass(keyClass)) {\n keyType = keyType.withStaticTyping();\n } else {\n Class currRaw = keyType.getRawClass();\n try {\n if (keyClass.isAssignableFrom(currRaw)) { \n keyType = tf.constructGeneralizedType(keyType, keyClass);\n } else if (currRaw.isAssignableFrom(keyClass)) { \n keyType = tf.constructSpecializedType(keyType, keyClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization key type %s into %s; types not related\",\n keyType, keyClass.getName()));\n }\n } catch (IllegalArgumentException iae) {\n throw new JsonMappingException(null,\n String.format(\"Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, keyClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = ((MapLikeType) type).withKeyType(keyType);\n }\n }\n JavaType contentType = type.getContentType();\n if (contentType != null) { \n Class contentClass = findSerializationContentType(a, contentType);\n if (contentClass != null) {\n if (contentType.hasRawClass(contentClass)) {\n contentType = contentType.withStaticTyping();\n } else {\n Class currRaw = contentType.getRawClass();\n try {\n if (contentClass.isAssignableFrom(currRaw)) { \n contentType = tf.constructGeneralizedType(contentType, contentClass);\n } else if (currRaw.isAssignableFrom(contentClass)) { \n contentType = tf.constructSpecializedType(contentType, contentClass);\n } else {\n throw new JsonMappingException(null,\n String.format(\"Can not refine serialization content type %s into %s; types not related\",\n contentType, contentClass.getName()));\n }\n } catch (IllegalArgumentException iae) { \n throw new JsonMappingException(null,\n String.format(\"Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s\",\n type, contentClass.getName(), a.getName(), iae.getMessage()),\n iae);\n }\n }\n type = type.withContentType(contentType);\n }\n }\n return type;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-47"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-47"}} {"sample_uid": "defects4j_function_repair::Math-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double percentageValue() {\n return multiply(100).doubleValue();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double percentageValue() {\n return multiply(100).doubleValue();\n }\n"}, "reference": " public double percentageValue() {\n return 100 * doubleValue();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-27"}} {"sample_uid": "defects4j_function_repair::Closure-36", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean canInline(\n Reference declaration,\n Reference initialization,\n Reference reference) {\n if (!isValidDeclaration(declaration)\n || !isValidInitialization(initialization)\n || !isValidReference(reference)) {\n return false;\n }\n if (declaration != initialization &&\n !initialization.getGrandparent().isExprResult()) {\n return false;\n }\n if (declaration.getBasicBlock() != initialization.getBasicBlock()\n || declaration.getBasicBlock() != reference.getBasicBlock()) {\n return false;\n }\n Node value = initialization.getAssignedValue();\n Preconditions.checkState(value != null);\n if (value.isGetProp()\n && reference.getParent().isCall()\n && reference.getParent().getFirstChild() == reference.getNode()) {\n return false;\n }\n if (value.isFunction()) {\n Node callNode = reference.getParent();\n if (reference.getParent().isCall()) {\n CodingConvention convention = compiler.getCodingConvention();\n SubclassRelationship relationship =\n convention.getClassesDefinedByCall(callNode);\n if (relationship != null) {\n return false;\n }\n }\n }\n return canMoveAggressively(value) ||\n canMoveModerately(initialization, reference);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean canInline(\n Reference declaration,\n Reference initialization,\n Reference reference) {\n if (!isValidDeclaration(declaration)\n || !isValidInitialization(initialization)\n || !isValidReference(reference)) {\n return false;\n }\n if (declaration != initialization &&\n !initialization.getGrandparent().isExprResult()) {\n return false;\n }\n if (declaration.getBasicBlock() != initialization.getBasicBlock()\n || declaration.getBasicBlock() != reference.getBasicBlock()) {\n return false;\n }\n Node value = initialization.getAssignedValue();\n Preconditions.checkState(value != null);\n if (value.isGetProp()\n && reference.getParent().isCall()\n && reference.getParent().getFirstChild() == reference.getNode()) {\n return false;\n }\n if (value.isFunction()) {\n Node callNode = reference.getParent();\n if (reference.getParent().isCall()) {\n CodingConvention convention = compiler.getCodingConvention();\n SubclassRelationship relationship =\n convention.getClassesDefinedByCall(callNode);\n if (relationship != null) {\n return false;\n }\n }\n }\n return canMoveAggressively(value) ||\n canMoveModerately(initialization, reference);\n }\n"}, "reference": " private boolean canInline(\n Reference declaration,\n Reference initialization,\n Reference reference) {\n if (!isValidDeclaration(declaration)\n || !isValidInitialization(initialization)\n || !isValidReference(reference)) {\n return false;\n }\n if (declaration != initialization &&\n !initialization.getGrandparent().isExprResult()) {\n return false;\n }\n if (declaration.getBasicBlock() != initialization.getBasicBlock()\n || declaration.getBasicBlock() != reference.getBasicBlock()) {\n return false;\n }\n Node value = initialization.getAssignedValue();\n Preconditions.checkState(value != null);\n if (value.isGetProp()\n && reference.getParent().isCall()\n && reference.getParent().getFirstChild() == reference.getNode()) {\n return false;\n }\n if (value.isFunction()) {\n Node callNode = reference.getParent();\n if (reference.getParent().isCall()) {\n CodingConvention convention = compiler.getCodingConvention();\n SubclassRelationship relationship =\n convention.getClassesDefinedByCall(callNode);\n if (relationship != null) {\n return false;\n }\n if (convention.getSingletonGetterClassName(callNode) != null) {\n return false;\n }\n }\n }\n return canMoveAggressively(value) ||\n canMoveModerately(initialization, reference);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-36"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-36"}} {"sample_uid": "defects4j_function_repair::Jsoup-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean hasAttr(String attributeKey) {\n Validate.notNull(attributeKey);\n return attributes.hasKey(attributeKey);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean hasAttr(String attributeKey) {\n Validate.notNull(attributeKey);\n return attributes.hasKey(attributeKey);\n }\n"}, "reference": " public boolean hasAttr(String attributeKey) {\n Validate.notNull(attributeKey);\n if (attributeKey.toLowerCase().startsWith(\"abs:\")) {\n String key = attributeKey.substring(\"abs:\".length());\n if (attributes.hasKey(key) && !absUrl(key).equals(\"\"))\n return true;\n }\n return attributes.hasKey(attributeKey);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-13"}} {"sample_uid": "defects4j_function_repair::Compress-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n boolean allNUL = true;\n for (int i = start; i < end; i++){\n if (buffer[i] != 0){\n allNUL = false;\n break;\n }\n }\n if (allNUL) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n boolean allNUL = true;\n for (int i = start; i < end; i++){\n if (buffer[i] != 0){\n allNUL = false;\n break;\n }\n }\n if (allNUL) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n"}, "reference": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-14"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-83", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n String text = p.getValueAsString();\n if (text != null) { \n if (text.length() == 0 || (text = text.trim()).length() == 0) {\n return _deserializeFromEmptyString();\n }\n Exception cause = null;\n try {\n if (_deserialize(text, ctxt) != null) {\n return _deserialize(text, ctxt);\n }\n } catch (IllegalArgumentException iae) {\n cause = iae;\n } catch (MalformedURLException me) {\n cause = me;\n }\n String msg = \"not a valid textual representation\";\n if (cause != null) {\n String m2 = cause.getMessage();\n if (m2 != null) {\n msg = msg + \", problem: \"+m2;\n }\n }\n JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);\n if (cause != null) {\n e.initCause(cause);\n }\n throw e;\n }\n JsonToken t = p.getCurrentToken();\n if (t == JsonToken.START_ARRAY) {\n return _deserializeFromArray(p, ctxt);\n }\n if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {\n Object ob = p.getEmbeddedObject();\n if (ob == null) {\n return null;\n }\n if (_valueClass.isAssignableFrom(ob.getClass())) {\n return (T) ob;\n }\n return _deserializeEmbedded(ob, ctxt);\n }\n return (T) ctxt.handleUnexpectedToken(_valueClass, p);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n String text = p.getValueAsString();\n if (text != null) { \n if (text.length() == 0 || (text = text.trim()).length() == 0) {\n return _deserializeFromEmptyString();\n }\n Exception cause = null;\n try {\n if (_deserialize(text, ctxt) != null) {\n return _deserialize(text, ctxt);\n }\n } catch (IllegalArgumentException iae) {\n cause = iae;\n } catch (MalformedURLException me) {\n cause = me;\n }\n String msg = \"not a valid textual representation\";\n if (cause != null) {\n String m2 = cause.getMessage();\n if (m2 != null) {\n msg = msg + \", problem: \"+m2;\n }\n }\n JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);\n if (cause != null) {\n e.initCause(cause);\n }\n throw e;\n }\n JsonToken t = p.getCurrentToken();\n if (t == JsonToken.START_ARRAY) {\n return _deserializeFromArray(p, ctxt);\n }\n if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {\n Object ob = p.getEmbeddedObject();\n if (ob == null) {\n return null;\n }\n if (_valueClass.isAssignableFrom(ob.getClass())) {\n return (T) ob;\n }\n return _deserializeEmbedded(ob, ctxt);\n }\n return (T) ctxt.handleUnexpectedToken(_valueClass, p);\n }\n"}, "reference": " public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n String text = p.getValueAsString();\n if (text != null) { \n if (text.length() == 0 || (text = text.trim()).length() == 0) {\n return _deserializeFromEmptyString();\n }\n Exception cause = null;\n try {\n return _deserialize(text, ctxt);\n } catch (IllegalArgumentException iae) {\n cause = iae;\n } catch (MalformedURLException me) {\n cause = me;\n }\n String msg = \"not a valid textual representation\";\n if (cause != null) {\n String m2 = cause.getMessage();\n if (m2 != null) {\n msg = msg + \", problem: \"+m2;\n }\n }\n JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);\n if (cause != null) {\n e.initCause(cause);\n }\n throw e;\n }\n JsonToken t = p.getCurrentToken();\n if (t == JsonToken.START_ARRAY) {\n return _deserializeFromArray(p, ctxt);\n }\n if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {\n Object ob = p.getEmbeddedObject();\n if (ob == null) {\n return null;\n }\n if (_valueClass.isAssignableFrom(ob.getClass())) {\n return (T) ob;\n }\n return _deserializeEmbedded(ob, ctxt);\n }\n return (T) ctxt.handleUnexpectedToken(_valueClass, p);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-83"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-83"}} {"sample_uid": "defects4j_function_repair::Closure-24", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void findAliases(NodeTraversal t) {\n Scope scope = t.getScope();\n for (Var v : scope.getVarIterable()) {\n Node n = v.getNode();\n int type = n.getType();\n Node parent = n.getParent();\n if (parent.isVar()) {\n if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {\n String name = n.getString();\n Var aliasVar = scope.getVar(name);\n aliases.put(name, aliasVar);\n String qualifiedName =\n aliasVar.getInitialValue().getQualifiedName();\n transformation.addAlias(name, qualifiedName);\n } else {\n report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void findAliases(NodeTraversal t) {\n Scope scope = t.getScope();\n for (Var v : scope.getVarIterable()) {\n Node n = v.getNode();\n int type = n.getType();\n Node parent = n.getParent();\n if (parent.isVar()) {\n if (n.hasChildren() && n.getFirstChild().isQualifiedName()) {\n String name = n.getString();\n Var aliasVar = scope.getVar(name);\n aliases.put(name, aliasVar);\n String qualifiedName =\n aliasVar.getInitialValue().getQualifiedName();\n transformation.addAlias(name, qualifiedName);\n } else {\n report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());\n }\n }\n }\n }\n"}, "reference": " private void findAliases(NodeTraversal t) {\n Scope scope = t.getScope();\n for (Var v : scope.getVarIterable()) {\n Node n = v.getNode();\n int type = n.getType();\n Node parent = n.getParent();\n if (parent.isVar() &&\n n.hasChildren() && n.getFirstChild().isQualifiedName()) {\n String name = n.getString();\n Var aliasVar = scope.getVar(name);\n aliases.put(name, aliasVar);\n String qualifiedName =\n aliasVar.getInitialValue().getQualifiedName();\n transformation.addAlias(name, qualifiedName);\n } else if (v.isBleedingFunction()) {\n } else if (parent.getType() == Token.LP) {\n } else {\n report(t, n, GOOG_SCOPE_NON_ALIAS_LOCAL, n.getString());\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-24"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-24"}} {"sample_uid": "defects4j_function_repair::Math-57", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static > List>\n chooseInitialCenters(final Collection points, final int k, final Random random) {\n final List pointSet = new ArrayList(points);\n final List> resultSet = new ArrayList>();\n final T firstPoint = pointSet.remove(random.nextInt(pointSet.size()));\n resultSet.add(new Cluster(firstPoint));\n final double[] dx2 = new double[pointSet.size()];\n while (resultSet.size() < k) {\n int sum = 0;\n for (int i = 0; i < pointSet.size(); i++) {\n final T p = pointSet.get(i);\n final Cluster nearest = getNearestCluster(resultSet, p);\n final double d = p.distanceFrom(nearest.getCenter());\n sum += d * d;\n dx2[i] = sum;\n }\n final double r = random.nextDouble() * sum;\n for (int i = 0 ; i < dx2.length; i++) {\n if (dx2[i] >= r) {\n final T p = pointSet.remove(i);\n resultSet.add(new Cluster(p));\n break;\n }\n }\n }\n return resultSet;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static > List>\n chooseInitialCenters(final Collection points, final int k, final Random random) {\n final List pointSet = new ArrayList(points);\n final List> resultSet = new ArrayList>();\n final T firstPoint = pointSet.remove(random.nextInt(pointSet.size()));\n resultSet.add(new Cluster(firstPoint));\n final double[] dx2 = new double[pointSet.size()];\n while (resultSet.size() < k) {\n int sum = 0;\n for (int i = 0; i < pointSet.size(); i++) {\n final T p = pointSet.get(i);\n final Cluster nearest = getNearestCluster(resultSet, p);\n final double d = p.distanceFrom(nearest.getCenter());\n sum += d * d;\n dx2[i] = sum;\n }\n final double r = random.nextDouble() * sum;\n for (int i = 0 ; i < dx2.length; i++) {\n if (dx2[i] >= r) {\n final T p = pointSet.remove(i);\n resultSet.add(new Cluster(p));\n break;\n }\n }\n }\n return resultSet;\n }\n"}, "reference": " private static > List>\n chooseInitialCenters(final Collection points, final int k, final Random random) {\n final List pointSet = new ArrayList(points);\n final List> resultSet = new ArrayList>();\n final T firstPoint = pointSet.remove(random.nextInt(pointSet.size()));\n resultSet.add(new Cluster(firstPoint));\n final double[] dx2 = new double[pointSet.size()];\n while (resultSet.size() < k) {\n double sum = 0;\n for (int i = 0; i < pointSet.size(); i++) {\n final T p = pointSet.get(i);\n final Cluster nearest = getNearestCluster(resultSet, p);\n final double d = p.distanceFrom(nearest.getCenter());\n sum += d * d;\n dx2[i] = sum;\n }\n final double r = random.nextDouble() * sum;\n for (int i = 0 ; i < dx2.length; i++) {\n if (dx2[i] >= r) {\n final T p = pointSet.remove(i);\n resultSet.add(new Cluster(p));\n break;\n }\n }\n }\n return resultSet;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-57"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-57"}} {"sample_uid": "defects4j_function_repair::Closure-57", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static String extractClassNameIfGoog(Node node, Node parent,\n String functionName){\n String className = null;\n if (NodeUtil.isExprCall(parent)) {\n Node callee = node.getFirstChild();\n if (callee != null && callee.getType() == Token.GETPROP) {\n String qualifiedName = callee.getQualifiedName();\n if (functionName.equals(qualifiedName)) {\n Node target = callee.getNext();\n if (target != null) {\n className = target.getString();\n }\n }\n }\n }\n return className;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static String extractClassNameIfGoog(Node node, Node parent,\n String functionName){\n String className = null;\n if (NodeUtil.isExprCall(parent)) {\n Node callee = node.getFirstChild();\n if (callee != null && callee.getType() == Token.GETPROP) {\n String qualifiedName = callee.getQualifiedName();\n if (functionName.equals(qualifiedName)) {\n Node target = callee.getNext();\n if (target != null) {\n className = target.getString();\n }\n }\n }\n }\n return className;\n }\n"}, "reference": " private static String extractClassNameIfGoog(Node node, Node parent,\n String functionName){\n String className = null;\n if (NodeUtil.isExprCall(parent)) {\n Node callee = node.getFirstChild();\n if (callee != null && callee.getType() == Token.GETPROP) {\n String qualifiedName = callee.getQualifiedName();\n if (functionName.equals(qualifiedName)) {\n Node target = callee.getNext();\n if (target != null && target.getType() == Token.STRING) {\n className = target.getString();\n }\n }\n }\n }\n return className;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-57"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-57"}} {"sample_uid": "defects4j_function_repair::Jsoup-1", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void normalise(Element element) {\n List toMove = new ArrayList();\n for (Node node: element.childNodes) {\n if (node instanceof TextNode) {\n TextNode tn = (TextNode) node;\n if (!tn.isBlank())\n toMove.add(tn);\n }\n }\n for (Node node: toMove) {\n element.removeChild(node);\n body().appendChild(new TextNode(\" \", \"\"));\n body().appendChild(node);\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void normalise(Element element) {\n List toMove = new ArrayList();\n for (Node node: element.childNodes) {\n if (node instanceof TextNode) {\n TextNode tn = (TextNode) node;\n if (!tn.isBlank())\n toMove.add(tn);\n }\n }\n for (Node node: toMove) {\n element.removeChild(node);\n body().appendChild(new TextNode(\" \", \"\"));\n body().appendChild(node);\n }\n }\n"}, "reference": " private void normalise(Element element) {\n List toMove = new ArrayList();\n for (Node node: element.childNodes) {\n if (node instanceof TextNode) {\n TextNode tn = (TextNode) node;\n if (!tn.isBlank())\n toMove.add(tn);\n }\n }\n for (Node node: toMove) {\n element.removeChild(node);\n body().prependChild(node);\n body().prependChild(new TextNode(\" \", \"\"));\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-1"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-1"}} {"sample_uid": "defects4j_function_repair::Math-32", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void computeGeometricalProperties() {\n final Vector2D[][] v = getVertices();\n if (v.length == 0) {\n final BSPTree tree = getTree(false);\n if ((Boolean) tree.getAttribute()) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(0);\n setBarycenter(new Vector2D(0, 0));\n }\n } else if (v[0][0] == null) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n double sum = 0;\n double sumX = 0;\n double sumY = 0;\n for (Vector2D[] loop : v) {\n double x1 = loop[loop.length - 1].getX();\n double y1 = loop[loop.length - 1].getY();\n for (final Vector2D point : loop) {\n final double x0 = x1;\n final double y0 = y1;\n x1 = point.getX();\n y1 = point.getY();\n final double factor = x0 * y1 - y0 * x1;\n sum += factor;\n sumX += factor * (x0 + x1);\n sumY += factor * (y0 + y1);\n }\n }\n if (sum < 0) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(sum / 2);\n setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum)));\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void computeGeometricalProperties() {\n final Vector2D[][] v = getVertices();\n if (v.length == 0) {\n final BSPTree tree = getTree(false);\n if ((Boolean) tree.getAttribute()) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(0);\n setBarycenter(new Vector2D(0, 0));\n }\n } else if (v[0][0] == null) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n double sum = 0;\n double sumX = 0;\n double sumY = 0;\n for (Vector2D[] loop : v) {\n double x1 = loop[loop.length - 1].getX();\n double y1 = loop[loop.length - 1].getY();\n for (final Vector2D point : loop) {\n final double x0 = x1;\n final double y0 = y1;\n x1 = point.getX();\n y1 = point.getY();\n final double factor = x0 * y1 - y0 * x1;\n sum += factor;\n sumX += factor * (x0 + x1);\n sumY += factor * (y0 + y1);\n }\n }\n if (sum < 0) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(sum / 2);\n setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum)));\n }\n }\n }\n"}, "reference": " protected void computeGeometricalProperties() {\n final Vector2D[][] v = getVertices();\n if (v.length == 0) {\n final BSPTree tree = getTree(false);\n if (tree.getCut() == null && (Boolean) tree.getAttribute()) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(0);\n setBarycenter(new Vector2D(0, 0));\n }\n } else if (v[0][0] == null) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n double sum = 0;\n double sumX = 0;\n double sumY = 0;\n for (Vector2D[] loop : v) {\n double x1 = loop[loop.length - 1].getX();\n double y1 = loop[loop.length - 1].getY();\n for (final Vector2D point : loop) {\n final double x0 = x1;\n final double y0 = y1;\n x1 = point.getX();\n y1 = point.getY();\n final double factor = x0 * y1 - y0 * x1;\n sum += factor;\n sumX += factor * (x0 + x1);\n sumY += factor * (y0 + y1);\n }\n }\n if (sum < 0) {\n setSize(Double.POSITIVE_INFINITY);\n setBarycenter(Vector2D.NaN);\n } else {\n setSize(sum / 2);\n setBarycenter(new Vector2D(sumX / (3 * sum), sumY / (3 * sum)));\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-32"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-32"}} {"sample_uid": "defects4j_function_repair::Math-72", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(yMin, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(yMax, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n if (yMin * yMax > 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n NON_BRACKETING_MESSAGE, min, max, yMin, yMax);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(yMin, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(yMax, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n if (yMin * yMax > 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n NON_BRACKETING_MESSAGE, min, max, yMin, yMax);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n"}, "reference": " public double solve(final UnivariateRealFunction f,\n final double min, final double max, final double initial)\n throws MaxIterationsExceededException, FunctionEvaluationException {\n clearResult();\n verifySequence(min, initial, max);\n double yInitial = f.value(initial);\n if (Math.abs(yInitial) <= functionValueAccuracy) {\n setResult(initial, 0);\n return result;\n }\n double yMin = f.value(min);\n if (Math.abs(yMin) <= functionValueAccuracy) {\n setResult(min, 0);\n return result;\n }\n if (yInitial * yMin < 0) {\n return solve(f, min, yMin, initial, yInitial, min, yMin);\n }\n double yMax = f.value(max);\n if (Math.abs(yMax) <= functionValueAccuracy) {\n setResult(max, 0);\n return result;\n }\n if (yInitial * yMax < 0) {\n return solve(f, initial, yInitial, max, yMax, initial, yInitial);\n }\n if (yMin * yMax > 0) {\n throw MathRuntimeException.createIllegalArgumentException(\n NON_BRACKETING_MESSAGE, min, max, yMin, yMax);\n }\n return solve(f, min, yMin, max, yMax, initial, yInitial);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-72"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-72"}} {"sample_uid": "defects4j_function_repair::JacksonCore-6", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n char c = str.charAt(i);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n char c = str.charAt(i);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n"}, "reference": " private final static int _parseIndex(String str) {\n final int len = str.length();\n if (len == 0 || len > 10) {\n return -1;\n }\n char c = str.charAt(0);\n if (c <= '0') {\n return (len == 1 && c == '0') ? 0 : -1;\n }\n if (c > '9') {\n return -1;\n }\n for (int i = 1; i < len; ++i) {\n c = str.charAt(i);\n if (c > '9' || c < '0') {\n return -1;\n }\n }\n if (len == 10) {\n long l = NumberInput.parseLong(str);\n if (l > Integer.MAX_VALUE) {\n return -1;\n }\n }\n return NumberInput.parseInt(str);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-6"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-6"}} {"sample_uid": "defects4j_function_repair::Closure-172", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean isQualifiedNameInferred(\n String qName, Node n, JSDocInfo info,\n Node rhsValue, JSType valueType) {\n if (valueType == null) {\n return true;\n }\n if (qName != null && qName.endsWith(\".prototype\")) {\n return false;\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (isConstantSymbol(info, n) && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred && rhsValue != null && rhsValue.isFunction()) {\n if (info != null) {\n return false;\n } else if (!scope.isDeclared(qName, false) &&\n n.isUnscopedQualifiedName()) {\n for (Node current = n.getParent();\n !(current.isScript() || current.isFunction());\n current = current.getParent()) {\n if (NodeUtil.isControlStructure(current)) {\n return true;\n }\n }\n AstFunctionContents contents =\n getFunctionAnalysisResults(scope.getRootNode());\n if (contents == null ||\n !contents.getEscapedQualifiedNames().contains(qName)) {\n return false;\n }\n }\n }\n return inferred;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean isQualifiedNameInferred(\n String qName, Node n, JSDocInfo info,\n Node rhsValue, JSType valueType) {\n if (valueType == null) {\n return true;\n }\n if (qName != null && qName.endsWith(\".prototype\")) {\n return false;\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (isConstantSymbol(info, n) && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred && rhsValue != null && rhsValue.isFunction()) {\n if (info != null) {\n return false;\n } else if (!scope.isDeclared(qName, false) &&\n n.isUnscopedQualifiedName()) {\n for (Node current = n.getParent();\n !(current.isScript() || current.isFunction());\n current = current.getParent()) {\n if (NodeUtil.isControlStructure(current)) {\n return true;\n }\n }\n AstFunctionContents contents =\n getFunctionAnalysisResults(scope.getRootNode());\n if (contents == null ||\n !contents.getEscapedQualifiedNames().contains(qName)) {\n return false;\n }\n }\n }\n return inferred;\n }\n"}, "reference": " private boolean isQualifiedNameInferred(\n String qName, Node n, JSDocInfo info,\n Node rhsValue, JSType valueType) {\n if (valueType == null) {\n return true;\n }\n if (qName != null && qName.endsWith(\".prototype\")) {\n String className = qName.substring(0, qName.lastIndexOf(\".prototype\"));\n Var slot = scope.getSlot(className);\n JSType classType = slot == null ? null : slot.getType();\n if (classType != null\n && (classType.isConstructor() || classType.isInterface())) {\n return false;\n }\n }\n boolean inferred = true;\n if (info != null) {\n inferred = !(info.hasType()\n || info.hasEnumParameterType()\n || (isConstantSymbol(info, n) && valueType != null\n && !valueType.isUnknownType())\n || FunctionTypeBuilder.isFunctionTypeDeclaration(info));\n }\n if (inferred && rhsValue != null && rhsValue.isFunction()) {\n if (info != null) {\n return false;\n } else if (!scope.isDeclared(qName, false) &&\n n.isUnscopedQualifiedName()) {\n for (Node current = n.getParent();\n !(current.isScript() || current.isFunction());\n current = current.getParent()) {\n if (NodeUtil.isControlStructure(current)) {\n return true;\n }\n }\n AstFunctionContents contents =\n getFunctionAnalysisResults(scope.getRootNode());\n if (contents == null ||\n !contents.getEscapedQualifiedNames().contains(qName)) {\n return false;\n }\n }\n }\n return inferred;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-172"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-172"}} {"sample_uid": "defects4j_function_repair::Closure-150", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (n == scope.getRootNode()) return;\n if (n.getType() == Token.LP && parent == scope.getRootNode()) {\n handleFunctionInputs(parent);\n return;\n }\n attachLiteralTypes(n);\n switch (n.getType()) {\n case Token.FUNCTION:\n if (parent.getType() == Token.NAME) {\n return;\n }\n defineDeclaredFunction(n, parent);\n break;\n case Token.CATCH:\n defineCatch(n, parent);\n break;\n case Token.VAR:\n defineVar(n, parent);\n break;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (n == scope.getRootNode()) return;\n if (n.getType() == Token.LP && parent == scope.getRootNode()) {\n handleFunctionInputs(parent);\n return;\n }\n attachLiteralTypes(n);\n switch (n.getType()) {\n case Token.FUNCTION:\n if (parent.getType() == Token.NAME) {\n return;\n }\n defineDeclaredFunction(n, parent);\n break;\n case Token.CATCH:\n defineCatch(n, parent);\n break;\n case Token.VAR:\n defineVar(n, parent);\n break;\n }\n }\n"}, "reference": " @Override public void visit(NodeTraversal t, Node n, Node parent) {\n if (n == scope.getRootNode()) return;\n if (n.getType() == Token.LP && parent == scope.getRootNode()) {\n handleFunctionInputs(parent);\n return;\n }\n super.visit(t, n, parent);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-150"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-150"}} {"sample_uid": "defects4j_function_repair::Jsoup-45", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void resetInsertionMode() {\n boolean last = false;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (pos == 0) {\n last = true;\n node = contextElement;\n }\n String name = node.nodeName();\n if (\"select\".equals(name)) {\n transition(HtmlTreeBuilderState.InSelect);\n break; \n } else if ((\"td\".equals(name) || \"td\".equals(name) && !last)) {\n transition(HtmlTreeBuilderState.InCell);\n break;\n } else if (\"tr\".equals(name)) {\n transition(HtmlTreeBuilderState.InRow);\n break;\n } else if (\"tbody\".equals(name) || \"thead\".equals(name) || \"tfoot\".equals(name)) {\n transition(HtmlTreeBuilderState.InTableBody);\n break;\n } else if (\"caption\".equals(name)) {\n transition(HtmlTreeBuilderState.InCaption);\n break;\n } else if (\"colgroup\".equals(name)) {\n transition(HtmlTreeBuilderState.InColumnGroup);\n break; \n } else if (\"table\".equals(name)) {\n transition(HtmlTreeBuilderState.InTable);\n break;\n } else if (\"head\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n } else if (\"body\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break;\n } else if (\"frameset\".equals(name)) {\n transition(HtmlTreeBuilderState.InFrameset);\n break; \n } else if (\"html\".equals(name)) {\n transition(HtmlTreeBuilderState.BeforeHead);\n break; \n } else if (last) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void resetInsertionMode() {\n boolean last = false;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (pos == 0) {\n last = true;\n node = contextElement;\n }\n String name = node.nodeName();\n if (\"select\".equals(name)) {\n transition(HtmlTreeBuilderState.InSelect);\n break; \n } else if ((\"td\".equals(name) || \"td\".equals(name) && !last)) {\n transition(HtmlTreeBuilderState.InCell);\n break;\n } else if (\"tr\".equals(name)) {\n transition(HtmlTreeBuilderState.InRow);\n break;\n } else if (\"tbody\".equals(name) || \"thead\".equals(name) || \"tfoot\".equals(name)) {\n transition(HtmlTreeBuilderState.InTableBody);\n break;\n } else if (\"caption\".equals(name)) {\n transition(HtmlTreeBuilderState.InCaption);\n break;\n } else if (\"colgroup\".equals(name)) {\n transition(HtmlTreeBuilderState.InColumnGroup);\n break; \n } else if (\"table\".equals(name)) {\n transition(HtmlTreeBuilderState.InTable);\n break;\n } else if (\"head\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n } else if (\"body\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break;\n } else if (\"frameset\".equals(name)) {\n transition(HtmlTreeBuilderState.InFrameset);\n break; \n } else if (\"html\".equals(name)) {\n transition(HtmlTreeBuilderState.BeforeHead);\n break; \n } else if (last) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n }\n }\n }\n"}, "reference": " void resetInsertionMode() {\n boolean last = false;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element node = stack.get(pos);\n if (pos == 0) {\n last = true;\n node = contextElement;\n }\n String name = node.nodeName();\n if (\"select\".equals(name)) {\n transition(HtmlTreeBuilderState.InSelect);\n break; \n } else if ((\"td\".equals(name) || \"th\".equals(name) && !last)) {\n transition(HtmlTreeBuilderState.InCell);\n break;\n } else if (\"tr\".equals(name)) {\n transition(HtmlTreeBuilderState.InRow);\n break;\n } else if (\"tbody\".equals(name) || \"thead\".equals(name) || \"tfoot\".equals(name)) {\n transition(HtmlTreeBuilderState.InTableBody);\n break;\n } else if (\"caption\".equals(name)) {\n transition(HtmlTreeBuilderState.InCaption);\n break;\n } else if (\"colgroup\".equals(name)) {\n transition(HtmlTreeBuilderState.InColumnGroup);\n break; \n } else if (\"table\".equals(name)) {\n transition(HtmlTreeBuilderState.InTable);\n break;\n } else if (\"head\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n } else if (\"body\".equals(name)) {\n transition(HtmlTreeBuilderState.InBody);\n break;\n } else if (\"frameset\".equals(name)) {\n transition(HtmlTreeBuilderState.InFrameset);\n break; \n } else if (\"html\".equals(name)) {\n transition(HtmlTreeBuilderState.BeforeHead);\n break; \n } else if (last) {\n transition(HtmlTreeBuilderState.InBody);\n break; \n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-45"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-45"}} {"sample_uid": "defects4j_function_repair::Compress-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public long readBits(final int count) throws IOException {\n if (count < 0 || count > MAXIMUM_CACHE_SIZE) {\n throw new IllegalArgumentException(\"count must not be negative or greater than \" + MAXIMUM_CACHE_SIZE);\n }\n while (bitsCachedSize < count) {\n final long nextByte = in.read();\n if (nextByte < 0) {\n return nextByte;\n }\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsCached |= (nextByte << bitsCachedSize);\n } else {\n bitsCached <<= 8;\n bitsCached |= nextByte;\n }\n bitsCachedSize += 8;\n }\n final long bitsOut;\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsOut = (bitsCached & MASKS[count]);\n bitsCached >>>= count;\n } else {\n bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];\n }\n bitsCachedSize -= count;\n return bitsOut;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public long readBits(final int count) throws IOException {\n if (count < 0 || count > MAXIMUM_CACHE_SIZE) {\n throw new IllegalArgumentException(\"count must not be negative or greater than \" + MAXIMUM_CACHE_SIZE);\n }\n while (bitsCachedSize < count) {\n final long nextByte = in.read();\n if (nextByte < 0) {\n return nextByte;\n }\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsCached |= (nextByte << bitsCachedSize);\n } else {\n bitsCached <<= 8;\n bitsCached |= nextByte;\n }\n bitsCachedSize += 8;\n }\n final long bitsOut;\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsOut = (bitsCached & MASKS[count]);\n bitsCached >>>= count;\n } else {\n bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];\n }\n bitsCachedSize -= count;\n return bitsOut;\n }\n"}, "reference": " public long readBits(final int count) throws IOException {\n if (count < 0 || count > MAXIMUM_CACHE_SIZE) {\n throw new IllegalArgumentException(\"count must not be negative or greater than \" + MAXIMUM_CACHE_SIZE);\n }\n while (bitsCachedSize < count && bitsCachedSize < 57) {\n final long nextByte = in.read();\n if (nextByte < 0) {\n return nextByte;\n }\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsCached |= (nextByte << bitsCachedSize);\n } else {\n bitsCached <<= 8;\n bitsCached |= nextByte;\n }\n bitsCachedSize += 8;\n }\n int overflowBits = 0;\n long overflow = 0l;\n if (bitsCachedSize < count) {\n int bitsToAddCount = count - bitsCachedSize;\n overflowBits = 8 - bitsToAddCount;\n final long nextByte = in.read();\n if (nextByte < 0) {\n return nextByte;\n }\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n long bitsToAdd = nextByte & MASKS[bitsToAddCount];\n bitsCached |= (bitsToAdd << bitsCachedSize);\n overflow = (nextByte >>> bitsToAddCount) & MASKS[overflowBits];\n } else {\n bitsCached <<= bitsToAddCount;\n long bitsToAdd = (nextByte >>> (overflowBits)) & MASKS[bitsToAddCount];\n bitsCached |= bitsToAdd;\n overflow = nextByte & MASKS[overflowBits];\n }\n bitsCachedSize = count;\n }\n final long bitsOut;\n if (overflowBits == 0) {\n if (byteOrder == ByteOrder.LITTLE_ENDIAN) {\n bitsOut = (bitsCached & MASKS[count]);\n bitsCached >>>= count;\n } else {\n bitsOut = (bitsCached >> (bitsCachedSize - count)) & MASKS[count];\n }\n bitsCachedSize -= count;\n } else {\n bitsOut = bitsCached & MASKS[count];\n bitsCached = overflow;\n bitsCachedSize = overflowBits;\n }\n return bitsOut;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-40"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-39", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n p.skipChildren();\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n p.skipChildren();\n return null;\n }\n"}, "reference": " public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException\n {\n if (p.hasToken(JsonToken.FIELD_NAME)) {\n while (true) {\n JsonToken t = p.nextToken();\n if ((t == null) || (t == JsonToken.END_OBJECT)) {\n break;\n }\n p.skipChildren();\n }\n } else {\n p.skipChildren();\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-39"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-39"}} {"sample_uid": "defects4j_function_repair::Closure-117", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n String getReadableJSTypeName(Node n, boolean dereference) {\n if (n.isGetProp()) {\n ObjectType objectType = getJSType(n.getFirstChild()).dereference();\n if (objectType != null) {\n String propName = n.getLastChild().getString();\n if (objectType.getConstructor() != null &&\n objectType.getConstructor().isInterface()) {\n objectType = FunctionType.getTopDefiningInterface(\n objectType, propName);\n } else {\n while (objectType != null && !objectType.hasOwnProperty(propName)) {\n objectType = objectType.getImplicitPrototype();\n }\n }\n if (objectType != null &&\n (objectType.getConstructor() != null ||\n objectType.isFunctionPrototypeType())) {\n return objectType.toString() + \".\" + propName;\n }\n }\n }\n JSType type = getJSType(n);\n if (dereference) {\n ObjectType dereferenced = type.dereference();\n if (dereferenced != null) {\n type = dereferenced;\n }\n }\n if (type.isFunctionPrototypeType() ||\n (type.toObjectType() != null &&\n type.toObjectType().getConstructor() != null)) {\n return type.toString();\n }\n String qualifiedName = n.getQualifiedName();\n if (qualifiedName != null) {\n return qualifiedName;\n } else if (type.isFunctionType()) {\n return \"function\";\n } else {\n return type.toString();\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " String getReadableJSTypeName(Node n, boolean dereference) {\n if (n.isGetProp()) {\n ObjectType objectType = getJSType(n.getFirstChild()).dereference();\n if (objectType != null) {\n String propName = n.getLastChild().getString();\n if (objectType.getConstructor() != null &&\n objectType.getConstructor().isInterface()) {\n objectType = FunctionType.getTopDefiningInterface(\n objectType, propName);\n } else {\n while (objectType != null && !objectType.hasOwnProperty(propName)) {\n objectType = objectType.getImplicitPrototype();\n }\n }\n if (objectType != null &&\n (objectType.getConstructor() != null ||\n objectType.isFunctionPrototypeType())) {\n return objectType.toString() + \".\" + propName;\n }\n }\n }\n JSType type = getJSType(n);\n if (dereference) {\n ObjectType dereferenced = type.dereference();\n if (dereferenced != null) {\n type = dereferenced;\n }\n }\n if (type.isFunctionPrototypeType() ||\n (type.toObjectType() != null &&\n type.toObjectType().getConstructor() != null)) {\n return type.toString();\n }\n String qualifiedName = n.getQualifiedName();\n if (qualifiedName != null) {\n return qualifiedName;\n } else if (type.isFunctionType()) {\n return \"function\";\n } else {\n return type.toString();\n }\n }\n"}, "reference": " String getReadableJSTypeName(Node n, boolean dereference) {\n JSType type = getJSType(n);\n if (dereference) {\n ObjectType dereferenced = type.dereference();\n if (dereferenced != null) {\n type = dereferenced;\n }\n }\n if (type.isFunctionPrototypeType() ||\n (type.toObjectType() != null &&\n type.toObjectType().getConstructor() != null)) {\n return type.toString();\n }\n if (n.isGetProp()) {\n ObjectType objectType = getJSType(n.getFirstChild()).dereference();\n if (objectType != null) {\n String propName = n.getLastChild().getString();\n if (objectType.getConstructor() != null &&\n objectType.getConstructor().isInterface()) {\n objectType = FunctionType.getTopDefiningInterface(\n objectType, propName);\n } else {\n while (objectType != null && !objectType.hasOwnProperty(propName)) {\n objectType = objectType.getImplicitPrototype();\n }\n }\n if (objectType != null &&\n (objectType.getConstructor() != null ||\n objectType.isFunctionPrototypeType())) {\n return objectType.toString() + \".\" + propName;\n }\n }\n }\n String qualifiedName = n.getQualifiedName();\n if (qualifiedName != null) {\n return qualifiedName;\n } else if (type.isFunctionType()) {\n return \"function\";\n } else {\n return type.toString();\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-117"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-117"}} {"sample_uid": "defects4j_function_repair::Closure-130", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void inlineAliases(GlobalNamespace namespace) {\n Deque workList = new ArrayDeque(namespace.getNameForest());\n while (!workList.isEmpty()) {\n Name name = workList.pop();\n if (name.type == Name.Type.GET || name.type == Name.Type.SET) {\n continue;\n }\n if (name.globalSets == 1 && name.localSets == 0 &&\n name.aliasingGets > 0) {\n List refs = Lists.newArrayList(name.getRefs());\n for (Ref ref : refs) {\n if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {\n if (inlineAliasIfPossible(ref, namespace)) {\n name.removeRef(ref);\n }\n }\n }\n }\n if ((name.type == Name.Type.OBJECTLIT ||\n name.type == Name.Type.FUNCTION) &&\n name.aliasingGets == 0 && name.props != null) {\n workList.addAll(name.props);\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void inlineAliases(GlobalNamespace namespace) {\n Deque workList = new ArrayDeque(namespace.getNameForest());\n while (!workList.isEmpty()) {\n Name name = workList.pop();\n if (name.type == Name.Type.GET || name.type == Name.Type.SET) {\n continue;\n }\n if (name.globalSets == 1 && name.localSets == 0 &&\n name.aliasingGets > 0) {\n List refs = Lists.newArrayList(name.getRefs());\n for (Ref ref : refs) {\n if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {\n if (inlineAliasIfPossible(ref, namespace)) {\n name.removeRef(ref);\n }\n }\n }\n }\n if ((name.type == Name.Type.OBJECTLIT ||\n name.type == Name.Type.FUNCTION) &&\n name.aliasingGets == 0 && name.props != null) {\n workList.addAll(name.props);\n }\n }\n }\n"}, "reference": " private void inlineAliases(GlobalNamespace namespace) {\n Deque workList = new ArrayDeque(namespace.getNameForest());\n while (!workList.isEmpty()) {\n Name name = workList.pop();\n if (name.type == Name.Type.GET || name.type == Name.Type.SET) {\n continue;\n }\n if (!name.inExterns && name.globalSets == 1 && name.localSets == 0 &&\n name.aliasingGets > 0) {\n List refs = Lists.newArrayList(name.getRefs());\n for (Ref ref : refs) {\n if (ref.type == Type.ALIASING_GET && ref.scope.isLocal()) {\n if (inlineAliasIfPossible(ref, namespace)) {\n name.removeRef(ref);\n }\n }\n }\n }\n if ((name.type == Name.Type.OBJECTLIT ||\n name.type == Name.Type.FUNCTION) &&\n name.aliasingGets == 0 && name.props != null) {\n workList.addAll(name.props);\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-130"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-130"}} {"sample_uid": "defects4j_function_repair::Gson-5", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Date parse(String date, ParsePosition pos) throws ParseException {\n Exception fail = null;\n try {\n int offset = pos.getIndex();\n int year = parseInt(date, offset, offset += 4);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int month = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int day = parseInt(date, offset, offset += 2);\n int hour = 0;\n int minutes = 0;\n int seconds = 0;\n int milliseconds = 0; \n boolean hasT = checkOffset(date, offset, 'T');\n if (!hasT && (date.length() <= offset)) {\n Calendar calendar = new GregorianCalendar(year, month - 1, day);\n pos.setIndex(offset);\n return calendar.getTime();\n }\n if (hasT) {\n hour = parseInt(date, offset += 1, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n minutes = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n if (date.length() > offset) {\n char c = date.charAt(offset);\n if (c != 'Z' && c != '+' && c != '-') {\n seconds = parseInt(date, offset, offset += 2);\n if (seconds > 59 && seconds < 63) seconds = 59; \n if (checkOffset(date, offset, '.')) {\n offset += 1;\n int endOffset = indexOfNonDigit(date, offset + 1); \n int parseEndOffset = Math.min(endOffset, offset + 3); \n int fraction = parseInt(date, offset, parseEndOffset);\n switch (parseEndOffset - offset) { \n case 2:\n milliseconds = fraction * 10;\n break;\n case 1:\n milliseconds = fraction * 100;\n break;\n default:\n milliseconds = fraction;\n }\n offset = endOffset;\n }\n }\n }\n }\n if (date.length() <= offset) {\n throw new IllegalArgumentException(\"No time zone indicator\");\n }\n TimeZone timezone = null;\n char timezoneIndicator = date.charAt(offset);\n if (timezoneIndicator == 'Z') {\n timezone = TIMEZONE_UTC;\n offset += 1;\n } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {\n String timezoneOffset = date.substring(offset);\n offset += timezoneOffset.length();\n if (\"+0000\".equals(timezoneOffset) || \"+00:00\".equals(timezoneOffset)) {\n timezone = TIMEZONE_UTC;\n } else {\n String timezoneId = \"GMT\" + timezoneOffset;\n timezone = TimeZone.getTimeZone(timezoneId);\n String act = timezone.getID();\n if (!act.equals(timezoneId)) {\n String cleaned = act.replace(\":\", \"\");\n if (!cleaned.equals(timezoneId)) {\n throw new IndexOutOfBoundsException(\"Mismatching time zone indicator: \"+timezoneId+\" given, resolves to \"\n +timezone.getID());\n }\n }\n }\n } else {\n throw new IndexOutOfBoundsException(\"Invalid time zone indicator '\" + timezoneIndicator+\"'\");\n }\n Calendar calendar = new GregorianCalendar(timezone);\n calendar.setLenient(false);\n calendar.set(Calendar.YEAR, year);\n calendar.set(Calendar.MONTH, month - 1);\n calendar.set(Calendar.DAY_OF_MONTH, day);\n calendar.set(Calendar.HOUR_OF_DAY, hour);\n calendar.set(Calendar.MINUTE, minutes);\n calendar.set(Calendar.SECOND, seconds);\n calendar.set(Calendar.MILLISECOND, milliseconds);\n pos.setIndex(offset);\n return calendar.getTime();\n } catch (IndexOutOfBoundsException e) {\n fail = e;\n } catch (NumberFormatException e) {\n fail = e;\n } catch (IllegalArgumentException e) {\n fail = e;\n }\n String input = (date == null) ? null : ('\"' + date + \"'\");\n String msg = fail.getMessage();\n if (msg == null || msg.isEmpty()) {\n msg = \"(\"+fail.getClass().getName()+\")\";\n }\n ParseException ex = new ParseException(\"Failed to parse date [\" + input + \"]: \" + msg, pos.getIndex());\n ex.initCause(fail);\n throw ex;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Date parse(String date, ParsePosition pos) throws ParseException {\n Exception fail = null;\n try {\n int offset = pos.getIndex();\n int year = parseInt(date, offset, offset += 4);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int month = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int day = parseInt(date, offset, offset += 2);\n int hour = 0;\n int minutes = 0;\n int seconds = 0;\n int milliseconds = 0; \n boolean hasT = checkOffset(date, offset, 'T');\n if (!hasT && (date.length() <= offset)) {\n Calendar calendar = new GregorianCalendar(year, month - 1, day);\n pos.setIndex(offset);\n return calendar.getTime();\n }\n if (hasT) {\n hour = parseInt(date, offset += 1, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n minutes = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n if (date.length() > offset) {\n char c = date.charAt(offset);\n if (c != 'Z' && c != '+' && c != '-') {\n seconds = parseInt(date, offset, offset += 2);\n if (seconds > 59 && seconds < 63) seconds = 59; \n if (checkOffset(date, offset, '.')) {\n offset += 1;\n int endOffset = indexOfNonDigit(date, offset + 1); \n int parseEndOffset = Math.min(endOffset, offset + 3); \n int fraction = parseInt(date, offset, parseEndOffset);\n switch (parseEndOffset - offset) { \n case 2:\n milliseconds = fraction * 10;\n break;\n case 1:\n milliseconds = fraction * 100;\n break;\n default:\n milliseconds = fraction;\n }\n offset = endOffset;\n }\n }\n }\n }\n if (date.length() <= offset) {\n throw new IllegalArgumentException(\"No time zone indicator\");\n }\n TimeZone timezone = null;\n char timezoneIndicator = date.charAt(offset);\n if (timezoneIndicator == 'Z') {\n timezone = TIMEZONE_UTC;\n offset += 1;\n } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {\n String timezoneOffset = date.substring(offset);\n offset += timezoneOffset.length();\n if (\"+0000\".equals(timezoneOffset) || \"+00:00\".equals(timezoneOffset)) {\n timezone = TIMEZONE_UTC;\n } else {\n String timezoneId = \"GMT\" + timezoneOffset;\n timezone = TimeZone.getTimeZone(timezoneId);\n String act = timezone.getID();\n if (!act.equals(timezoneId)) {\n String cleaned = act.replace(\":\", \"\");\n if (!cleaned.equals(timezoneId)) {\n throw new IndexOutOfBoundsException(\"Mismatching time zone indicator: \"+timezoneId+\" given, resolves to \"\n +timezone.getID());\n }\n }\n }\n } else {\n throw new IndexOutOfBoundsException(\"Invalid time zone indicator '\" + timezoneIndicator+\"'\");\n }\n Calendar calendar = new GregorianCalendar(timezone);\n calendar.setLenient(false);\n calendar.set(Calendar.YEAR, year);\n calendar.set(Calendar.MONTH, month - 1);\n calendar.set(Calendar.DAY_OF_MONTH, day);\n calendar.set(Calendar.HOUR_OF_DAY, hour);\n calendar.set(Calendar.MINUTE, minutes);\n calendar.set(Calendar.SECOND, seconds);\n calendar.set(Calendar.MILLISECOND, milliseconds);\n pos.setIndex(offset);\n return calendar.getTime();\n } catch (IndexOutOfBoundsException e) {\n fail = e;\n } catch (NumberFormatException e) {\n fail = e;\n } catch (IllegalArgumentException e) {\n fail = e;\n }\n String input = (date == null) ? null : ('\"' + date + \"'\");\n String msg = fail.getMessage();\n if (msg == null || msg.isEmpty()) {\n msg = \"(\"+fail.getClass().getName()+\")\";\n }\n ParseException ex = new ParseException(\"Failed to parse date [\" + input + \"]: \" + msg, pos.getIndex());\n ex.initCause(fail);\n throw ex;\n }\n"}, "reference": " public static Date parse(String date, ParsePosition pos) throws ParseException {\n Exception fail = null;\n try {\n int offset = pos.getIndex();\n int year = parseInt(date, offset, offset += 4);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int month = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, '-')) {\n offset += 1;\n }\n int day = parseInt(date, offset, offset += 2);\n int hour = 0;\n int minutes = 0;\n int seconds = 0;\n int milliseconds = 0; \n boolean hasT = checkOffset(date, offset, 'T');\n if (!hasT && (date.length() <= offset)) {\n Calendar calendar = new GregorianCalendar(year, month - 1, day);\n pos.setIndex(offset);\n return calendar.getTime();\n }\n if (hasT) {\n hour = parseInt(date, offset += 1, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n minutes = parseInt(date, offset, offset += 2);\n if (checkOffset(date, offset, ':')) {\n offset += 1;\n }\n if (date.length() > offset) {\n char c = date.charAt(offset);\n if (c != 'Z' && c != '+' && c != '-') {\n seconds = parseInt(date, offset, offset += 2);\n if (seconds > 59 && seconds < 63) seconds = 59; \n if (checkOffset(date, offset, '.')) {\n offset += 1;\n int endOffset = indexOfNonDigit(date, offset + 1); \n int parseEndOffset = Math.min(endOffset, offset + 3); \n int fraction = parseInt(date, offset, parseEndOffset);\n switch (parseEndOffset - offset) { \n case 2:\n milliseconds = fraction * 10;\n break;\n case 1:\n milliseconds = fraction * 100;\n break;\n default:\n milliseconds = fraction;\n }\n offset = endOffset;\n }\n }\n }\n }\n if (date.length() <= offset) {\n throw new IllegalArgumentException(\"No time zone indicator\");\n }\n TimeZone timezone = null;\n char timezoneIndicator = date.charAt(offset);\n if (timezoneIndicator == 'Z') {\n timezone = TIMEZONE_UTC;\n offset += 1;\n } else if (timezoneIndicator == '+' || timezoneIndicator == '-') {\n String timezoneOffset = date.substring(offset);\n timezoneOffset = timezoneOffset.length() >= 5 ? timezoneOffset : timezoneOffset + \"00\";\n offset += timezoneOffset.length();\n if (\"+0000\".equals(timezoneOffset) || \"+00:00\".equals(timezoneOffset)) {\n timezone = TIMEZONE_UTC;\n } else {\n String timezoneId = \"GMT\" + timezoneOffset;\n timezone = TimeZone.getTimeZone(timezoneId);\n String act = timezone.getID();\n if (!act.equals(timezoneId)) {\n String cleaned = act.replace(\":\", \"\");\n if (!cleaned.equals(timezoneId)) {\n throw new IndexOutOfBoundsException(\"Mismatching time zone indicator: \"+timezoneId+\" given, resolves to \"\n +timezone.getID());\n }\n }\n }\n } else {\n throw new IndexOutOfBoundsException(\"Invalid time zone indicator '\" + timezoneIndicator+\"'\");\n }\n Calendar calendar = new GregorianCalendar(timezone);\n calendar.setLenient(false);\n calendar.set(Calendar.YEAR, year);\n calendar.set(Calendar.MONTH, month - 1);\n calendar.set(Calendar.DAY_OF_MONTH, day);\n calendar.set(Calendar.HOUR_OF_DAY, hour);\n calendar.set(Calendar.MINUTE, minutes);\n calendar.set(Calendar.SECOND, seconds);\n calendar.set(Calendar.MILLISECOND, milliseconds);\n pos.setIndex(offset);\n return calendar.getTime();\n } catch (IndexOutOfBoundsException e) {\n fail = e;\n } catch (NumberFormatException e) {\n fail = e;\n } catch (IllegalArgumentException e) {\n fail = e;\n }\n String input = (date == null) ? null : ('\"' + date + \"'\");\n String msg = fail.getMessage();\n if (msg == null || msg.isEmpty()) {\n msg = \"(\"+fail.getClass().getName()+\")\";\n }\n ParseException ex = new ParseException(\"Failed to parse date [\" + input + \"]: \" + msg, pos.getIndex());\n ex.initCause(fail);\n throw ex;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-5"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-5"}} {"sample_uid": "defects4j_function_repair::Closure-131", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static boolean isJSIdentifier(String s) {\n int length = s.length();\n if (length == 0 ||\n !Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < length; i++) {\n if (\n !Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static boolean isJSIdentifier(String s) {\n int length = s.length();\n if (length == 0 ||\n !Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < length; i++) {\n if (\n !Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n"}, "reference": " public static boolean isJSIdentifier(String s) {\n int length = s.length();\n if (length == 0 ||\n Character.isIdentifierIgnorable(s.charAt(0)) ||\n !Character.isJavaIdentifierStart(s.charAt(0))) {\n return false;\n }\n for (int i = 1; i < length; i++) {\n if (Character.isIdentifierIgnorable(s.charAt(i)) ||\n !Character.isJavaIdentifierPart(s.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-131"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-131"}} {"sample_uid": "defects4j_function_repair::Closure-95", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n void defineSlot(Node n, Node parent, JSType type, boolean inferred) {\n Preconditions.checkArgument(inferred || type != null);\n boolean shouldDeclareOnGlobalThis = false;\n if (n.getType() == Token.NAME) {\n Preconditions.checkArgument(\n parent.getType() == Token.FUNCTION ||\n parent.getType() == Token.VAR ||\n parent.getType() == Token.LP ||\n parent.getType() == Token.CATCH);\n shouldDeclareOnGlobalThis = scope.isGlobal() &&\n (parent.getType() == Token.VAR ||\n parent.getType() == Token.FUNCTION);\n } else {\n Preconditions.checkArgument(\n n.getType() == Token.GETPROP &&\n (parent.getType() == Token.ASSIGN ||\n parent.getType() == Token.EXPR_RESULT));\n }\n String variableName = n.getQualifiedName();\n Preconditions.checkArgument(!variableName.isEmpty());\n Scope scopeToDeclareIn = scope;\n if (scopeToDeclareIn.isDeclared(variableName, false)) {\n Var oldVar = scopeToDeclareIn.getVar(variableName);\n validator.expectUndeclaredVariable(\n sourceName, n, parent, oldVar, variableName, type);\n } else {\n if (!inferred) {\n setDeferredType(n, type);\n }\n CompilerInput input = compiler.getInput(sourceName);\n scopeToDeclareIn.declare(variableName, n, type, input, inferred);\n if (shouldDeclareOnGlobalThis) {\n ObjectType globalThis =\n typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);\n boolean isExtern = input.isExtern();\n if (inferred) {\n globalThis.defineInferredProperty(variableName,\n type == null ?\n getNativeType(JSTypeNative.NO_TYPE) :\n type,\n isExtern);\n } else {\n globalThis.defineDeclaredProperty(variableName, type, isExtern);\n }\n }\n if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) {\n FunctionType fnType = (FunctionType) type;\n if (fnType.isConstructor() || fnType.isInterface()) {\n FunctionType superClassCtor = fnType.getSuperClassConstructor();\n scopeToDeclareIn.declare(variableName + \".prototype\", n,\n fnType.getPrototype(), compiler.getInput(sourceName),\n superClassCtor == null ||\n superClassCtor.getInstanceType().equals(\n getNativeType(OBJECT_TYPE)));\n }\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " void defineSlot(Node n, Node parent, JSType type, boolean inferred) {\n Preconditions.checkArgument(inferred || type != null);\n boolean shouldDeclareOnGlobalThis = false;\n if (n.getType() == Token.NAME) {\n Preconditions.checkArgument(\n parent.getType() == Token.FUNCTION ||\n parent.getType() == Token.VAR ||\n parent.getType() == Token.LP ||\n parent.getType() == Token.CATCH);\n shouldDeclareOnGlobalThis = scope.isGlobal() &&\n (parent.getType() == Token.VAR ||\n parent.getType() == Token.FUNCTION);\n } else {\n Preconditions.checkArgument(\n n.getType() == Token.GETPROP &&\n (parent.getType() == Token.ASSIGN ||\n parent.getType() == Token.EXPR_RESULT));\n }\n String variableName = n.getQualifiedName();\n Preconditions.checkArgument(!variableName.isEmpty());\n Scope scopeToDeclareIn = scope;\n if (scopeToDeclareIn.isDeclared(variableName, false)) {\n Var oldVar = scopeToDeclareIn.getVar(variableName);\n validator.expectUndeclaredVariable(\n sourceName, n, parent, oldVar, variableName, type);\n } else {\n if (!inferred) {\n setDeferredType(n, type);\n }\n CompilerInput input = compiler.getInput(sourceName);\n scopeToDeclareIn.declare(variableName, n, type, input, inferred);\n if (shouldDeclareOnGlobalThis) {\n ObjectType globalThis =\n typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);\n boolean isExtern = input.isExtern();\n if (inferred) {\n globalThis.defineInferredProperty(variableName,\n type == null ?\n getNativeType(JSTypeNative.NO_TYPE) :\n type,\n isExtern);\n } else {\n globalThis.defineDeclaredProperty(variableName, type, isExtern);\n }\n }\n if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) {\n FunctionType fnType = (FunctionType) type;\n if (fnType.isConstructor() || fnType.isInterface()) {\n FunctionType superClassCtor = fnType.getSuperClassConstructor();\n scopeToDeclareIn.declare(variableName + \".prototype\", n,\n fnType.getPrototype(), compiler.getInput(sourceName),\n superClassCtor == null ||\n superClassCtor.getInstanceType().equals(\n getNativeType(OBJECT_TYPE)));\n }\n }\n }\n }\n"}, "reference": " void defineSlot(Node n, Node parent, JSType type, boolean inferred) {\n Preconditions.checkArgument(inferred || type != null);\n boolean shouldDeclareOnGlobalThis = false;\n if (n.getType() == Token.NAME) {\n Preconditions.checkArgument(\n parent.getType() == Token.FUNCTION ||\n parent.getType() == Token.VAR ||\n parent.getType() == Token.LP ||\n parent.getType() == Token.CATCH);\n shouldDeclareOnGlobalThis = scope.isGlobal() &&\n (parent.getType() == Token.VAR ||\n parent.getType() == Token.FUNCTION);\n } else {\n Preconditions.checkArgument(\n n.getType() == Token.GETPROP &&\n (parent.getType() == Token.ASSIGN ||\n parent.getType() == Token.EXPR_RESULT));\n }\n String variableName = n.getQualifiedName();\n Preconditions.checkArgument(!variableName.isEmpty());\n Scope scopeToDeclareIn = scope;\n if (n.getType() == Token.GETPROP && !scope.isGlobal() &&\n isQnameRootedInGlobalScope(n)) {\n Scope globalScope = scope.getGlobalScope();\n if (!globalScope.isDeclared(variableName, false)) {\n scopeToDeclareIn = scope.getGlobalScope();\n }\n }\n if (scopeToDeclareIn.isDeclared(variableName, false)) {\n Var oldVar = scopeToDeclareIn.getVar(variableName);\n validator.expectUndeclaredVariable(\n sourceName, n, parent, oldVar, variableName, type);\n } else {\n if (!inferred) {\n setDeferredType(n, type);\n }\n CompilerInput input = compiler.getInput(sourceName);\n scopeToDeclareIn.declare(variableName, n, type, input, inferred);\n if (shouldDeclareOnGlobalThis) {\n ObjectType globalThis =\n typeRegistry.getNativeObjectType(JSTypeNative.GLOBAL_THIS);\n boolean isExtern = input.isExtern();\n if (inferred) {\n globalThis.defineInferredProperty(variableName,\n type == null ?\n getNativeType(JSTypeNative.NO_TYPE) :\n type,\n isExtern);\n } else {\n globalThis.defineDeclaredProperty(variableName, type, isExtern);\n }\n }\n if (scopeToDeclareIn.isGlobal() && type instanceof FunctionType) {\n FunctionType fnType = (FunctionType) type;\n if (fnType.isConstructor() || fnType.isInterface()) {\n FunctionType superClassCtor = fnType.getSuperClassConstructor();\n scopeToDeclareIn.declare(variableName + \".prototype\", n,\n fnType.getPrototype(), compiler.getInput(sourceName),\n superClassCtor == null ||\n superClassCtor.getInstanceType().equals(\n getNativeType(OBJECT_TYPE)));\n }\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-95"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-95"}} {"sample_uid": "defects4j_function_repair::Closure-78", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node performArithmeticOp(int opType, Node left, Node right) {\n if (opType == Token.ADD\n && (NodeUtil.mayBeString(left, false)\n || NodeUtil.mayBeString(right, false))) {\n return null;\n }\n double result;\n Double lValObj = NodeUtil.getNumberValue(left);\n if (lValObj == null) {\n return null;\n }\n Double rValObj = NodeUtil.getNumberValue(right);\n if (rValObj == null) {\n return null;\n }\n double lval = lValObj;\n double rval = rValObj;\n switch (opType) {\n case Token.BITAND:\n result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);\n break;\n case Token.BITOR:\n result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);\n break;\n case Token.BITXOR:\n result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);\n break;\n case Token.ADD:\n result = lval + rval;\n break;\n case Token.SUB:\n result = lval - rval;\n break;\n case Token.MUL:\n result = lval * rval;\n break;\n case Token.MOD:\n if (rval == 0) {\n error(DiagnosticType.error(\"JSC_DIVIDE_BY_0_ERROR\", \"Divide by 0\"), right);\n return null;\n }\n result = lval % rval;\n break;\n case Token.DIV:\n if (rval == 0) {\n error(DiagnosticType.error(\"JSC_DIVIDE_BY_0_ERROR\", \"Divide by 0\"), right);\n return null;\n }\n result = lval / rval;\n break;\n default:\n throw new Error(\"Unexpected arithmetic operator\");\n }\n if (String.valueOf(result).length() <=\n String.valueOf(lval).length() + String.valueOf(rval).length() + 1 &&\n Math.abs(result) <= MAX_FOLD_NUMBER) {\n Node newNumber = Node.newNumber(result);\n return newNumber;\n } else if (Double.isNaN(result)) {\n return Node.newString(Token.NAME, \"NaN\");\n } else if (result == Double.POSITIVE_INFINITY) {\n return Node.newString(Token.NAME, \"Infinity\");\n } else if (result == Double.NEGATIVE_INFINITY) {\n return new Node(Token.NEG, Node.newString(Token.NAME, \"Infinity\"));\n }\n return null;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node performArithmeticOp(int opType, Node left, Node right) {\n if (opType == Token.ADD\n && (NodeUtil.mayBeString(left, false)\n || NodeUtil.mayBeString(right, false))) {\n return null;\n }\n double result;\n Double lValObj = NodeUtil.getNumberValue(left);\n if (lValObj == null) {\n return null;\n }\n Double rValObj = NodeUtil.getNumberValue(right);\n if (rValObj == null) {\n return null;\n }\n double lval = lValObj;\n double rval = rValObj;\n switch (opType) {\n case Token.BITAND:\n result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);\n break;\n case Token.BITOR:\n result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);\n break;\n case Token.BITXOR:\n result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);\n break;\n case Token.ADD:\n result = lval + rval;\n break;\n case Token.SUB:\n result = lval - rval;\n break;\n case Token.MUL:\n result = lval * rval;\n break;\n case Token.MOD:\n if (rval == 0) {\n error(DiagnosticType.error(\"JSC_DIVIDE_BY_0_ERROR\", \"Divide by 0\"), right);\n return null;\n }\n result = lval % rval;\n break;\n case Token.DIV:\n if (rval == 0) {\n error(DiagnosticType.error(\"JSC_DIVIDE_BY_0_ERROR\", \"Divide by 0\"), right);\n return null;\n }\n result = lval / rval;\n break;\n default:\n throw new Error(\"Unexpected arithmetic operator\");\n }\n if (String.valueOf(result).length() <=\n String.valueOf(lval).length() + String.valueOf(rval).length() + 1 &&\n Math.abs(result) <= MAX_FOLD_NUMBER) {\n Node newNumber = Node.newNumber(result);\n return newNumber;\n } else if (Double.isNaN(result)) {\n return Node.newString(Token.NAME, \"NaN\");\n } else if (result == Double.POSITIVE_INFINITY) {\n return Node.newString(Token.NAME, \"Infinity\");\n } else if (result == Double.NEGATIVE_INFINITY) {\n return new Node(Token.NEG, Node.newString(Token.NAME, \"Infinity\"));\n }\n return null;\n }\n"}, "reference": " private Node performArithmeticOp(int opType, Node left, Node right) {\n if (opType == Token.ADD\n && (NodeUtil.mayBeString(left, false)\n || NodeUtil.mayBeString(right, false))) {\n return null;\n }\n double result;\n Double lValObj = NodeUtil.getNumberValue(left);\n if (lValObj == null) {\n return null;\n }\n Double rValObj = NodeUtil.getNumberValue(right);\n if (rValObj == null) {\n return null;\n }\n double lval = lValObj;\n double rval = rValObj;\n switch (opType) {\n case Token.BITAND:\n result = ScriptRuntime.toInt32(lval) & ScriptRuntime.toInt32(rval);\n break;\n case Token.BITOR:\n result = ScriptRuntime.toInt32(lval) | ScriptRuntime.toInt32(rval);\n break;\n case Token.BITXOR:\n result = ScriptRuntime.toInt32(lval) ^ ScriptRuntime.toInt32(rval);\n break;\n case Token.ADD:\n result = lval + rval;\n break;\n case Token.SUB:\n result = lval - rval;\n break;\n case Token.MUL:\n result = lval * rval;\n break;\n case Token.MOD:\n if (rval == 0) {\n return null;\n }\n result = lval % rval;\n break;\n case Token.DIV:\n if (rval == 0) {\n return null;\n }\n result = lval / rval;\n break;\n default:\n throw new Error(\"Unexpected arithmetic operator\");\n }\n if (String.valueOf(result).length() <=\n String.valueOf(lval).length() + String.valueOf(rval).length() + 1 &&\n Math.abs(result) <= MAX_FOLD_NUMBER) {\n Node newNumber = Node.newNumber(result);\n return newNumber;\n } else if (Double.isNaN(result)) {\n return Node.newString(Token.NAME, \"NaN\");\n } else if (result == Double.POSITIVE_INFINITY) {\n return Node.newString(Token.NAME, \"Infinity\");\n } else if (result == Double.NEGATIVE_INFINITY) {\n return new Node(Token.NEG, Node.newString(Token.NAME, \"Infinity\"));\n }\n return null;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-78"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-78"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-27", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final ExternalTypeHandler ext = _externalTypeIdHandler.start();\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (ext.handlePropertyValue(p, ctxt, propName, buffer)) {\n ;\n } else {\n if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n continue; \n }\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken(); \n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n if (bean.getClass() != _beanType.getRawClass()) {\n throw ctxt.mappingException(\"Can not create polymorphic instances with unwrapped values\");\n }\n return ext.complete(p, ctxt, bean);\n }\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (ext.handlePropertyValue(p, ctxt, propName, null)) {\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n try {\n return ext.complete(p, ctxt, buffer, creator);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final ExternalTypeHandler ext = _externalTypeIdHandler.start();\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (ext.handlePropertyValue(p, ctxt, propName, buffer)) {\n ;\n } else {\n if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n continue; \n }\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken(); \n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n if (bean.getClass() != _beanType.getRawClass()) {\n throw ctxt.mappingException(\"Can not create polymorphic instances with unwrapped values\");\n }\n return ext.complete(p, ctxt, bean);\n }\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (ext.handlePropertyValue(p, ctxt, propName, null)) {\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n try {\n return ext.complete(p, ctxt, buffer, creator);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n }\n"}, "reference": " protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)\n throws IOException\n {\n final ExternalTypeHandler ext = _externalTypeIdHandler.start();\n final PropertyBasedCreator creator = _propertyBasedCreator;\n PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);\n TokenBuffer tokens = new TokenBuffer(p);\n tokens.writeStartObject();\n JsonToken t = p.getCurrentToken();\n for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {\n String propName = p.getCurrentName();\n p.nextToken(); \n SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);\n if (creatorProp != null) {\n if (ext.handlePropertyValue(p, ctxt, propName, null)) {\n ;\n } else {\n if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {\n t = p.nextToken(); \n Object bean;\n try {\n bean = creator.build(ctxt, buffer);\n } catch (Exception e) {\n wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);\n continue; \n }\n while (t == JsonToken.FIELD_NAME) {\n p.nextToken(); \n tokens.copyCurrentStructure(p);\n t = p.nextToken();\n }\n if (bean.getClass() != _beanType.getRawClass()) {\n throw ctxt.mappingException(\"Can not create polymorphic instances with unwrapped values\");\n }\n return ext.complete(p, ctxt, bean);\n }\n }\n continue;\n }\n if (buffer.readIdProperty(propName)) {\n continue;\n }\n SettableBeanProperty prop = _beanProperties.find(propName);\n if (prop != null) {\n buffer.bufferProperty(prop, prop.deserialize(p, ctxt));\n continue;\n }\n if (ext.handlePropertyValue(p, ctxt, propName, null)) {\n continue;\n }\n if (_ignorableProps != null && _ignorableProps.contains(propName)) {\n handleIgnoredProperty(p, ctxt, handledType(), propName);\n continue;\n }\n if (_anySetter != null) {\n buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));\n }\n }\n try {\n return ext.complete(p, ctxt, buffer, creator);\n } catch (Exception e) {\n wrapInstantiationProblem(e, ctxt);\n return null; \n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-27"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-27"}} {"sample_uid": "defects4j_function_repair::Math-31", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double evaluate(double x, double epsilon, int maxIterations) {\n final double small = 1e-50;\n double hPrev = getA(0, x);\n if (Precision.equals(hPrev, 0.0, small)) {\n hPrev = small;\n }\n int n = 1;\n double dPrev = 0.0;\n double p0 = 1.0;\n double q1 = 1.0;\n double cPrev = hPrev;\n double hN = hPrev;\n while (n < maxIterations) {\n final double a = getA(n, x);\n final double b = getB(n, x);\n double cN = a * hPrev + b * p0;\n double q2 = a * q1 + b * dPrev;\n if (Double.isInfinite(cN) || Double.isInfinite(q2)) {\n double scaleFactor = 1d;\n double lastScaleFactor = 1d;\n final int maxPower = 5;\n final double scale = FastMath.max(a,b);\n if (scale <= 0) { \n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x);\n }\n for (int i = 0; i < maxPower; i++) {\n lastScaleFactor = scaleFactor;\n scaleFactor *= scale;\n if (a != 0.0 && a > b) {\n cN = hPrev / lastScaleFactor + (b / scaleFactor * p0);\n q2 = q1 / lastScaleFactor + (b / scaleFactor * dPrev);\n } else if (b != 0) {\n cN = (a / scaleFactor * hPrev) + p0 / lastScaleFactor;\n q2 = (a / scaleFactor * q1) + dPrev / lastScaleFactor;\n }\n if (!(Double.isInfinite(cN) || Double.isInfinite(q2))) {\n break;\n }\n }\n }\n final double deltaN = cN / q2 / cPrev;\n hN = cPrev * deltaN;\n if (Double.isInfinite(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE,\n x);\n }\n if (Double.isNaN(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE,\n x);\n }\n if (FastMath.abs(deltaN - 1.0) < epsilon) {\n break;\n }\n dPrev = q1;\n cPrev = cN / q2;\n p0 = hPrev;\n hPrev = cN;\n q1 = q2;\n n++;\n }\n if (n >= maxIterations) {\n throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION,\n maxIterations, x);\n }\n return hN;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double evaluate(double x, double epsilon, int maxIterations) {\n final double small = 1e-50;\n double hPrev = getA(0, x);\n if (Precision.equals(hPrev, 0.0, small)) {\n hPrev = small;\n }\n int n = 1;\n double dPrev = 0.0;\n double p0 = 1.0;\n double q1 = 1.0;\n double cPrev = hPrev;\n double hN = hPrev;\n while (n < maxIterations) {\n final double a = getA(n, x);\n final double b = getB(n, x);\n double cN = a * hPrev + b * p0;\n double q2 = a * q1 + b * dPrev;\n if (Double.isInfinite(cN) || Double.isInfinite(q2)) {\n double scaleFactor = 1d;\n double lastScaleFactor = 1d;\n final int maxPower = 5;\n final double scale = FastMath.max(a,b);\n if (scale <= 0) { \n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x);\n }\n for (int i = 0; i < maxPower; i++) {\n lastScaleFactor = scaleFactor;\n scaleFactor *= scale;\n if (a != 0.0 && a > b) {\n cN = hPrev / lastScaleFactor + (b / scaleFactor * p0);\n q2 = q1 / lastScaleFactor + (b / scaleFactor * dPrev);\n } else if (b != 0) {\n cN = (a / scaleFactor * hPrev) + p0 / lastScaleFactor;\n q2 = (a / scaleFactor * q1) + dPrev / lastScaleFactor;\n }\n if (!(Double.isInfinite(cN) || Double.isInfinite(q2))) {\n break;\n }\n }\n }\n final double deltaN = cN / q2 / cPrev;\n hN = cPrev * deltaN;\n if (Double.isInfinite(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE,\n x);\n }\n if (Double.isNaN(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE,\n x);\n }\n if (FastMath.abs(deltaN - 1.0) < epsilon) {\n break;\n }\n dPrev = q1;\n cPrev = cN / q2;\n p0 = hPrev;\n hPrev = cN;\n q1 = q2;\n n++;\n }\n if (n >= maxIterations) {\n throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION,\n maxIterations, x);\n }\n return hN;\n }\n"}, "reference": " public double evaluate(double x, double epsilon, int maxIterations) {\n final double small = 1e-50;\n double hPrev = getA(0, x);\n if (Precision.equals(hPrev, 0.0, small)) {\n hPrev = small;\n }\n int n = 1;\n double dPrev = 0.0;\n double cPrev = hPrev;\n double hN = hPrev;\n while (n < maxIterations) {\n final double a = getA(n, x);\n final double b = getB(n, x);\n double dN = a + b * dPrev;\n if (Precision.equals(dN, 0.0, small)) {\n dN = small;\n }\n double cN = a + b / cPrev;\n if (Precision.equals(cN, 0.0, small)) {\n cN = small;\n }\n dN = 1 / dN;\n final double deltaN = cN * dN;\n hN = hPrev * deltaN;\n if (Double.isInfinite(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE,\n x);\n }\n if (Double.isNaN(hN)) {\n throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE,\n x);\n }\n if (FastMath.abs(deltaN - 1.0) < epsilon) {\n break;\n }\n dPrev = dN;\n cPrev = cN;\n hPrev = hN;\n n++;\n }\n if (n >= maxIterations) {\n throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION,\n maxIterations, x);\n }\n return hN;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-31"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-31"}} {"sample_uid": "defects4j_function_repair::Chart-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected Size2D arrangeFF(BlockContainer container, Graphics2D g2,\n RectangleConstraint constraint) {\n double[] w = new double[5];\n double[] h = new double[5];\n w[0] = constraint.getWidth();\n if (this.topBlock != null) {\n RectangleConstraint c1 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0,\n new Range(0.0, constraint.getHeight()),\n LengthConstraintType.RANGE);\n Size2D size = this.topBlock.arrange(g2, c1);\n h[0] = size.height;\n }\n w[1] = w[0];\n if (this.bottomBlock != null) {\n RectangleConstraint c2 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0, new Range(0.0,\n constraint.getHeight() - h[0]), LengthConstraintType.RANGE);\n Size2D size = this.bottomBlock.arrange(g2, c2);\n h[1] = size.height;\n }\n h[2] = constraint.getHeight() - h[1] - h[0];\n if (this.leftBlock != null) {\n RectangleConstraint c3 = new RectangleConstraint(0.0,\n new Range(0.0, constraint.getWidth()),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.leftBlock.arrange(g2, c3);\n w[2] = size.width;\n }\n h[3] = h[2];\n if (this.rightBlock != null) {\n RectangleConstraint c4 = new RectangleConstraint(0.0,\n new Range(0.0, constraint.getWidth() - w[2]),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.rightBlock.arrange(g2, c4);\n w[3] = size.width;\n }\n h[4] = h[2];\n w[4] = constraint.getWidth() - w[3] - w[2];\n RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]);\n if (this.centerBlock != null) {\n this.centerBlock.arrange(g2, c5);\n }\n if (this.topBlock != null) {\n this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0],\n h[0]));\n }\n if (this.bottomBlock != null) {\n this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2],\n w[1], h[1]));\n }\n if (this.leftBlock != null) {\n this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2],\n h[2]));\n }\n if (this.rightBlock != null) {\n this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0],\n w[3], h[3]));\n }\n if (this.centerBlock != null) {\n this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4],\n h[4]));\n }\n return new Size2D(constraint.getWidth(), constraint.getHeight());\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected Size2D arrangeFF(BlockContainer container, Graphics2D g2,\n RectangleConstraint constraint) {\n double[] w = new double[5];\n double[] h = new double[5];\n w[0] = constraint.getWidth();\n if (this.topBlock != null) {\n RectangleConstraint c1 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0,\n new Range(0.0, constraint.getHeight()),\n LengthConstraintType.RANGE);\n Size2D size = this.topBlock.arrange(g2, c1);\n h[0] = size.height;\n }\n w[1] = w[0];\n if (this.bottomBlock != null) {\n RectangleConstraint c2 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0, new Range(0.0,\n constraint.getHeight() - h[0]), LengthConstraintType.RANGE);\n Size2D size = this.bottomBlock.arrange(g2, c2);\n h[1] = size.height;\n }\n h[2] = constraint.getHeight() - h[1] - h[0];\n if (this.leftBlock != null) {\n RectangleConstraint c3 = new RectangleConstraint(0.0,\n new Range(0.0, constraint.getWidth()),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.leftBlock.arrange(g2, c3);\n w[2] = size.width;\n }\n h[3] = h[2];\n if (this.rightBlock != null) {\n RectangleConstraint c4 = new RectangleConstraint(0.0,\n new Range(0.0, constraint.getWidth() - w[2]),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.rightBlock.arrange(g2, c4);\n w[3] = size.width;\n }\n h[4] = h[2];\n w[4] = constraint.getWidth() - w[3] - w[2];\n RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]);\n if (this.centerBlock != null) {\n this.centerBlock.arrange(g2, c5);\n }\n if (this.topBlock != null) {\n this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0],\n h[0]));\n }\n if (this.bottomBlock != null) {\n this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2],\n w[1], h[1]));\n }\n if (this.leftBlock != null) {\n this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2],\n h[2]));\n }\n if (this.rightBlock != null) {\n this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0],\n w[3], h[3]));\n }\n if (this.centerBlock != null) {\n this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4],\n h[4]));\n }\n return new Size2D(constraint.getWidth(), constraint.getHeight());\n }\n"}, "reference": " protected Size2D arrangeFF(BlockContainer container, Graphics2D g2,\n RectangleConstraint constraint) {\n double[] w = new double[5];\n double[] h = new double[5];\n w[0] = constraint.getWidth();\n if (this.topBlock != null) {\n RectangleConstraint c1 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0,\n new Range(0.0, constraint.getHeight()),\n LengthConstraintType.RANGE);\n Size2D size = this.topBlock.arrange(g2, c1);\n h[0] = size.height;\n }\n w[1] = w[0];\n if (this.bottomBlock != null) {\n RectangleConstraint c2 = new RectangleConstraint(w[0], null,\n LengthConstraintType.FIXED, 0.0, new Range(0.0,\n constraint.getHeight() - h[0]), LengthConstraintType.RANGE);\n Size2D size = this.bottomBlock.arrange(g2, c2);\n h[1] = size.height;\n }\n h[2] = constraint.getHeight() - h[1] - h[0];\n if (this.leftBlock != null) {\n RectangleConstraint c3 = new RectangleConstraint(0.0,\n new Range(0.0, constraint.getWidth()),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.leftBlock.arrange(g2, c3);\n w[2] = size.width;\n }\n h[3] = h[2];\n if (this.rightBlock != null) {\n RectangleConstraint c4 = new RectangleConstraint(0.0,\n new Range(0.0, Math.max(constraint.getWidth() - w[2], 0.0)),\n LengthConstraintType.RANGE, h[2], null,\n LengthConstraintType.FIXED);\n Size2D size = this.rightBlock.arrange(g2, c4);\n w[3] = size.width;\n }\n h[4] = h[2];\n w[4] = constraint.getWidth() - w[3] - w[2];\n RectangleConstraint c5 = new RectangleConstraint(w[4], h[4]);\n if (this.centerBlock != null) {\n this.centerBlock.arrange(g2, c5);\n }\n if (this.topBlock != null) {\n this.topBlock.setBounds(new Rectangle2D.Double(0.0, 0.0, w[0],\n h[0]));\n }\n if (this.bottomBlock != null) {\n this.bottomBlock.setBounds(new Rectangle2D.Double(0.0, h[0] + h[2],\n w[1], h[1]));\n }\n if (this.leftBlock != null) {\n this.leftBlock.setBounds(new Rectangle2D.Double(0.0, h[0], w[2],\n h[2]));\n }\n if (this.rightBlock != null) {\n this.rightBlock.setBounds(new Rectangle2D.Double(w[2] + w[4], h[0],\n w[3], h[3]));\n }\n if (this.centerBlock != null) {\n this.centerBlock.setBounds(new Rectangle2D.Double(w[2], h[0], w[4],\n h[4]));\n }\n return new Size2D(constraint.getWidth(), constraint.getHeight());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Chart-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Chart-13"}} {"sample_uid": "defects4j_function_repair::Math-106", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Fraction parse(String source, ParsePosition pos) {\n Fraction ret = super.parse(source, pos);\n if (ret != null) {\n return ret;\n }\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number whole = getWholeFormat().parse(source, pos);\n if (whole == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number num = getNumeratorFormat().parse(source, pos);\n if (num == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n switch (c) {\n case 0 :\n return new Fraction(num.intValue(), 1);\n case '/' :\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number den = getDenominatorFormat().parse(source, pos);\n if (den == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int w = whole.intValue();\n int n = num.intValue();\n int d = den.intValue();\n return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Fraction parse(String source, ParsePosition pos) {\n Fraction ret = super.parse(source, pos);\n if (ret != null) {\n return ret;\n }\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number whole = getWholeFormat().parse(source, pos);\n if (whole == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number num = getNumeratorFormat().parse(source, pos);\n if (num == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n switch (c) {\n case 0 :\n return new Fraction(num.intValue(), 1);\n case '/' :\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number den = getDenominatorFormat().parse(source, pos);\n if (den == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n int w = whole.intValue();\n int n = num.intValue();\n int d = den.intValue();\n return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);\n }\n"}, "reference": " public Fraction parse(String source, ParsePosition pos) {\n Fraction ret = super.parse(source, pos);\n if (ret != null) {\n return ret;\n }\n int initialIndex = pos.getIndex();\n parseAndIgnoreWhitespace(source, pos);\n Number whole = getWholeFormat().parse(source, pos);\n if (whole == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number num = getNumeratorFormat().parse(source, pos);\n if (num == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n if (num.intValue() < 0) {\n pos.setIndex(initialIndex);\n return null;\n }\n int startIndex = pos.getIndex();\n char c = parseNextCharacter(source, pos);\n switch (c) {\n case 0 :\n return new Fraction(num.intValue(), 1);\n case '/' :\n break;\n default :\n pos.setIndex(initialIndex);\n pos.setErrorIndex(startIndex);\n return null;\n }\n parseAndIgnoreWhitespace(source, pos);\n Number den = getDenominatorFormat().parse(source, pos);\n if (den == null) {\n pos.setIndex(initialIndex);\n return null;\n }\n if (den.intValue() < 0) {\n pos.setIndex(initialIndex);\n return null;\n }\n int w = whole.intValue();\n int n = num.intValue();\n int d = den.intValue();\n return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-106"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-106"}} {"sample_uid": "defects4j_function_repair::Compress-41", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ZipArchiveEntry getNextZipEntry() throws IOException {\n boolean firstEntry = true;\n if (closed || hitCentralDirectory) {\n return null;\n }\n if (current != null) {\n closeEntry();\n firstEntry = false;\n }\n try {\n if (firstEntry) {\n readFirstLocalFileHeader(LFH_BUF);\n } else {\n readFully(LFH_BUF);\n }\n } catch (final EOFException e) {\n return null;\n }\n final ZipLong sig = new ZipLong(LFH_BUF);\n if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) {\n hitCentralDirectory = true;\n skipRemainderOfArchive();\n }\n if (!sig.equals(ZipLong.LFH_SIG)) {\n return null;\n }\n int off = WORD;\n current = new CurrentEntry();\n final int versionMadeBy = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);\n final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off);\n final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();\n final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;\n current.hasDataDescriptor = gpFlag.usesDataDescriptor();\n current.entry.setGeneralPurposeBit(gpFlag);\n off += SHORT;\n current.entry.setMethod(ZipShort.getValue(LFH_BUF, off));\n off += SHORT;\n final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off));\n current.entry.setTime(time);\n off += WORD;\n ZipLong size = null, cSize = null;\n if (!current.hasDataDescriptor) {\n current.entry.setCrc(ZipLong.getValue(LFH_BUF, off));\n off += WORD;\n cSize = new ZipLong(LFH_BUF, off);\n off += WORD;\n size = new ZipLong(LFH_BUF, off);\n off += WORD;\n } else {\n off += 3 * WORD;\n }\n final int fileNameLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final int extraLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final byte[] fileName = new byte[fileNameLen];\n readFully(fileName);\n current.entry.setName(entryEncoding.decode(fileName), fileName);\n final byte[] extraData = new byte[extraLen];\n readFully(extraData);\n current.entry.setExtra(extraData);\n if (!hasUTF8Flag && useUnicodeExtraFields) {\n ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);\n }\n processZip64Extra(size, cSize);\n if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {\n if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {\n current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {\n current.in = new ExplodingInputStream(\n current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),\n current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),\n new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {\n current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n }\n }\n entriesRead++;\n return current.entry;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ZipArchiveEntry getNextZipEntry() throws IOException {\n boolean firstEntry = true;\n if (closed || hitCentralDirectory) {\n return null;\n }\n if (current != null) {\n closeEntry();\n firstEntry = false;\n }\n try {\n if (firstEntry) {\n readFirstLocalFileHeader(LFH_BUF);\n } else {\n readFully(LFH_BUF);\n }\n } catch (final EOFException e) {\n return null;\n }\n final ZipLong sig = new ZipLong(LFH_BUF);\n if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) {\n hitCentralDirectory = true;\n skipRemainderOfArchive();\n }\n if (!sig.equals(ZipLong.LFH_SIG)) {\n return null;\n }\n int off = WORD;\n current = new CurrentEntry();\n final int versionMadeBy = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);\n final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off);\n final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();\n final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;\n current.hasDataDescriptor = gpFlag.usesDataDescriptor();\n current.entry.setGeneralPurposeBit(gpFlag);\n off += SHORT;\n current.entry.setMethod(ZipShort.getValue(LFH_BUF, off));\n off += SHORT;\n final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off));\n current.entry.setTime(time);\n off += WORD;\n ZipLong size = null, cSize = null;\n if (!current.hasDataDescriptor) {\n current.entry.setCrc(ZipLong.getValue(LFH_BUF, off));\n off += WORD;\n cSize = new ZipLong(LFH_BUF, off);\n off += WORD;\n size = new ZipLong(LFH_BUF, off);\n off += WORD;\n } else {\n off += 3 * WORD;\n }\n final int fileNameLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final int extraLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final byte[] fileName = new byte[fileNameLen];\n readFully(fileName);\n current.entry.setName(entryEncoding.decode(fileName), fileName);\n final byte[] extraData = new byte[extraLen];\n readFully(extraData);\n current.entry.setExtra(extraData);\n if (!hasUTF8Flag && useUnicodeExtraFields) {\n ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);\n }\n processZip64Extra(size, cSize);\n if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {\n if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {\n current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {\n current.in = new ExplodingInputStream(\n current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),\n current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),\n new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {\n current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n }\n }\n entriesRead++;\n return current.entry;\n }\n"}, "reference": " public ZipArchiveEntry getNextZipEntry() throws IOException {\n boolean firstEntry = true;\n if (closed || hitCentralDirectory) {\n return null;\n }\n if (current != null) {\n closeEntry();\n firstEntry = false;\n }\n try {\n if (firstEntry) {\n readFirstLocalFileHeader(LFH_BUF);\n } else {\n readFully(LFH_BUF);\n }\n } catch (final EOFException e) {\n return null;\n }\n final ZipLong sig = new ZipLong(LFH_BUF);\n if (sig.equals(ZipLong.CFH_SIG) || sig.equals(ZipLong.AED_SIG)) {\n hitCentralDirectory = true;\n skipRemainderOfArchive();\n return null;\n }\n if (!sig.equals(ZipLong.LFH_SIG)) {\n throw new ZipException(String.format(\"Unexpected record signature: 0X%X\", sig.getValue()));\n }\n int off = WORD;\n current = new CurrentEntry();\n final int versionMadeBy = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n current.entry.setPlatform((versionMadeBy >> ZipFile.BYTE_SHIFT) & ZipFile.NIBLET_MASK);\n final GeneralPurposeBit gpFlag = GeneralPurposeBit.parse(LFH_BUF, off);\n final boolean hasUTF8Flag = gpFlag.usesUTF8ForNames();\n final ZipEncoding entryEncoding = hasUTF8Flag ? ZipEncodingHelper.UTF8_ZIP_ENCODING : zipEncoding;\n current.hasDataDescriptor = gpFlag.usesDataDescriptor();\n current.entry.setGeneralPurposeBit(gpFlag);\n off += SHORT;\n current.entry.setMethod(ZipShort.getValue(LFH_BUF, off));\n off += SHORT;\n final long time = ZipUtil.dosToJavaTime(ZipLong.getValue(LFH_BUF, off));\n current.entry.setTime(time);\n off += WORD;\n ZipLong size = null, cSize = null;\n if (!current.hasDataDescriptor) {\n current.entry.setCrc(ZipLong.getValue(LFH_BUF, off));\n off += WORD;\n cSize = new ZipLong(LFH_BUF, off);\n off += WORD;\n size = new ZipLong(LFH_BUF, off);\n off += WORD;\n } else {\n off += 3 * WORD;\n }\n final int fileNameLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final int extraLen = ZipShort.getValue(LFH_BUF, off);\n off += SHORT;\n final byte[] fileName = new byte[fileNameLen];\n readFully(fileName);\n current.entry.setName(entryEncoding.decode(fileName), fileName);\n final byte[] extraData = new byte[extraLen];\n readFully(extraData);\n current.entry.setExtra(extraData);\n if (!hasUTF8Flag && useUnicodeExtraFields) {\n ZipUtil.setNameAndCommentFromExtraFields(current.entry, fileName, null);\n }\n processZip64Extra(size, cSize);\n if (current.entry.getCompressedSize() != ArchiveEntry.SIZE_UNKNOWN) {\n if (current.entry.getMethod() == ZipMethod.UNSHRINKING.getCode()) {\n current.in = new UnshrinkingInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.IMPLODING.getCode()) {\n current.in = new ExplodingInputStream(\n current.entry.getGeneralPurposeBit().getSlidingDictionarySize(),\n current.entry.getGeneralPurposeBit().getNumberOfShannonFanoTrees(),\n new BoundedInputStream(in, current.entry.getCompressedSize()));\n } else if (current.entry.getMethod() == ZipMethod.BZIP2.getCode()) {\n current.in = new BZip2CompressorInputStream(new BoundedInputStream(in, current.entry.getCompressedSize()));\n }\n }\n entriesRead++;\n return current.entry;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-41"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-41"}} {"sample_uid": "defects4j_function_repair::Closure-59", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn()) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) {\n options.setWarningLevel(\n DiagnosticGroups.ES5_STRICT,\n CheckLevel.ERROR);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards);\n if (!options.checkSymbols &&\n !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) {\n composedGuards.addGuard(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = composedGuards;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn()) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) {\n options.setWarningLevel(\n DiagnosticGroups.ES5_STRICT,\n CheckLevel.ERROR);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards);\n if (!options.checkSymbols &&\n !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) {\n composedGuards.addGuard(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = composedGuards;\n }\n"}, "reference": " public void initOptions(CompilerOptions options) {\n this.options = options;\n if (errorManager == null) {\n if (outStream == null) {\n setErrorManager(\n new LoggerErrorManager(createMessageFormatter(), logger));\n } else {\n PrintStreamErrorManager printer =\n new PrintStreamErrorManager(createMessageFormatter(), outStream);\n printer.setSummaryDetailLevel(options.summaryDetailLevel);\n setErrorManager(printer);\n }\n }\n if (options.enables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = true;\n } else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {\n options.checkTypes = false;\n } else if (!options.checkTypes) {\n options.setWarningLevel(\n DiagnosticGroup.forType(\n RhinoErrorReporter.TYPE_PARSE_ERROR),\n CheckLevel.OFF);\n }\n if (options.checkGlobalThisLevel.isOn() &&\n !options.disables(DiagnosticGroups.GLOBAL_THIS)) {\n options.setWarningLevel(\n DiagnosticGroups.GLOBAL_THIS,\n options.checkGlobalThisLevel);\n }\n if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT) {\n options.setWarningLevel(\n DiagnosticGroups.ES5_STRICT,\n CheckLevel.ERROR);\n }\n List guards = Lists.newArrayList();\n guards.add(\n new SuppressDocWarningsGuard(\n getDiagnosticGroups().getRegisteredGroups()));\n guards.add(options.getWarningsGuard());\n ComposeWarningsGuard composedGuards = new ComposeWarningsGuard(guards);\n if (!options.checkSymbols &&\n !composedGuards.enables(DiagnosticGroups.CHECK_VARIABLES)) {\n composedGuards.addGuard(new DiagnosticGroupWarningsGuard(\n DiagnosticGroups.CHECK_VARIABLES, CheckLevel.OFF));\n }\n this.warningsGuard = composedGuards;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-59"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-59"}} {"sample_uid": "defects4j_function_repair::Lang-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16) { \n return createBigInteger(str);\n }\n if (hexDigits > 8) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16) { \n return createBigInteger(str);\n }\n if (hexDigits > 8) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n"}, "reference": " public static Number createNumber(final String str) throws NumberFormatException {\n if (str == null) {\n return null;\n }\n if (StringUtils.isBlank(str)) {\n throw new NumberFormatException(\"A blank string is not a valid number\");\n }\n final String[] hex_prefixes = {\"0x\", \"0X\", \"-0x\", \"-0X\", \"#\", \"-#\"};\n int pfxLen = 0;\n for(final String pfx : hex_prefixes) {\n if (str.startsWith(pfx)) {\n pfxLen += pfx.length();\n break;\n }\n }\n if (pfxLen > 0) { \n final int hexDigits = str.length() - pfxLen;\n if (hexDigits > 16) { \n return createBigInteger(str);\n }\n if (hexDigits > 8) { \n return createLong(str);\n }\n return createInteger(str);\n }\n final char lastChar = str.charAt(str.length() - 1);\n String mant;\n String dec;\n String exp;\n final int decPos = str.indexOf('.');\n final int expPos = str.indexOf('e') + str.indexOf('E') + 1; \n int numDecimals = 0; \n if (decPos > -1) { \n if (expPos > -1) { \n if (expPos < decPos || expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n dec = str.substring(decPos + 1, expPos);\n } else {\n dec = str.substring(decPos + 1);\n }\n mant = str.substring(0, decPos);\n numDecimals = dec.length(); \n } else {\n if (expPos > -1) {\n if (expPos > str.length()) { \n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n mant = str.substring(0, expPos);\n } else {\n mant = str;\n }\n dec = null;\n }\n if (!Character.isDigit(lastChar) && lastChar != '.') {\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length() - 1);\n } else {\n exp = null;\n }\n final String numeric = str.substring(0, str.length() - 1);\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n switch (lastChar) {\n case 'l' :\n case 'L' :\n if (dec == null\n && exp == null\n && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {\n try {\n return createLong(numeric);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(numeric);\n }\n throw new NumberFormatException(str + \" is not a valid number.\");\n case 'f' :\n case 'F' :\n try {\n final Float f = NumberUtils.createFloat(numeric);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n } catch (final NumberFormatException nfe) { \n }\n case 'd' :\n case 'D' :\n try {\n final Double d = NumberUtils.createDouble(numeric);\n if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) {\n return d;\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createBigDecimal(numeric);\n } catch (final NumberFormatException e) { \n }\n default :\n throw new NumberFormatException(str + \" is not a valid number.\");\n }\n }\n if (expPos > -1 && expPos < str.length() - 1) {\n exp = str.substring(expPos + 1, str.length());\n } else {\n exp = null;\n }\n if (dec == null && exp == null) { \n try {\n return createInteger(str);\n } catch (final NumberFormatException nfe) { \n }\n try {\n return createLong(str);\n } catch (final NumberFormatException nfe) { \n }\n return createBigInteger(str);\n }\n final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);\n try {\n if(numDecimals <= 7){\n final Float f = createFloat(str);\n if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) {\n return f;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n try {\n if(numDecimals <= 16){\n final Double d = createDouble(str);\n if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) {\n return d;\n }\n }\n } catch (final NumberFormatException nfe) { \n }\n return createBigDecimal(str);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-3"}} {"sample_uid": "defects4j_function_repair::Closure-152", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n JSType resolveInternal(ErrorReporter t, StaticScope scope) {\n setResolvedTypeInternal(this);\n call = (ArrowType) safeResolve(call, t, scope);\n prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope);\n typeOfThis = (ObjectType) safeResolve(typeOfThis, t, scope);\n boolean changed = false;\n ImmutableList.Builder resolvedInterfaces =\n ImmutableList.builder();\n for (ObjectType iface : implementedInterfaces) {\n ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope);\n resolvedInterfaces.add(resolvedIface);\n changed |= (resolvedIface != iface);\n }\n if (changed) {\n implementedInterfaces = resolvedInterfaces.build();\n }\n if (subTypes != null) {\n for (int i = 0; i < subTypes.size(); i++) {\n subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope));\n }\n }\n return super.resolveInternal(t, scope);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " JSType resolveInternal(ErrorReporter t, StaticScope scope) {\n setResolvedTypeInternal(this);\n call = (ArrowType) safeResolve(call, t, scope);\n prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope);\n typeOfThis = (ObjectType) safeResolve(typeOfThis, t, scope);\n boolean changed = false;\n ImmutableList.Builder resolvedInterfaces =\n ImmutableList.builder();\n for (ObjectType iface : implementedInterfaces) {\n ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope);\n resolvedInterfaces.add(resolvedIface);\n changed |= (resolvedIface != iface);\n }\n if (changed) {\n implementedInterfaces = resolvedInterfaces.build();\n }\n if (subTypes != null) {\n for (int i = 0; i < subTypes.size(); i++) {\n subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope));\n }\n }\n return super.resolveInternal(t, scope);\n }\n"}, "reference": " JSType resolveInternal(ErrorReporter t, StaticScope scope) {\n setResolvedTypeInternal(this);\n call = (ArrowType) safeResolve(call, t, scope);\n prototype = (FunctionPrototypeType) safeResolve(prototype, t, scope);\n JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope);\n if (maybeTypeOfThis instanceof ObjectType) {\n typeOfThis = (ObjectType) maybeTypeOfThis;\n }\n boolean changed = false;\n ImmutableList.Builder resolvedInterfaces =\n ImmutableList.builder();\n for (ObjectType iface : implementedInterfaces) {\n ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope);\n resolvedInterfaces.add(resolvedIface);\n changed |= (resolvedIface != iface);\n }\n if (changed) {\n implementedInterfaces = resolvedInterfaces.build();\n }\n if (subTypes != null) {\n for (int i = 0; i < subTypes.size(); i++) {\n subTypes.set(i, (FunctionType) subTypes.get(i).resolve(t, scope));\n }\n }\n return super.resolveInternal(t, scope);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-152"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-152"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-58", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef,\n JavaType propType0)\n throws JsonMappingException\n {\n AnnotatedMember mutator = propDef.getNonConstructorMutator();\n if (ctxt.canOverrideAccessModifiers()) {\n mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),\n propType0, propDef.getWrapperName(),\n beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());\n JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);\n if (type != propType0) {\n property = property.withType(type);\n }\n JsonDeserializer propDeser = findDeserializerFromAnnotation(ctxt, mutator);\n type = modifyTypeByAnnotation(ctxt, mutator, type);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop;\n if (mutator instanceof AnnotatedMethod) {\n prop = new MethodProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);\n } else {\n prop = new FieldProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedField) mutator);\n }\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();\n if (ref != null && ref.isManagedReference()) {\n prop.setManagedReferenceName(ref.getName());\n }\n ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();\n if(objectIdInfo != null){\n prop.setObjectIdInfo(objectIdInfo);\n }\n return prop;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef,\n JavaType propType0)\n throws JsonMappingException\n {\n AnnotatedMember mutator = propDef.getNonConstructorMutator();\n if (ctxt.canOverrideAccessModifiers()) {\n mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),\n propType0, propDef.getWrapperName(),\n beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());\n JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);\n if (type != propType0) {\n property = property.withType(type);\n }\n JsonDeserializer propDeser = findDeserializerFromAnnotation(ctxt, mutator);\n type = modifyTypeByAnnotation(ctxt, mutator, type);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop;\n if (mutator instanceof AnnotatedMethod) {\n prop = new MethodProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);\n } else {\n prop = new FieldProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedField) mutator);\n }\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();\n if (ref != null && ref.isManagedReference()) {\n prop.setManagedReferenceName(ref.getName());\n }\n ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();\n if(objectIdInfo != null){\n prop.setObjectIdInfo(objectIdInfo);\n }\n return prop;\n }\n"}, "reference": " protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,\n BeanDescription beanDesc, BeanPropertyDefinition propDef,\n JavaType propType0)\n throws JsonMappingException\n {\n AnnotatedMember mutator = propDef.getNonConstructorMutator();\n if (ctxt.canOverrideAccessModifiers()) {\n if ((mutator instanceof AnnotatedField)\n && \"cause\".equals(mutator.getName())) {\n ;\n } else {\n mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));\n }\n }\n BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),\n propType0, propDef.getWrapperName(),\n beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());\n JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);\n if (type != propType0) {\n property = property.withType(type);\n }\n JsonDeserializer propDeser = findDeserializerFromAnnotation(ctxt, mutator);\n type = modifyTypeByAnnotation(ctxt, mutator, type);\n TypeDeserializer typeDeser = type.getTypeHandler();\n SettableBeanProperty prop;\n if (mutator instanceof AnnotatedMethod) {\n prop = new MethodProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);\n } else {\n prop = new FieldProperty(propDef, type, typeDeser,\n beanDesc.getClassAnnotations(), (AnnotatedField) mutator);\n }\n if (propDeser != null) {\n prop = prop.withValueDeserializer(propDeser);\n }\n AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();\n if (ref != null && ref.isManagedReference()) {\n prop.setManagedReferenceName(ref.getName());\n }\n ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();\n if(objectIdInfo != null){\n prop.setObjectIdInfo(objectIdInfo);\n }\n return prop;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-58"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-58"}} {"sample_uid": "defects4j_function_repair::Math-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static double linearCombination(final double[] a, final double[] b)\n throws DimensionMismatchException {\n final int len = a.length;\n if (len != b.length) {\n throw new DimensionMismatchException(len, b.length);\n }\n final double[] prodHigh = new double[len];\n double prodLowSum = 0;\n for (int i = 0; i < len; i++) {\n final double ai = a[i];\n final double ca = SPLIT_FACTOR * ai;\n final double aHigh = ca - (ca - ai);\n final double aLow = ai - aHigh;\n final double bi = b[i];\n final double cb = SPLIT_FACTOR * bi;\n final double bHigh = cb - (cb - bi);\n final double bLow = bi - bHigh;\n prodHigh[i] = ai * bi;\n final double prodLow = aLow * bLow - (((prodHigh[i] -\n aHigh * bHigh) -\n aLow * bHigh) -\n aHigh * bLow);\n prodLowSum += prodLow;\n }\n final double prodHighCur = prodHigh[0];\n double prodHighNext = prodHigh[1];\n double sHighPrev = prodHighCur + prodHighNext;\n double sPrime = sHighPrev - prodHighNext;\n double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime);\n final int lenMinusOne = len - 1;\n for (int i = 1; i < lenMinusOne; i++) {\n prodHighNext = prodHigh[i + 1];\n final double sHighCur = sHighPrev + prodHighNext;\n sPrime = sHighCur - prodHighNext;\n sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime);\n sHighPrev = sHighCur;\n }\n double result = sHighPrev + (prodLowSum + sLowSum);\n if (Double.isNaN(result)) {\n result = 0;\n for (int i = 0; i < len; ++i) {\n result += a[i] * b[i];\n }\n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static double linearCombination(final double[] a, final double[] b)\n throws DimensionMismatchException {\n final int len = a.length;\n if (len != b.length) {\n throw new DimensionMismatchException(len, b.length);\n }\n final double[] prodHigh = new double[len];\n double prodLowSum = 0;\n for (int i = 0; i < len; i++) {\n final double ai = a[i];\n final double ca = SPLIT_FACTOR * ai;\n final double aHigh = ca - (ca - ai);\n final double aLow = ai - aHigh;\n final double bi = b[i];\n final double cb = SPLIT_FACTOR * bi;\n final double bHigh = cb - (cb - bi);\n final double bLow = bi - bHigh;\n prodHigh[i] = ai * bi;\n final double prodLow = aLow * bLow - (((prodHigh[i] -\n aHigh * bHigh) -\n aLow * bHigh) -\n aHigh * bLow);\n prodLowSum += prodLow;\n }\n final double prodHighCur = prodHigh[0];\n double prodHighNext = prodHigh[1];\n double sHighPrev = prodHighCur + prodHighNext;\n double sPrime = sHighPrev - prodHighNext;\n double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime);\n final int lenMinusOne = len - 1;\n for (int i = 1; i < lenMinusOne; i++) {\n prodHighNext = prodHigh[i + 1];\n final double sHighCur = sHighPrev + prodHighNext;\n sPrime = sHighCur - prodHighNext;\n sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime);\n sHighPrev = sHighCur;\n }\n double result = sHighPrev + (prodLowSum + sLowSum);\n if (Double.isNaN(result)) {\n result = 0;\n for (int i = 0; i < len; ++i) {\n result += a[i] * b[i];\n }\n }\n return result;\n }\n"}, "reference": " public static double linearCombination(final double[] a, final double[] b)\n throws DimensionMismatchException {\n final int len = a.length;\n if (len != b.length) {\n throw new DimensionMismatchException(len, b.length);\n }\n if (len == 1) {\n return a[0] * b[0];\n }\n final double[] prodHigh = new double[len];\n double prodLowSum = 0;\n for (int i = 0; i < len; i++) {\n final double ai = a[i];\n final double ca = SPLIT_FACTOR * ai;\n final double aHigh = ca - (ca - ai);\n final double aLow = ai - aHigh;\n final double bi = b[i];\n final double cb = SPLIT_FACTOR * bi;\n final double bHigh = cb - (cb - bi);\n final double bLow = bi - bHigh;\n prodHigh[i] = ai * bi;\n final double prodLow = aLow * bLow - (((prodHigh[i] -\n aHigh * bHigh) -\n aLow * bHigh) -\n aHigh * bLow);\n prodLowSum += prodLow;\n }\n final double prodHighCur = prodHigh[0];\n double prodHighNext = prodHigh[1];\n double sHighPrev = prodHighCur + prodHighNext;\n double sPrime = sHighPrev - prodHighNext;\n double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime);\n final int lenMinusOne = len - 1;\n for (int i = 1; i < lenMinusOne; i++) {\n prodHighNext = prodHigh[i + 1];\n final double sHighCur = sHighPrev + prodHighNext;\n sPrime = sHighCur - prodHighNext;\n sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime);\n sHighPrev = sHighCur;\n }\n double result = sHighPrev + (prodLowSum + sLowSum);\n if (Double.isNaN(result)) {\n result = 0;\n for (int i = 0; i < len; ++i) {\n result += a[i] * b[i];\n }\n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-3"}} {"sample_uid": "defects4j_function_repair::JacksonCore-3", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,\n ObjectCodec codec, BytesToNameCanonicalizer sym,\n byte[] inputBuffer, int start, int end,\n boolean bufferRecyclable)\n {\n super(ctxt, features);\n _inputStream = in;\n _objectCodec = codec;\n _symbols = sym;\n _inputBuffer = inputBuffer;\n _inputPtr = start;\n _inputEnd = end;\n _bufferRecyclable = bufferRecyclable;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,\n ObjectCodec codec, BytesToNameCanonicalizer sym,\n byte[] inputBuffer, int start, int end,\n boolean bufferRecyclable)\n {\n super(ctxt, features);\n _inputStream = in;\n _objectCodec = codec;\n _symbols = sym;\n _inputBuffer = inputBuffer;\n _inputPtr = start;\n _inputEnd = end;\n _bufferRecyclable = bufferRecyclable;\n }\n"}, "reference": " public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,\n ObjectCodec codec, BytesToNameCanonicalizer sym,\n byte[] inputBuffer, int start, int end,\n boolean bufferRecyclable)\n {\n super(ctxt, features);\n _inputStream = in;\n _objectCodec = codec;\n _symbols = sym;\n _inputBuffer = inputBuffer;\n _inputPtr = start;\n _inputEnd = end;\n _currInputRowStart = start;\n _currInputProcessed = -start;\n _bufferRecyclable = bufferRecyclable;\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonCore-3"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonCore-3"}} {"sample_uid": "defects4j_function_repair::Lang-39", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private static String replaceEach(String text, String[] searchList, String[] replacementList, \n boolean repeat, int timeToLive) \n {\n if (text == null || text.length() == 0 || searchList == null || \n searchList.length == 0 || replacementList == null || replacementList.length == 0) \n {\n return text;\n }\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \"\n + searchLength\n + \" vs \"\n + replacementLength);\n }\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n int increase = 0;\n for (int i = 0; i < searchList.length; i++) {\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; \n }\n }\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private static String replaceEach(String text, String[] searchList, String[] replacementList, \n boolean repeat, int timeToLive) \n {\n if (text == null || text.length() == 0 || searchList == null || \n searchList.length == 0 || replacementList == null || replacementList.length == 0) \n {\n return text;\n }\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \"\n + searchLength\n + \" vs \"\n + replacementLength);\n }\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n int increase = 0;\n for (int i = 0; i < searchList.length; i++) {\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; \n }\n }\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n"}, "reference": " private static String replaceEach(String text, String[] searchList, String[] replacementList, \n boolean repeat, int timeToLive) \n {\n if (text == null || text.length() == 0 || searchList == null || \n searchList.length == 0 || replacementList == null || replacementList.length == 0) \n {\n return text;\n }\n if (timeToLive < 0) {\n throw new IllegalStateException(\"TimeToLive of \" + timeToLive + \" is less than 0: \" + text);\n }\n int searchLength = searchList.length;\n int replacementLength = replacementList.length;\n if (searchLength != replacementLength) {\n throw new IllegalArgumentException(\"Search and Replace array lengths don't match: \"\n + searchLength\n + \" vs \"\n + replacementLength);\n }\n boolean[] noMoreMatchesForReplIndex = new boolean[searchLength];\n int textIndex = -1;\n int replaceIndex = -1;\n int tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i]);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n if (textIndex == -1) {\n return text;\n }\n int start = 0;\n int increase = 0;\n for (int i = 0; i < searchList.length; i++) {\n if (searchList[i] == null || replacementList[i] == null) {\n continue;\n }\n int greater = replacementList[i].length() - searchList[i].length();\n if (greater > 0) {\n increase += 3 * greater; \n }\n }\n increase = Math.min(increase, text.length() / 5);\n StringBuilder buf = new StringBuilder(text.length() + increase);\n while (textIndex != -1) {\n for (int i = start; i < textIndex; i++) {\n buf.append(text.charAt(i));\n }\n buf.append(replacementList[replaceIndex]);\n start = textIndex + searchList[replaceIndex].length();\n textIndex = -1;\n replaceIndex = -1;\n tempIndex = -1;\n for (int i = 0; i < searchLength; i++) {\n if (noMoreMatchesForReplIndex[i] || searchList[i] == null || \n searchList[i].length() == 0 || replacementList[i] == null) \n {\n continue;\n }\n tempIndex = text.indexOf(searchList[i], start);\n if (tempIndex == -1) {\n noMoreMatchesForReplIndex[i] = true;\n } else {\n if (textIndex == -1 || tempIndex < textIndex) {\n textIndex = tempIndex;\n replaceIndex = i;\n }\n }\n }\n }\n int textLength = text.length();\n for (int i = start; i < textLength; i++) {\n buf.append(text.charAt(i));\n }\n String result = buf.toString();\n if (!repeat) {\n return result;\n }\n return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-39"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-39"}} {"sample_uid": "defects4j_function_repair::Compress-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected void setName(String name) {\n this.name = name;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected void setName(String name) {\n this.name = name;\n }\n"}, "reference": " protected void setName(String name) {\n if (name != null && getPlatform() == PLATFORM_FAT\n && name.indexOf(\"/\") == -1) {\n name = name.replace('\\\\', '/');\n }\n this.name = name;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-13"}} {"sample_uid": "defects4j_function_repair::Gson-13", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private int peekNumber() throws IOException {\n char[] buffer = this.buffer;\n int p = pos;\n int l = limit;\n long value = 0; \n boolean negative = false;\n boolean fitsInLong = true;\n int last = NUMBER_CHAR_NONE;\n int i = 0;\n charactersOfNumber:\n for (; true; i++) {\n if (p + i == l) {\n if (i == buffer.length) {\n return PEEKED_NONE;\n }\n if (!fillBuffer(i + 1)) {\n break;\n }\n p = pos;\n l = limit;\n }\n char c = buffer[p + i];\n switch (c) {\n case '-':\n if (last == NUMBER_CHAR_NONE) {\n negative = true;\n last = NUMBER_CHAR_SIGN;\n continue;\n } else if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case '+':\n if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case 'e':\n case 'E':\n if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {\n last = NUMBER_CHAR_EXP_E;\n continue;\n }\n return PEEKED_NONE;\n case '.':\n if (last == NUMBER_CHAR_DIGIT) {\n last = NUMBER_CHAR_DECIMAL;\n continue;\n }\n return PEEKED_NONE;\n default:\n if (c < '0' || c > '9') {\n if (!isLiteral(c)) {\n break charactersOfNumber;\n }\n return PEEKED_NONE;\n }\n if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {\n value = -(c - '0');\n last = NUMBER_CHAR_DIGIT;\n } else if (last == NUMBER_CHAR_DIGIT) {\n if (value == 0) {\n return PEEKED_NONE; \n }\n long newValue = value * 10 - (c - '0');\n fitsInLong &= value > MIN_INCOMPLETE_INTEGER\n || (value == MIN_INCOMPLETE_INTEGER && newValue < value);\n value = newValue;\n } else if (last == NUMBER_CHAR_DECIMAL) {\n last = NUMBER_CHAR_FRACTION_DIGIT;\n } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {\n last = NUMBER_CHAR_EXP_DIGIT;\n }\n }\n }\n if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {\n peekedLong = negative ? value : -value;\n pos += i;\n return peeked = PEEKED_LONG;\n } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT\n || last == NUMBER_CHAR_EXP_DIGIT) {\n peekedNumberLength = i;\n return peeked = PEEKED_NUMBER;\n } else {\n return PEEKED_NONE;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private int peekNumber() throws IOException {\n char[] buffer = this.buffer;\n int p = pos;\n int l = limit;\n long value = 0; \n boolean negative = false;\n boolean fitsInLong = true;\n int last = NUMBER_CHAR_NONE;\n int i = 0;\n charactersOfNumber:\n for (; true; i++) {\n if (p + i == l) {\n if (i == buffer.length) {\n return PEEKED_NONE;\n }\n if (!fillBuffer(i + 1)) {\n break;\n }\n p = pos;\n l = limit;\n }\n char c = buffer[p + i];\n switch (c) {\n case '-':\n if (last == NUMBER_CHAR_NONE) {\n negative = true;\n last = NUMBER_CHAR_SIGN;\n continue;\n } else if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case '+':\n if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case 'e':\n case 'E':\n if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {\n last = NUMBER_CHAR_EXP_E;\n continue;\n }\n return PEEKED_NONE;\n case '.':\n if (last == NUMBER_CHAR_DIGIT) {\n last = NUMBER_CHAR_DECIMAL;\n continue;\n }\n return PEEKED_NONE;\n default:\n if (c < '0' || c > '9') {\n if (!isLiteral(c)) {\n break charactersOfNumber;\n }\n return PEEKED_NONE;\n }\n if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {\n value = -(c - '0');\n last = NUMBER_CHAR_DIGIT;\n } else if (last == NUMBER_CHAR_DIGIT) {\n if (value == 0) {\n return PEEKED_NONE; \n }\n long newValue = value * 10 - (c - '0');\n fitsInLong &= value > MIN_INCOMPLETE_INTEGER\n || (value == MIN_INCOMPLETE_INTEGER && newValue < value);\n value = newValue;\n } else if (last == NUMBER_CHAR_DECIMAL) {\n last = NUMBER_CHAR_FRACTION_DIGIT;\n } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {\n last = NUMBER_CHAR_EXP_DIGIT;\n }\n }\n }\n if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {\n peekedLong = negative ? value : -value;\n pos += i;\n return peeked = PEEKED_LONG;\n } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT\n || last == NUMBER_CHAR_EXP_DIGIT) {\n peekedNumberLength = i;\n return peeked = PEEKED_NUMBER;\n } else {\n return PEEKED_NONE;\n }\n }\n"}, "reference": " private int peekNumber() throws IOException {\n char[] buffer = this.buffer;\n int p = pos;\n int l = limit;\n long value = 0; \n boolean negative = false;\n boolean fitsInLong = true;\n int last = NUMBER_CHAR_NONE;\n int i = 0;\n charactersOfNumber:\n for (; true; i++) {\n if (p + i == l) {\n if (i == buffer.length) {\n return PEEKED_NONE;\n }\n if (!fillBuffer(i + 1)) {\n break;\n }\n p = pos;\n l = limit;\n }\n char c = buffer[p + i];\n switch (c) {\n case '-':\n if (last == NUMBER_CHAR_NONE) {\n negative = true;\n last = NUMBER_CHAR_SIGN;\n continue;\n } else if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case '+':\n if (last == NUMBER_CHAR_EXP_E) {\n last = NUMBER_CHAR_EXP_SIGN;\n continue;\n }\n return PEEKED_NONE;\n case 'e':\n case 'E':\n if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {\n last = NUMBER_CHAR_EXP_E;\n continue;\n }\n return PEEKED_NONE;\n case '.':\n if (last == NUMBER_CHAR_DIGIT) {\n last = NUMBER_CHAR_DECIMAL;\n continue;\n }\n return PEEKED_NONE;\n default:\n if (c < '0' || c > '9') {\n if (!isLiteral(c)) {\n break charactersOfNumber;\n }\n return PEEKED_NONE;\n }\n if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {\n value = -(c - '0');\n last = NUMBER_CHAR_DIGIT;\n } else if (last == NUMBER_CHAR_DIGIT) {\n if (value == 0) {\n return PEEKED_NONE; \n }\n long newValue = value * 10 - (c - '0');\n fitsInLong &= value > MIN_INCOMPLETE_INTEGER\n || (value == MIN_INCOMPLETE_INTEGER && newValue < value);\n value = newValue;\n } else if (last == NUMBER_CHAR_DECIMAL) {\n last = NUMBER_CHAR_FRACTION_DIGIT;\n } else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {\n last = NUMBER_CHAR_EXP_DIGIT;\n }\n }\n }\n if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value!=0 || false==negative)) {\n peekedLong = negative ? value : -value;\n pos += i;\n return peeked = PEEKED_LONG;\n } else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT\n || last == NUMBER_CHAR_EXP_DIGIT) {\n peekedNumberLength = i;\n return peeked = PEEKED_NUMBER;\n } else {\n return PEEKED_NONE;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Gson-13"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Gson-13"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-112", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegate = null;\n if (_valueInstantiator != null) {\n AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator();\n if (delegateCreator != null) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n delegate = findDeserializer(ctxt, delegateType, property);\n }\n }\n JsonDeserializer valueDeser = _valueDeserializer;\n final JavaType valueType = _containerType.getContentType();\n if (valueDeser == null) {\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(valueType, property);\n }\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);\n if (isDefaultDeserializer(valueDeser)) {\n valueDeser = null;\n }\n return withResolved(delegate, valueDeser, nuller, unwrapSingle);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegate = null;\n if (_valueInstantiator != null) {\n AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator();\n if (delegateCreator != null) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n delegate = findDeserializer(ctxt, delegateType, property);\n }\n }\n JsonDeserializer valueDeser = _valueDeserializer;\n final JavaType valueType = _containerType.getContentType();\n if (valueDeser == null) {\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(valueType, property);\n }\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);\n if (isDefaultDeserializer(valueDeser)) {\n valueDeser = null;\n }\n return withResolved(delegate, valueDeser, nuller, unwrapSingle);\n }\n"}, "reference": " public JsonDeserializer createContextual(DeserializationContext ctxt,\n BeanProperty property) throws JsonMappingException\n {\n JsonDeserializer delegate = null;\n if (_valueInstantiator != null) {\n AnnotatedWithParams delegateCreator = _valueInstantiator.getArrayDelegateCreator();\n if (delegateCreator != null) {\n JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());\n delegate = findDeserializer(ctxt, delegateType, property);\n } else if ((delegateCreator = _valueInstantiator.getDelegateCreator()) != null) {\n JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());\n delegate = findDeserializer(ctxt, delegateType, property);\n }\n }\n JsonDeserializer valueDeser = _valueDeserializer;\n final JavaType valueType = _containerType.getContentType();\n if (valueDeser == null) {\n valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);\n if (valueDeser == null) {\n valueDeser = ctxt.findContextualValueDeserializer(valueType, property);\n }\n } else { \n valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);\n }\n Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,\n JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);\n if (isDefaultDeserializer(valueDeser)) {\n valueDeser = null;\n }\n return withResolved(delegate, valueDeser, nuller, unwrapSingle);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-112"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-112"}} {"sample_uid": "defects4j_function_repair::Closure-65", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c < 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\0\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c < 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n"}, "reference": " static String strEscape(String s, char quote,\n String doublequoteEscape,\n String singlequoteEscape,\n String backslashEscape,\n CharsetEncoder outputCharsetEncoder) {\n StringBuilder sb = new StringBuilder(s.length() + 2);\n sb.append(quote);\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n switch (c) {\n case '\\0': sb.append(\"\\\\000\"); break;\n case '\\n': sb.append(\"\\\\n\"); break;\n case '\\r': sb.append(\"\\\\r\"); break;\n case '\\t': sb.append(\"\\\\t\"); break;\n case '\\\\': sb.append(backslashEscape); break;\n case '\\\"': sb.append(doublequoteEscape); break;\n case '\\'': sb.append(singlequoteEscape); break;\n case '>': \n if (i >= 2 &&\n ((s.charAt(i - 1) == '-' && s.charAt(i - 2) == '-') ||\n (s.charAt(i - 1) == ']' && s.charAt(i - 2) == ']'))) {\n sb.append(\"\\\\>\");\n } else {\n sb.append(c);\n }\n break;\n case '<':\n final String END_SCRIPT = \"/script\";\n final String START_COMMENT = \"!--\";\n if (s.regionMatches(true, i + 1, END_SCRIPT, 0,\n END_SCRIPT.length())) {\n sb.append(\"<\\\\\");\n } else if (s.regionMatches(false, i + 1, START_COMMENT, 0,\n START_COMMENT.length())) {\n sb.append(\"<\\\\\");\n } else {\n sb.append(c);\n }\n break;\n default:\n if (outputCharsetEncoder != null) {\n if (outputCharsetEncoder.canEncode(c)) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n } else {\n if (c > 0x1f && c < 0x7f) {\n sb.append(c);\n } else {\n appendHexJavaScriptRepresentation(sb, c);\n }\n }\n }\n }\n sb.append(quote);\n return sb.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-65"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-65"}} {"sample_uid": "defects4j_function_repair::Math-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Fraction(double value, double epsilon, int maxDenominator, int maxIterations)\n throws FractionConversionException\n {\n long overflow = Integer.MAX_VALUE;\n double r0 = value;\n long a0 = (long)FastMath.floor(r0);\n if (a0 > overflow) {\n throw new FractionConversionException(value, a0, 1l);\n }\n if (FastMath.abs(a0 - value) < epsilon) {\n this.numerator = (int) a0;\n this.denominator = 1;\n return;\n }\n long p0 = 1;\n long q0 = 0;\n long p1 = a0;\n long q1 = 1;\n long p2 = 0;\n long q2 = 1;\n int n = 0;\n boolean stop = false;\n do {\n ++n;\n double r1 = 1.0 / (r0 - a0);\n long a1 = (long)FastMath.floor(r1);\n p2 = (a1 * p1) + p0;\n q2 = (a1 * q1) + q0;\n if ((p2 > overflow) || (q2 > overflow)) {\n throw new FractionConversionException(value, p2, q2);\n }\n double convergent = (double)p2 / (double)q2;\n if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) {\n p0 = p1;\n p1 = p2;\n q0 = q1;\n q1 = q2;\n a0 = a1;\n r0 = r1;\n } else {\n stop = true;\n }\n } while (!stop);\n if (n >= maxIterations) {\n throw new FractionConversionException(value, maxIterations);\n }\n if (q2 < maxDenominator) {\n this.numerator = (int) p2;\n this.denominator = (int) q2;\n } else {\n this.numerator = (int) p1;\n this.denominator = (int) q1;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Fraction(double value, double epsilon, int maxDenominator, int maxIterations)\n throws FractionConversionException\n {\n long overflow = Integer.MAX_VALUE;\n double r0 = value;\n long a0 = (long)FastMath.floor(r0);\n if (a0 > overflow) {\n throw new FractionConversionException(value, a0, 1l);\n }\n if (FastMath.abs(a0 - value) < epsilon) {\n this.numerator = (int) a0;\n this.denominator = 1;\n return;\n }\n long p0 = 1;\n long q0 = 0;\n long p1 = a0;\n long q1 = 1;\n long p2 = 0;\n long q2 = 1;\n int n = 0;\n boolean stop = false;\n do {\n ++n;\n double r1 = 1.0 / (r0 - a0);\n long a1 = (long)FastMath.floor(r1);\n p2 = (a1 * p1) + p0;\n q2 = (a1 * q1) + q0;\n if ((p2 > overflow) || (q2 > overflow)) {\n throw new FractionConversionException(value, p2, q2);\n }\n double convergent = (double)p2 / (double)q2;\n if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) {\n p0 = p1;\n p1 = p2;\n q0 = q1;\n q1 = q2;\n a0 = a1;\n r0 = r1;\n } else {\n stop = true;\n }\n } while (!stop);\n if (n >= maxIterations) {\n throw new FractionConversionException(value, maxIterations);\n }\n if (q2 < maxDenominator) {\n this.numerator = (int) p2;\n this.denominator = (int) q2;\n } else {\n this.numerator = (int) p1;\n this.denominator = (int) q1;\n }\n }\n"}, "reference": " private Fraction(double value, double epsilon, int maxDenominator, int maxIterations)\n throws FractionConversionException\n {\n long overflow = Integer.MAX_VALUE;\n double r0 = value;\n long a0 = (long)FastMath.floor(r0);\n if (FastMath.abs(a0) > overflow) {\n throw new FractionConversionException(value, a0, 1l);\n }\n if (FastMath.abs(a0 - value) < epsilon) {\n this.numerator = (int) a0;\n this.denominator = 1;\n return;\n }\n long p0 = 1;\n long q0 = 0;\n long p1 = a0;\n long q1 = 1;\n long p2 = 0;\n long q2 = 1;\n int n = 0;\n boolean stop = false;\n do {\n ++n;\n double r1 = 1.0 / (r0 - a0);\n long a1 = (long)FastMath.floor(r1);\n p2 = (a1 * p1) + p0;\n q2 = (a1 * q1) + q0;\n if ((FastMath.abs(p2) > overflow) || (FastMath.abs(q2) > overflow)) {\n throw new FractionConversionException(value, p2, q2);\n }\n double convergent = (double)p2 / (double)q2;\n if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) {\n p0 = p1;\n p1 = p2;\n q0 = q1;\n q1 = q2;\n a0 = a1;\n r0 = r1;\n } else {\n stop = true;\n }\n } while (!stop);\n if (n >= maxIterations) {\n throw new FractionConversionException(value, maxIterations);\n }\n if (q2 < maxDenominator) {\n this.numerator = (int) p2;\n this.denominator = (int) q2;\n } else {\n this.numerator = (int) p1;\n this.denominator = (int) q1;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-26"}} {"sample_uid": "defects4j_function_repair::Jsoup-77", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void popStackToClose(Token.EndTag endTag) {\n String elName = endTag.name();\n Element firstFound = null;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n if (next.nodeName().equals(elName)) {\n firstFound = next;\n break;\n }\n }\n if (firstFound == null)\n return; \n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n stack.remove(pos);\n if (next == firstFound)\n break;\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void popStackToClose(Token.EndTag endTag) {\n String elName = endTag.name();\n Element firstFound = null;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n if (next.nodeName().equals(elName)) {\n firstFound = next;\n break;\n }\n }\n if (firstFound == null)\n return; \n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n stack.remove(pos);\n if (next == firstFound)\n break;\n }\n }\n"}, "reference": " private void popStackToClose(Token.EndTag endTag) {\n String elName = endTag.normalName();\n Element firstFound = null;\n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n if (next.nodeName().equals(elName)) {\n firstFound = next;\n break;\n }\n }\n if (firstFound == null)\n return; \n for (int pos = stack.size() -1; pos >= 0; pos--) {\n Element next = stack.get(pos);\n stack.remove(pos);\n if (next == firstFound)\n break;\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-77"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-77"}} {"sample_uid": "defects4j_function_repair::Jsoup-26", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public Document clean(Document dirtyDocument) {\n Validate.notNull(dirtyDocument);\n Document clean = Document.createShell(dirtyDocument.baseUri());\n copySafeNodes(dirtyDocument.body(), clean.body());\n return clean;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public Document clean(Document dirtyDocument) {\n Validate.notNull(dirtyDocument);\n Document clean = Document.createShell(dirtyDocument.baseUri());\n copySafeNodes(dirtyDocument.body(), clean.body());\n return clean;\n }\n"}, "reference": " public Document clean(Document dirtyDocument) {\n Validate.notNull(dirtyDocument);\n Document clean = Document.createShell(dirtyDocument.baseUri());\n if (dirtyDocument.body() != null) \n copySafeNodes(dirtyDocument.body(), clean.body());\n return clean;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-26"}} {"sample_uid": "defects4j_function_repair::JxPath-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean compute(Object left, Object right) {\n left = reduce(left);\n right = reduce(right);\n if (left instanceof InitialContext) {\n ((InitialContext) left).reset();\n }\n if (right instanceof InitialContext) {\n ((InitialContext) right).reset();\n }\n if (left instanceof Iterator && right instanceof Iterator) {\n return findMatch((Iterator) left, (Iterator) right);\n }\n if (left instanceof Iterator) {\n return containsMatch((Iterator) left, right);\n }\n if (right instanceof Iterator) {\n return containsMatch((Iterator) right, left);\n }\n double ld = InfoSetUtil.doubleValue(left);\n double rd = InfoSetUtil.doubleValue(right);\n return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean compute(Object left, Object right) {\n left = reduce(left);\n right = reduce(right);\n if (left instanceof InitialContext) {\n ((InitialContext) left).reset();\n }\n if (right instanceof InitialContext) {\n ((InitialContext) right).reset();\n }\n if (left instanceof Iterator && right instanceof Iterator) {\n return findMatch((Iterator) left, (Iterator) right);\n }\n if (left instanceof Iterator) {\n return containsMatch((Iterator) left, right);\n }\n if (right instanceof Iterator) {\n return containsMatch((Iterator) right, left);\n }\n double ld = InfoSetUtil.doubleValue(left);\n double rd = InfoSetUtil.doubleValue(right);\n return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);\n }\n"}, "reference": " private boolean compute(Object left, Object right) {\n left = reduce(left);\n right = reduce(right);\n if (left instanceof InitialContext) {\n ((InitialContext) left).reset();\n }\n if (right instanceof InitialContext) {\n ((InitialContext) right).reset();\n }\n if (left instanceof Iterator && right instanceof Iterator) {\n return findMatch((Iterator) left, (Iterator) right);\n }\n if (left instanceof Iterator) {\n return containsMatch((Iterator) left, right);\n }\n if (right instanceof Iterator) {\n return containsMatch((Iterator) right, left);\n }\n double ld = InfoSetUtil.doubleValue(left);\n if (Double.isNaN(ld)) {\n return false;\n }\n double rd = InfoSetUtil.doubleValue(right);\n if (Double.isNaN(rd)) {\n return false;\n }\n return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JxPath-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JxPath-8"}} {"sample_uid": "defects4j_function_repair::Math-30", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private double calculateAsymptoticPValue(final double Umin,\n final int n1,\n final int n2)\n throws ConvergenceException, MaxCountExceededException {\n final int n1n2prod = n1 * n2;\n final double EU = n1n2prod / 2.0;\n final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0;\n final double z = (Umin - EU) / FastMath.sqrt(VarU);\n final NormalDistribution standardNormal = new NormalDistribution(0, 1);\n return 2 * standardNormal.cumulativeProbability(z);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private double calculateAsymptoticPValue(final double Umin,\n final int n1,\n final int n2)\n throws ConvergenceException, MaxCountExceededException {\n final int n1n2prod = n1 * n2;\n final double EU = n1n2prod / 2.0;\n final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0;\n final double z = (Umin - EU) / FastMath.sqrt(VarU);\n final NormalDistribution standardNormal = new NormalDistribution(0, 1);\n return 2 * standardNormal.cumulativeProbability(z);\n }\n"}, "reference": " private double calculateAsymptoticPValue(final double Umin,\n final int n1,\n final int n2)\n throws ConvergenceException, MaxCountExceededException {\n final double n1n2prod = n1 * n2;\n final double EU = n1n2prod / 2.0;\n final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0;\n final double z = (Umin - EU) / FastMath.sqrt(VarU);\n final NormalDistribution standardNormal = new NormalDistribution(0, 1);\n return 2 * standardNormal.cumulativeProbability(z);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-30"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-30"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-99", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected String buildCanonicalName()\n {\n StringBuilder sb = new StringBuilder();\n sb.append(_class.getName());\n sb.append('<');\n sb.append(_referencedType.toCanonical());\n return sb.toString();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected String buildCanonicalName()\n {\n StringBuilder sb = new StringBuilder();\n sb.append(_class.getName());\n sb.append('<');\n sb.append(_referencedType.toCanonical());\n return sb.toString();\n }\n"}, "reference": " protected String buildCanonicalName()\n {\n StringBuilder sb = new StringBuilder();\n sb.append(_class.getName());\n sb.append('<');\n sb.append(_referencedType.toCanonical());\n sb.append('>');\n return sb.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-99"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-99"}} {"sample_uid": "defects4j_function_repair::Math-40", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected double doSolve() {\n final double[] x = new double[maximalOrder + 1];\n final double[] y = new double[maximalOrder + 1];\n x[0] = getMin();\n x[1] = getStartValue();\n x[2] = getMax();\n verifySequence(x[0], x[1], x[2]);\n y[1] = computeObjectiveValue(x[1]);\n if (Precision.equals(y[1], 0.0, 1)) {\n return x[1];\n }\n y[0] = computeObjectiveValue(x[0]);\n if (Precision.equals(y[0], 0.0, 1)) {\n return x[0];\n }\n int nbPoints;\n int signChangeIndex;\n if (y[0] * y[1] < 0) {\n nbPoints = 2;\n signChangeIndex = 1;\n } else {\n y[2] = computeObjectiveValue(x[2]);\n if (Precision.equals(y[2], 0.0, 1)) {\n return x[2];\n }\n if (y[1] * y[2] < 0) {\n nbPoints = 3;\n signChangeIndex = 2;\n } else {\n throw new NoBracketingException(x[0], x[2], y[0], y[2]);\n }\n }\n final double[] tmpX = new double[x.length];\n double xA = x[signChangeIndex - 1];\n double yA = y[signChangeIndex - 1];\n double absYA = FastMath.abs(yA);\n int agingA = 0;\n double xB = x[signChangeIndex];\n double yB = y[signChangeIndex];\n double absYB = FastMath.abs(yB);\n int agingB = 0;\n while (true) {\n final double xTol = getAbsoluteAccuracy() +\n getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB));\n if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) {\n switch (allowed) {\n case ANY_SIDE :\n return absYA < absYB ? xA : xB;\n case LEFT_SIDE :\n return xA;\n case RIGHT_SIDE :\n return xB;\n case BELOW_SIDE :\n return (yA <= 0) ? xA : xB;\n case ABOVE_SIDE :\n return (yA < 0) ? xB : xA;\n default :\n throw new MathInternalError(null);\n }\n }\n double targetY;\n if (agingA >= MAXIMAL_AGING) {\n targetY = -REDUCTION_FACTOR * yB;\n } else if (agingB >= MAXIMAL_AGING) {\n targetY = -REDUCTION_FACTOR * yA;\n } else {\n targetY = 0;\n }\n double nextX;\n int start = 0;\n int end = nbPoints;\n do {\n System.arraycopy(x, start, tmpX, start, end - start);\n nextX = guessX(targetY, tmpX, y, start, end);\n if (!((nextX > xA) && (nextX < xB))) {\n if (signChangeIndex - start >= end - signChangeIndex) {\n ++start;\n } else {\n --end;\n }\n nextX = Double.NaN;\n }\n } while (Double.isNaN(nextX) && (end - start > 1));\n if (Double.isNaN(nextX)) {\n nextX = xA + 0.5 * (xB - xA);\n start = signChangeIndex - 1;\n end = signChangeIndex;\n }\n final double nextY = computeObjectiveValue(nextX);\n if (Precision.equals(nextY, 0.0, 1)) {\n return nextX;\n }\n if ((nbPoints > 2) && (end - start != nbPoints)) {\n nbPoints = end - start;\n System.arraycopy(x, start, x, 0, nbPoints);\n System.arraycopy(y, start, y, 0, nbPoints);\n signChangeIndex -= start;\n } else if (nbPoints == x.length) {\n nbPoints--;\n if (signChangeIndex >= (x.length + 1) / 2) {\n System.arraycopy(x, 1, x, 0, nbPoints);\n System.arraycopy(y, 1, y, 0, nbPoints);\n --signChangeIndex;\n }\n }\n System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex);\n x[signChangeIndex] = nextX;\n System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex);\n y[signChangeIndex] = nextY;\n ++nbPoints;\n if (nextY * yA <= 0) {\n xB = nextX;\n yB = nextY;\n absYB = FastMath.abs(yB);\n ++agingA;\n agingB = 0;\n } else {\n xA = nextX;\n yA = nextY;\n absYA = FastMath.abs(yA);\n agingA = 0;\n ++agingB;\n signChangeIndex++;\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected double doSolve() {\n final double[] x = new double[maximalOrder + 1];\n final double[] y = new double[maximalOrder + 1];\n x[0] = getMin();\n x[1] = getStartValue();\n x[2] = getMax();\n verifySequence(x[0], x[1], x[2]);\n y[1] = computeObjectiveValue(x[1]);\n if (Precision.equals(y[1], 0.0, 1)) {\n return x[1];\n }\n y[0] = computeObjectiveValue(x[0]);\n if (Precision.equals(y[0], 0.0, 1)) {\n return x[0];\n }\n int nbPoints;\n int signChangeIndex;\n if (y[0] * y[1] < 0) {\n nbPoints = 2;\n signChangeIndex = 1;\n } else {\n y[2] = computeObjectiveValue(x[2]);\n if (Precision.equals(y[2], 0.0, 1)) {\n return x[2];\n }\n if (y[1] * y[2] < 0) {\n nbPoints = 3;\n signChangeIndex = 2;\n } else {\n throw new NoBracketingException(x[0], x[2], y[0], y[2]);\n }\n }\n final double[] tmpX = new double[x.length];\n double xA = x[signChangeIndex - 1];\n double yA = y[signChangeIndex - 1];\n double absYA = FastMath.abs(yA);\n int agingA = 0;\n double xB = x[signChangeIndex];\n double yB = y[signChangeIndex];\n double absYB = FastMath.abs(yB);\n int agingB = 0;\n while (true) {\n final double xTol = getAbsoluteAccuracy() +\n getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB));\n if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) {\n switch (allowed) {\n case ANY_SIDE :\n return absYA < absYB ? xA : xB;\n case LEFT_SIDE :\n return xA;\n case RIGHT_SIDE :\n return xB;\n case BELOW_SIDE :\n return (yA <= 0) ? xA : xB;\n case ABOVE_SIDE :\n return (yA < 0) ? xB : xA;\n default :\n throw new MathInternalError(null);\n }\n }\n double targetY;\n if (agingA >= MAXIMAL_AGING) {\n targetY = -REDUCTION_FACTOR * yB;\n } else if (agingB >= MAXIMAL_AGING) {\n targetY = -REDUCTION_FACTOR * yA;\n } else {\n targetY = 0;\n }\n double nextX;\n int start = 0;\n int end = nbPoints;\n do {\n System.arraycopy(x, start, tmpX, start, end - start);\n nextX = guessX(targetY, tmpX, y, start, end);\n if (!((nextX > xA) && (nextX < xB))) {\n if (signChangeIndex - start >= end - signChangeIndex) {\n ++start;\n } else {\n --end;\n }\n nextX = Double.NaN;\n }\n } while (Double.isNaN(nextX) && (end - start > 1));\n if (Double.isNaN(nextX)) {\n nextX = xA + 0.5 * (xB - xA);\n start = signChangeIndex - 1;\n end = signChangeIndex;\n }\n final double nextY = computeObjectiveValue(nextX);\n if (Precision.equals(nextY, 0.0, 1)) {\n return nextX;\n }\n if ((nbPoints > 2) && (end - start != nbPoints)) {\n nbPoints = end - start;\n System.arraycopy(x, start, x, 0, nbPoints);\n System.arraycopy(y, start, y, 0, nbPoints);\n signChangeIndex -= start;\n } else if (nbPoints == x.length) {\n nbPoints--;\n if (signChangeIndex >= (x.length + 1) / 2) {\n System.arraycopy(x, 1, x, 0, nbPoints);\n System.arraycopy(y, 1, y, 0, nbPoints);\n --signChangeIndex;\n }\n }\n System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex);\n x[signChangeIndex] = nextX;\n System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex);\n y[signChangeIndex] = nextY;\n ++nbPoints;\n if (nextY * yA <= 0) {\n xB = nextX;\n yB = nextY;\n absYB = FastMath.abs(yB);\n ++agingA;\n agingB = 0;\n } else {\n xA = nextX;\n yA = nextY;\n absYA = FastMath.abs(yA);\n agingA = 0;\n ++agingB;\n signChangeIndex++;\n }\n }\n }\n"}, "reference": " protected double doSolve() {\n final double[] x = new double[maximalOrder + 1];\n final double[] y = new double[maximalOrder + 1];\n x[0] = getMin();\n x[1] = getStartValue();\n x[2] = getMax();\n verifySequence(x[0], x[1], x[2]);\n y[1] = computeObjectiveValue(x[1]);\n if (Precision.equals(y[1], 0.0, 1)) {\n return x[1];\n }\n y[0] = computeObjectiveValue(x[0]);\n if (Precision.equals(y[0], 0.0, 1)) {\n return x[0];\n }\n int nbPoints;\n int signChangeIndex;\n if (y[0] * y[1] < 0) {\n nbPoints = 2;\n signChangeIndex = 1;\n } else {\n y[2] = computeObjectiveValue(x[2]);\n if (Precision.equals(y[2], 0.0, 1)) {\n return x[2];\n }\n if (y[1] * y[2] < 0) {\n nbPoints = 3;\n signChangeIndex = 2;\n } else {\n throw new NoBracketingException(x[0], x[2], y[0], y[2]);\n }\n }\n final double[] tmpX = new double[x.length];\n double xA = x[signChangeIndex - 1];\n double yA = y[signChangeIndex - 1];\n double absYA = FastMath.abs(yA);\n int agingA = 0;\n double xB = x[signChangeIndex];\n double yB = y[signChangeIndex];\n double absYB = FastMath.abs(yB);\n int agingB = 0;\n while (true) {\n final double xTol = getAbsoluteAccuracy() +\n getRelativeAccuracy() * FastMath.max(FastMath.abs(xA), FastMath.abs(xB));\n if (((xB - xA) <= xTol) || (FastMath.max(absYA, absYB) < getFunctionValueAccuracy())) {\n switch (allowed) {\n case ANY_SIDE :\n return absYA < absYB ? xA : xB;\n case LEFT_SIDE :\n return xA;\n case RIGHT_SIDE :\n return xB;\n case BELOW_SIDE :\n return (yA <= 0) ? xA : xB;\n case ABOVE_SIDE :\n return (yA < 0) ? xB : xA;\n default :\n throw new MathInternalError(null);\n }\n }\n double targetY;\n if (agingA >= MAXIMAL_AGING) {\n final int p = agingA - MAXIMAL_AGING;\n final double weightA = (1 << p) - 1;\n final double weightB = p + 1;\n targetY = (weightA * yA - weightB * REDUCTION_FACTOR * yB) / (weightA + weightB);\n } else if (agingB >= MAXIMAL_AGING) {\n final int p = agingB - MAXIMAL_AGING;\n final double weightA = p + 1;\n final double weightB = (1 << p) - 1;\n targetY = (weightB * yB - weightA * REDUCTION_FACTOR * yA) / (weightA + weightB);\n } else {\n targetY = 0;\n }\n double nextX;\n int start = 0;\n int end = nbPoints;\n do {\n System.arraycopy(x, start, tmpX, start, end - start);\n nextX = guessX(targetY, tmpX, y, start, end);\n if (!((nextX > xA) && (nextX < xB))) {\n if (signChangeIndex - start >= end - signChangeIndex) {\n ++start;\n } else {\n --end;\n }\n nextX = Double.NaN;\n }\n } while (Double.isNaN(nextX) && (end - start > 1));\n if (Double.isNaN(nextX)) {\n nextX = xA + 0.5 * (xB - xA);\n start = signChangeIndex - 1;\n end = signChangeIndex;\n }\n final double nextY = computeObjectiveValue(nextX);\n if (Precision.equals(nextY, 0.0, 1)) {\n return nextX;\n }\n if ((nbPoints > 2) && (end - start != nbPoints)) {\n nbPoints = end - start;\n System.arraycopy(x, start, x, 0, nbPoints);\n System.arraycopy(y, start, y, 0, nbPoints);\n signChangeIndex -= start;\n } else if (nbPoints == x.length) {\n nbPoints--;\n if (signChangeIndex >= (x.length + 1) / 2) {\n System.arraycopy(x, 1, x, 0, nbPoints);\n System.arraycopy(y, 1, y, 0, nbPoints);\n --signChangeIndex;\n }\n }\n System.arraycopy(x, signChangeIndex, x, signChangeIndex + 1, nbPoints - signChangeIndex);\n x[signChangeIndex] = nextX;\n System.arraycopy(y, signChangeIndex, y, signChangeIndex + 1, nbPoints - signChangeIndex);\n y[signChangeIndex] = nextY;\n ++nbPoints;\n if (nextY * yA <= 0) {\n xB = nextX;\n yB = nextY;\n absYB = FastMath.abs(yB);\n ++agingA;\n agingB = 0;\n } else {\n xA = nextX;\n yA = nextY;\n absYA = FastMath.abs(yA);\n agingA = 0;\n ++agingB;\n signChangeIndex++;\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-40"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-40"}} {"sample_uid": "defects4j_function_repair::Jsoup-37", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public String html() {\n StringBuilder accum = new StringBuilder();\n html(accum);\n return accum.toString().trim();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public String html() {\n StringBuilder accum = new StringBuilder();\n html(accum);\n return accum.toString().trim();\n }\n"}, "reference": " public String html() {\n StringBuilder accum = new StringBuilder();\n html(accum);\n return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString();\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-37"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-37"}} {"sample_uid": "defects4j_function_repair::Cli-15", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public List getValues(final Option option,\n List defaultValues) {\n List valueList = (List) values.get(option);\n if ((valueList == null) || valueList.isEmpty()) {\n valueList = defaultValues;\n }\n if ((valueList == null) || valueList.isEmpty()) {\n valueList = (List) this.defaultValues.get(option);\n }\n return valueList == null ? Collections.EMPTY_LIST : valueList;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public List getValues(final Option option,\n List defaultValues) {\n List valueList = (List) values.get(option);\n if ((valueList == null) || valueList.isEmpty()) {\n valueList = defaultValues;\n }\n if ((valueList == null) || valueList.isEmpty()) {\n valueList = (List) this.defaultValues.get(option);\n }\n return valueList == null ? Collections.EMPTY_LIST : valueList;\n }\n"}, "reference": " public List getValues(final Option option,\n List defaultValues) {\n List valueList = (List) values.get(option);\n if (defaultValues == null || defaultValues.isEmpty()) {\n defaultValues = (List) this.defaultValues.get(option);\n }\n if (defaultValues != null && !defaultValues.isEmpty()) {\n if (valueList == null || valueList.isEmpty()) {\n valueList = defaultValues;\n } else {\n if (defaultValues.size() > valueList.size()) {\n valueList = new ArrayList(valueList);\n for (int i=valueList.size(); i 0) {\n long skipped = input.skip(numToSkip);\n if (skipped == 0) {\n break;\n }\n numToSkip -= skipped;\n }\n return available - numToSkip;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long skip(InputStream input, long numToSkip) throws IOException {\n long available = numToSkip;\n while (numToSkip > 0) {\n long skipped = input.skip(numToSkip);\n if (skipped == 0) {\n break;\n }\n numToSkip -= skipped;\n }\n return available - numToSkip;\n }\n"}, "reference": " public static long skip(InputStream input, long numToSkip) throws IOException {\n long available = numToSkip;\n while (numToSkip > 0) {\n long skipped = input.skip(numToSkip);\n if (skipped == 0) {\n break;\n }\n numToSkip -= skipped;\n }\n if (numToSkip > 0) {\n byte[] skipBuf = new byte[SKIP_BUF_SIZE];\n while (numToSkip > 0) {\n int read = readFully(input, skipBuf, 0,\n (int) Math.min(numToSkip, SKIP_BUF_SIZE));\n if (read < 1) {\n break;\n }\n numToSkip -= read;\n }\n }\n return available - numToSkip;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-26"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-26"}} {"sample_uid": "defects4j_function_repair::Compress-31", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte == 0) {\n break;\n }\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte == 0) {\n break;\n }\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n"}, "reference": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer = buffer[end - 1];\n while (start < end && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-31"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-31"}} {"sample_uid": "defects4j_function_repair::Lang-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (start == 0 && end == 0) {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (start == 0 && end == 0) {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n"}, "reference": " public static String random(int count, int start, int end, boolean letters, boolean numbers,\n char[] chars, Random random) {\n if (count == 0) {\n return \"\";\n } else if (count < 0) {\n throw new IllegalArgumentException(\"Requested random string length \" + count + \" is less than 0.\");\n }\n if (chars != null && chars.length == 0) {\n throw new IllegalArgumentException(\"The chars array must not be empty\");\n }\n if (start == 0 && end == 0) {\n if (chars != null) {\n end = chars.length;\n } else {\n if (!letters && !numbers) {\n end = Integer.MAX_VALUE;\n } else {\n end = 'z' + 1;\n start = ' '; \n }\n }\n }\n char[] buffer = new char[count];\n int gap = end - start;\n while (count-- != 0) {\n char ch;\n if (chars == null) {\n ch = (char) (random.nextInt(gap) + start);\n } else {\n ch = chars[random.nextInt(gap) + start];\n }\n if (letters && Character.isLetter(ch)\n || numbers && Character.isDigit(ch)\n || !letters && !numbers) {\n if(ch >= 56320 && ch <= 57343) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = ch;\n count--;\n buffer[count] = (char) (55296 + random.nextInt(128));\n }\n } else if(ch >= 55296 && ch <= 56191) {\n if(count == 0) {\n count++;\n } else {\n buffer[count] = (char) (56320 + random.nextInt(128));\n count--;\n buffer[count] = ch;\n }\n } else if(ch >= 56192 && ch <= 56319) {\n count++;\n } else {\n buffer[count] = ch;\n }\n } else {\n count++;\n }\n }\n return new String(buffer);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Lang-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Lang-12"}} {"sample_uid": "defects4j_function_repair::Compress-44", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) {\n this.checksum = checksum;\n this.in = in;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) {\n this.checksum = checksum;\n this.in = in;\n }\n"}, "reference": " public ChecksumCalculatingInputStream(final Checksum checksum, final InputStream in) {\n if ( checksum == null ){\n throw new NullPointerException(\"Parameter checksum must not be null\");\n }\n if ( in == null ){\n throw new NullPointerException(\"Parameter in must not be null\");\n }\n this.checksum = checksum;\n this.in = in;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-44"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-44"}} {"sample_uid": "defects4j_function_repair::Time-8", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException {\n if (hoursOffset == 0 && minutesOffset == 0) {\n return DateTimeZone.UTC;\n }\n if (hoursOffset < -23 || hoursOffset > 23) {\n throw new IllegalArgumentException(\"Hours out of range: \" + hoursOffset);\n }\n if (minutesOffset < 0 || minutesOffset > 59) {\n throw new IllegalArgumentException(\"Minutes out of range: \" + minutesOffset);\n }\n int offset = 0;\n try {\n int hoursInMinutes = hoursOffset * 60;\n if (hoursInMinutes < 0) {\n minutesOffset = hoursInMinutes - minutesOffset;\n } else {\n minutesOffset = hoursInMinutes + minutesOffset;\n }\n offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE);\n } catch (ArithmeticException ex) {\n throw new IllegalArgumentException(\"Offset is too large\");\n }\n return forOffsetMillis(offset);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException {\n if (hoursOffset == 0 && minutesOffset == 0) {\n return DateTimeZone.UTC;\n }\n if (hoursOffset < -23 || hoursOffset > 23) {\n throw new IllegalArgumentException(\"Hours out of range: \" + hoursOffset);\n }\n if (minutesOffset < 0 || minutesOffset > 59) {\n throw new IllegalArgumentException(\"Minutes out of range: \" + minutesOffset);\n }\n int offset = 0;\n try {\n int hoursInMinutes = hoursOffset * 60;\n if (hoursInMinutes < 0) {\n minutesOffset = hoursInMinutes - minutesOffset;\n } else {\n minutesOffset = hoursInMinutes + minutesOffset;\n }\n offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE);\n } catch (ArithmeticException ex) {\n throw new IllegalArgumentException(\"Offset is too large\");\n }\n return forOffsetMillis(offset);\n }\n"}, "reference": " public static DateTimeZone forOffsetHoursMinutes(int hoursOffset, int minutesOffset) throws IllegalArgumentException {\n if (hoursOffset == 0 && minutesOffset == 0) {\n return DateTimeZone.UTC;\n }\n if (hoursOffset < -23 || hoursOffset > 23) {\n throw new IllegalArgumentException(\"Hours out of range: \" + hoursOffset);\n }\n if (minutesOffset < -59 || minutesOffset > 59) {\n throw new IllegalArgumentException(\"Minutes out of range: \" + minutesOffset);\n }\n if (hoursOffset > 0 && minutesOffset < 0) {\n throw new IllegalArgumentException(\"Positive hours must not have negative minutes: \" + minutesOffset);\n }\n int offset = 0;\n try {\n int hoursInMinutes = hoursOffset * 60;\n if (hoursInMinutes < 0) {\n minutesOffset = hoursInMinutes - Math.abs(minutesOffset);\n } else {\n minutesOffset = hoursInMinutes + minutesOffset;\n }\n offset = FieldUtils.safeMultiply(minutesOffset, DateTimeConstants.MILLIS_PER_MINUTE);\n } catch (ArithmeticException ex) {\n throw new IllegalArgumentException(\"Offset is too large\");\n }\n return forOffsetMillis(offset);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Time-8"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Time-8"}} {"sample_uid": "defects4j_function_repair::Math-2", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public double getNumericalMean() {\n return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize();\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public double getNumericalMean() {\n return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize();\n }\n"}, "reference": " public double getNumericalMean() {\n return getSampleSize() * (getNumberOfSuccesses() / (double) getPopulationSize());\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-2"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-2"}} {"sample_uid": "defects4j_function_repair::Csv-14", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (newRecord && (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')) {\n quote = true;\n } else if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (newRecord && (c < '0' || c > '9' && c < 'A' || c > 'Z' && c < 'a' || c > 'z')) {\n quote = true;\n } else if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n"}, "reference": " private void printAndQuote(final Object object, final CharSequence value, final int offset, final int len,\n final Appendable out, final boolean newRecord) throws IOException {\n boolean quote = false;\n int start = offset;\n int pos = offset;\n final int end = offset + len;\n final char delimChar = getDelimiter();\n final char quoteChar = getQuoteCharacter().charValue();\n QuoteMode quoteModePolicy = getQuoteMode();\n if (quoteModePolicy == null) {\n quoteModePolicy = QuoteMode.MINIMAL;\n }\n switch (quoteModePolicy) {\n case ALL:\n quote = true;\n break;\n case NON_NUMERIC:\n quote = !(object instanceof Number);\n break;\n case NONE:\n printAndEscape(value, offset, len, out);\n return;\n case MINIMAL:\n if (len <= 0) {\n if (newRecord) {\n quote = true;\n }\n } else {\n char c = value.charAt(pos);\n if (newRecord && (c < 0x20 || c > 0x21 && c < 0x23 || c > 0x2B && c < 0x2D || c > 0x7E)) {\n quote = true;\n } else if (c <= COMMENT) {\n quote = true;\n } else {\n while (pos < end) {\n c = value.charAt(pos);\n if (c == LF || c == CR || c == quoteChar || c == delimChar) {\n quote = true;\n break;\n }\n pos++;\n }\n if (!quote) {\n pos = end - 1;\n c = value.charAt(pos);\n if (c <= SP) {\n quote = true;\n }\n }\n }\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n break;\n default:\n throw new IllegalStateException(\"Unexpected Quote value: \" + quoteModePolicy);\n }\n if (!quote) {\n out.append(value, start, end);\n return;\n }\n out.append(quoteChar);\n while (pos < end) {\n final char c = value.charAt(pos);\n if (c == quoteChar) {\n out.append(value, start, pos + 1);\n start = pos;\n }\n pos++;\n }\n out.append(value, start, pos);\n out.append(quoteChar);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Csv-14"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Csv-14"}} {"sample_uid": "defects4j_function_repair::JacksonDatabind-85", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property == null) {\n return this;\n }\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()\n || format.hasLocale() || format.hasTimeZone()) {\n TimeZone tz = format.getTimeZone();\n final String pattern = format.hasPattern()\n ? format.getPattern()\n : StdDateFormat.DATE_FORMAT_STR_ISO8601;\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(pattern, loc);\n if (tz == null) {\n tz = serializers.getTimeZone();\n }\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n return this;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property == null) {\n return this;\n }\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()\n || format.hasLocale() || format.hasTimeZone()) {\n TimeZone tz = format.getTimeZone();\n final String pattern = format.hasPattern()\n ? format.getPattern()\n : StdDateFormat.DATE_FORMAT_STR_ISO8601;\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(pattern, loc);\n if (tz == null) {\n tz = serializers.getTimeZone();\n }\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n return this;\n }\n"}, "reference": " public JsonSerializer createContextual(SerializerProvider serializers,\n BeanProperty property) throws JsonMappingException\n {\n if (property == null) {\n return this;\n }\n JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());\n if (format == null) {\n return this;\n }\n JsonFormat.Shape shape = format.getShape();\n if (shape.isNumeric()) {\n return withFormat(Boolean.TRUE, null);\n }\n if (format.hasPattern()) {\n final Locale loc = format.hasLocale()\n ? format.getLocale()\n : serializers.getLocale();\n SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);\n TimeZone tz = format.hasTimeZone() ? format.getTimeZone()\n : serializers.getTimeZone();\n df.setTimeZone(tz);\n return withFormat(Boolean.FALSE, df);\n }\n final boolean hasLocale = format.hasLocale();\n final boolean hasTZ = format.hasTimeZone();\n final boolean asString = (shape == JsonFormat.Shape.STRING);\n if (!hasLocale && !hasTZ && !asString) {\n return this;\n }\n DateFormat df0 = serializers.getConfig().getDateFormat();\n if (df0 instanceof StdDateFormat) {\n StdDateFormat std = (StdDateFormat) df0;\n if (format.hasLocale()) {\n std = std.withLocale(format.getLocale());\n }\n if (format.hasTimeZone()) {\n std = std.withTimeZone(format.getTimeZone());\n }\n return withFormat(Boolean.FALSE, std);\n }\n if (!(df0 instanceof SimpleDateFormat)) {\n serializers.reportMappingProblem(\n\"Configured `DateFormat` (%s) not a `SimpleDateFormat`; can not configure `Locale` or `TimeZone`\",\ndf0.getClass().getName());\n }\n SimpleDateFormat df = (SimpleDateFormat) df0;\n if (hasLocale) {\n df = new SimpleDateFormat(df.toPattern(), format.getLocale());\n } else {\n df = (SimpleDateFormat) df.clone();\n }\n TimeZone newTz = format.getTimeZone();\n boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());\n if (changeTZ) {\n df.setTimeZone(newTz);\n }\n return withFormat(Boolean.FALSE, df);\n }\n", "tests": {}, "repo_meta": {"bug_id": "JacksonDatabind-85"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "JacksonDatabind-85"}} {"sample_uid": "defects4j_function_repair::Compress-17", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end - 1];\n if (trailer == 0 || trailer == ' '){\n end--;\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end - 1];\n if (trailer == 0 || trailer == ' '){\n end--;\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n"}, "reference": " public static long parseOctal(final byte[] buffer, final int offset, final int length) {\n long result = 0;\n int end = offset + length;\n int start = offset;\n if (length < 2){\n throw new IllegalArgumentException(\"Length \"+length+\" must be at least 2\");\n }\n if (buffer[start] == 0) {\n return 0L;\n }\n while (start < end){\n if (buffer[start] == ' '){\n start++;\n } else {\n break;\n }\n }\n byte trailer;\n trailer = buffer[end-1];\n if (trailer == 0 || trailer == ' '){\n end--;\n } else {\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, end-1, trailer));\n }\n trailer = buffer[end - 1];\n while (start < end - 1 && (trailer == 0 || trailer == ' ')) {\n end--;\n trailer = buffer[end - 1];\n }\n for ( ;start < end; start++) {\n final byte currentByte = buffer[start];\n if (currentByte < '0' || currentByte > '7'){\n throw new IllegalArgumentException(\n exceptionMessage(buffer, offset, length, start, currentByte));\n }\n result = (result << 3) + (currentByte - '0'); \n }\n return result;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Compress-17"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Compress-17"}} {"sample_uid": "defects4j_function_repair::Math-88", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected RealPointValuePair getSolution() {\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n Integer basicRow =\n getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());\n double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());\n for (int i = 0; i < coefficients.length; i++) {\n basicRow = getBasicRow(getNumObjectiveFunctions() + i);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n if (basicRow != null) {\n for (int j = getNumObjectiveFunctions(); j < getNumObjectiveFunctions() + i; j++) {\n if (tableau.getEntry(basicRow, j) == 1) {\n coefficients[i] = 0;\n }\n }\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected RealPointValuePair getSolution() {\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n Integer basicRow =\n getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());\n double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());\n for (int i = 0; i < coefficients.length; i++) {\n basicRow = getBasicRow(getNumObjectiveFunctions() + i);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n if (basicRow != null) {\n for (int j = getNumObjectiveFunctions(); j < getNumObjectiveFunctions() + i; j++) {\n if (tableau.getEntry(basicRow, j) == 1) {\n coefficients[i] = 0;\n }\n }\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n"}, "reference": " protected RealPointValuePair getSolution() {\n double[] coefficients = new double[getOriginalNumDecisionVariables()];\n Integer basicRow =\n getBasicRow(getNumObjectiveFunctions() + getOriginalNumDecisionVariables());\n double mostNegative = basicRow == null ? 0 : getEntry(basicRow, getRhsOffset());\n Set basicRows = new HashSet();\n for (int i = 0; i < coefficients.length; i++) {\n basicRow = getBasicRow(getNumObjectiveFunctions() + i);\n if (basicRows.contains(basicRow)) {\n coefficients[i] = 0;\n } else {\n basicRows.add(basicRow);\n coefficients[i] =\n (basicRow == null ? 0 : getEntry(basicRow, getRhsOffset())) -\n (restrictToNonNegative ? 0 : mostNegative);\n }\n }\n return new RealPointValuePair(coefficients, f.getValue(coefficients));\n }\n", "tests": {}, "repo_meta": {"bug_id": "Math-88"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Math-88"}} {"sample_uid": "defects4j_function_repair::Closure-91", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.isInterface() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN ||\n pType == Token.STRING ||\n pType == Token.NUMBER)) {\n return false;\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (NodeUtil.isGet(lhs)) {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n Node llhs = lhs.getFirstChild();\n if (llhs.getType() == Token.GETPROP &&\n llhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n }\n }\n }\n return true;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.isInterface() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN ||\n pType == Token.STRING ||\n pType == Token.NUMBER)) {\n return false;\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (NodeUtil.isGet(lhs)) {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n Node llhs = lhs.getFirstChild();\n if (llhs.getType() == Token.GETPROP &&\n llhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n }\n }\n }\n return true;\n }\n"}, "reference": " public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {\n if (n.getType() == Token.FUNCTION) {\n JSDocInfo jsDoc = getFunctionJsDocInfo(n);\n if (jsDoc != null &&\n (jsDoc.isConstructor() ||\n jsDoc.isInterface() ||\n jsDoc.hasThisType() ||\n jsDoc.isOverride())) {\n return false;\n }\n int pType = parent.getType();\n if (!(pType == Token.BLOCK ||\n pType == Token.SCRIPT ||\n pType == Token.NAME ||\n pType == Token.ASSIGN ||\n pType == Token.STRING ||\n pType == Token.NUMBER)) {\n return false;\n }\n Node gramps = parent.getParent();\n if (NodeUtil.isObjectLitKey(parent, gramps)) {\n JSDocInfo maybeLends = gramps.getJSDocInfo();\n if (maybeLends != null &&\n maybeLends.getLendsName() != null &&\n maybeLends.getLendsName().endsWith(\".prototype\")) {\n return false;\n }\n }\n }\n if (parent != null && parent.getType() == Token.ASSIGN) {\n Node lhs = parent.getFirstChild();\n Node rhs = lhs.getNext();\n if (n == lhs) {\n if (assignLhsChild == null) {\n assignLhsChild = lhs;\n }\n } else {\n if (NodeUtil.isGet(lhs)) {\n if (lhs.getType() == Token.GETPROP &&\n lhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n Node llhs = lhs.getFirstChild();\n if (llhs.getType() == Token.GETPROP &&\n llhs.getLastChild().getString().equals(\"prototype\")) {\n return false;\n }\n }\n }\n }\n return true;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-91"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-91"}} {"sample_uid": "defects4j_function_repair::Closure-113", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private void processRequireCall(NodeTraversal t, Node n, Node parent) {\n Node left = n.getFirstChild();\n Node arg = left.getNext();\n if (verifyLastArgumentIsString(t, left, arg)) {\n String ns = arg.getString();\n ProvidedName provided = providedNames.get(ns);\n if (provided == null || !provided.isExplicitlyProvided()) {\n unrecognizedRequires.add(\n new UnrecognizedRequire(n, ns, t.getSourceName()));\n } else {\n JSModule providedModule = provided.explicitModule;\n Preconditions.checkNotNull(providedModule);\n JSModule module = t.getModule();\n if (moduleGraph != null &&\n module != providedModule &&\n !moduleGraph.dependsOn(module, providedModule)) {\n compiler.report(\n t.makeError(n, XMODULE_REQUIRE_ERROR, ns,\n providedModule.getName(),\n module.getName()));\n }\n }\n maybeAddToSymbolTable(left);\n maybeAddStringNodeToSymbolTable(arg);\n if (provided != null) {\n parent.detachFromParent();\n compiler.reportCodeChange();\n }\n }\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private void processRequireCall(NodeTraversal t, Node n, Node parent) {\n Node left = n.getFirstChild();\n Node arg = left.getNext();\n if (verifyLastArgumentIsString(t, left, arg)) {\n String ns = arg.getString();\n ProvidedName provided = providedNames.get(ns);\n if (provided == null || !provided.isExplicitlyProvided()) {\n unrecognizedRequires.add(\n new UnrecognizedRequire(n, ns, t.getSourceName()));\n } else {\n JSModule providedModule = provided.explicitModule;\n Preconditions.checkNotNull(providedModule);\n JSModule module = t.getModule();\n if (moduleGraph != null &&\n module != providedModule &&\n !moduleGraph.dependsOn(module, providedModule)) {\n compiler.report(\n t.makeError(n, XMODULE_REQUIRE_ERROR, ns,\n providedModule.getName(),\n module.getName()));\n }\n }\n maybeAddToSymbolTable(left);\n maybeAddStringNodeToSymbolTable(arg);\n if (provided != null) {\n parent.detachFromParent();\n compiler.reportCodeChange();\n }\n }\n }\n"}, "reference": " private void processRequireCall(NodeTraversal t, Node n, Node parent) {\n Node left = n.getFirstChild();\n Node arg = left.getNext();\n if (verifyLastArgumentIsString(t, left, arg)) {\n String ns = arg.getString();\n ProvidedName provided = providedNames.get(ns);\n if (provided == null || !provided.isExplicitlyProvided()) {\n unrecognizedRequires.add(\n new UnrecognizedRequire(n, ns, t.getSourceName()));\n } else {\n JSModule providedModule = provided.explicitModule;\n Preconditions.checkNotNull(providedModule);\n JSModule module = t.getModule();\n if (moduleGraph != null &&\n module != providedModule &&\n !moduleGraph.dependsOn(module, providedModule)) {\n compiler.report(\n t.makeError(n, XMODULE_REQUIRE_ERROR, ns,\n providedModule.getName(),\n module.getName()));\n }\n }\n maybeAddToSymbolTable(left);\n maybeAddStringNodeToSymbolTable(arg);\n if (provided != null || requiresLevel.isOn()) {\n parent.detachFromParent();\n compiler.reportCodeChange();\n }\n }\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-113"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-113"}} {"sample_uid": "defects4j_function_repair::Closure-111", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n protected JSType caseTopType(JSType topType) {\n return topType;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " protected JSType caseTopType(JSType topType) {\n return topType;\n }\n"}, "reference": " protected JSType caseTopType(JSType topType) {\n return topType.isAllType() ?\n getNativeType(ARRAY_TYPE) : topType;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-111"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-111"}} {"sample_uid": "defects4j_function_repair::Closure-12", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private boolean hasExceptionHandler(Node cfgNode) {\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private boolean hasExceptionHandler(Node cfgNode) {\n return false;\n }\n"}, "reference": " private boolean hasExceptionHandler(Node cfgNode) {\n List> branchEdges = getCfg().getOutEdges(cfgNode);\n for (DiGraphEdge edge : branchEdges) {\n if (edge.getValue() == Branch.ON_EX) {\n return true;\n }\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-12"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-12"}} {"sample_uid": "defects4j_function_repair::Jsoup-70", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n static boolean preserveWhitespace(Node node) {\n if (node != null && node instanceof Element) {\n Element el = (Element) node;\n if (el.tag.preserveWhitespace())\n return true;\n else\n return el.parent() != null && el.parent().tag.preserveWhitespace();\n }\n return false;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " static boolean preserveWhitespace(Node node) {\n if (node != null && node instanceof Element) {\n Element el = (Element) node;\n if (el.tag.preserveWhitespace())\n return true;\n else\n return el.parent() != null && el.parent().tag.preserveWhitespace();\n }\n return false;\n }\n"}, "reference": " static boolean preserveWhitespace(Node node) {\n if (node != null && node instanceof Element) {\n Element el = (Element) node;\n int i = 0;\n do {\n if (el.tag.preserveWhitespace())\n return true;\n el = el.parent();\n i++;\n } while (i < 6 && el != null);\n }\n return false;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Jsoup-70"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Jsoup-70"}} {"sample_uid": "defects4j_function_repair::Closure-66", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n public void visit(NodeTraversal t, Node n, Node parent) {\n JSType childType;\n JSType leftType, rightType;\n Node left, right;\n boolean typeable = true;\n switch (n.getType()) {\n case Token.NAME:\n typeable = visitName(t, n, parent);\n break;\n case Token.LP:\n if (parent.getType() != Token.FUNCTION) {\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n } else {\n typeable = false;\n }\n break;\n case Token.COMMA:\n ensureTyped(t, n, getJSType(n.getLastChild()));\n break;\n case Token.TRUE:\n case Token.FALSE:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.THIS:\n ensureTyped(t, n, t.getScope().getTypeOfThis());\n break;\n case Token.REF_SPECIAL:\n ensureTyped(t, n);\n break;\n case Token.GET_REF:\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n break;\n case Token.NULL:\n ensureTyped(t, n, NULL_TYPE);\n break;\n case Token.NUMBER:\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.STRING:\n if (!NodeUtil.isObjectLitKey(n, n.getParent())) {\n ensureTyped(t, n, STRING_TYPE);\n }\n break;\n case Token.GET:\n case Token.SET:\n break;\n case Token.ARRAYLIT:\n ensureTyped(t, n, ARRAY_TYPE);\n break;\n case Token.REGEXP:\n ensureTyped(t, n, REGEXP_TYPE);\n break;\n case Token.GETPROP:\n visitGetProp(t, n, parent);\n typeable = !(parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == n);\n break;\n case Token.GETELEM:\n visitGetElem(t, n);\n typeable = false;\n break;\n case Token.VAR:\n visitVar(t, n);\n typeable = false;\n break;\n case Token.NEW:\n visitNew(t, n);\n typeable = true;\n break;\n case Token.CALL:\n visitCall(t, n);\n typeable = !NodeUtil.isExpressionNode(parent);\n break;\n case Token.RETURN:\n visitReturn(t, n);\n typeable = false;\n break;\n case Token.DEC:\n case Token.INC:\n left = n.getFirstChild();\n validator.expectNumber(\n t, left, getJSType(left), \"increment/decrement\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.NOT:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.VOID:\n ensureTyped(t, n, VOID_TYPE);\n break;\n case Token.TYPEOF:\n ensureTyped(t, n, STRING_TYPE);\n break;\n case Token.BITNOT:\n childType = getJSType(n.getFirstChild());\n if (!childType.matchesInt32Context()) {\n report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()),\n childType.toString());\n }\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.POS:\n case Token.NEG:\n left = n.getFirstChild();\n validator.expectNumber(t, left, getJSType(left), \"sign operator\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.EQ:\n case Token.NE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n TernaryValue result =\n leftTypeRestricted.testForEquality(rightTypeRestricted);\n if (result != TernaryValue.UNKNOWN) {\n if (n.getType() == Token.NE) {\n result = result.not();\n }\n report(t, n, DETERMINISTIC_TEST, leftType.toString(),\n rightType.toString(), result.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.SHEQ:\n case Token.SHNE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n if (!leftTypeRestricted.canTestForShallowEqualityWith(\n rightTypeRestricted)) {\n report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(),\n rightType.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.LT:\n case Token.LE:\n case Token.GT:\n case Token.GE:\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n if (rightType.isNumber()) {\n validator.expectNumber(\n t, n, leftType, \"left side of numeric comparison\");\n } else if (leftType.isNumber()) {\n validator.expectNumber(\n t, n, rightType, \"right side of numeric comparison\");\n } else if (leftType.matchesNumberContext() &&\n rightType.matchesNumberContext()) {\n } else {\n String message = \"left side of comparison\";\n validator.expectString(t, n, leftType, message);\n validator.expectNotNullOrUndefined(\n t, n, leftType, message, getNativeType(STRING_TYPE));\n message = \"right side of comparison\";\n validator.expectString(t, n, rightType, message);\n validator.expectNotNullOrUndefined(\n t, n, rightType, message, getNativeType(STRING_TYPE));\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.IN:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right);\n validator.expectObject(t, n, rightType, \"'in' requires an object\");\n validator.expectString(t, left, leftType, \"left side of 'in'\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.INSTANCEOF:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right).restrictByNotNullOrUndefined();\n validator.expectAnyObject(\n t, left, leftType, \"deterministic instanceof yields false\");\n validator.expectActualObject(\n t, right, rightType, \"instanceof requires an object\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.ASSIGN:\n visitAssign(t, n);\n typeable = false;\n break;\n case Token.ASSIGN_LSH:\n case Token.ASSIGN_RSH:\n case Token.ASSIGN_URSH:\n case Token.ASSIGN_DIV:\n case Token.ASSIGN_MOD:\n case Token.ASSIGN_BITOR:\n case Token.ASSIGN_BITXOR:\n case Token.ASSIGN_BITAND:\n case Token.ASSIGN_SUB:\n case Token.ASSIGN_ADD:\n case Token.ASSIGN_MUL:\n case Token.LSH:\n case Token.RSH:\n case Token.URSH:\n case Token.DIV:\n case Token.MOD:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.BITAND:\n case Token.SUB:\n case Token.ADD:\n case Token.MUL:\n visitBinaryOperator(n.getType(), t, n);\n break;\n case Token.DELPROP:\n if (!isReference(n.getFirstChild())) {\n report(t, n, BAD_DELETE);\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.CASE:\n JSType switchType = getJSType(parent.getFirstChild());\n JSType caseType = getJSType(n.getFirstChild());\n validator.expectSwitchMatchesCase(t, n, switchType, caseType);\n typeable = false;\n break;\n case Token.WITH: {\n Node child = n.getFirstChild();\n childType = getJSType(child);\n validator.expectObject(\n t, child, childType, \"with requires an object\");\n typeable = false;\n break;\n }\n case Token.FUNCTION:\n visitFunction(t, n);\n break;\n case Token.LABEL:\n case Token.LABEL_NAME:\n case Token.SWITCH:\n case Token.BREAK:\n case Token.CATCH:\n case Token.TRY:\n case Token.SCRIPT:\n case Token.EXPR_RESULT:\n case Token.BLOCK:\n case Token.EMPTY:\n case Token.DEFAULT:\n case Token.CONTINUE:\n case Token.DEBUGGER:\n case Token.THROW:\n typeable = false;\n break;\n case Token.DO:\n case Token.FOR:\n case Token.IF:\n case Token.WHILE:\n typeable = false;\n break;\n case Token.AND:\n case Token.HOOK:\n case Token.OBJECTLIT:\n case Token.OR:\n if (n.getJSType() != null) { \n ensureTyped(t, n);\n } else {\n if ((n.getType() == Token.OBJECTLIT)\n && (parent.getJSType() instanceof EnumType)) {\n ensureTyped(t, n, parent.getJSType());\n } else {\n ensureTyped(t, n);\n }\n }\n if (n.getType() == Token.OBJECTLIT) {\n for (Node key : n.children()) {\n visitObjLitKey(t, key, n);\n }\n }\n break;\n default:\n report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType()));\n ensureTyped(t, n);\n break;\n }\n typeable = typeable && !inExterns;\n if (typeable) {\n doPercentTypedAccounting(t, n);\n }\n checkNoTypeCheckSection(n, false);\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " public void visit(NodeTraversal t, Node n, Node parent) {\n JSType childType;\n JSType leftType, rightType;\n Node left, right;\n boolean typeable = true;\n switch (n.getType()) {\n case Token.NAME:\n typeable = visitName(t, n, parent);\n break;\n case Token.LP:\n if (parent.getType() != Token.FUNCTION) {\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n } else {\n typeable = false;\n }\n break;\n case Token.COMMA:\n ensureTyped(t, n, getJSType(n.getLastChild()));\n break;\n case Token.TRUE:\n case Token.FALSE:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.THIS:\n ensureTyped(t, n, t.getScope().getTypeOfThis());\n break;\n case Token.REF_SPECIAL:\n ensureTyped(t, n);\n break;\n case Token.GET_REF:\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n break;\n case Token.NULL:\n ensureTyped(t, n, NULL_TYPE);\n break;\n case Token.NUMBER:\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.STRING:\n if (!NodeUtil.isObjectLitKey(n, n.getParent())) {\n ensureTyped(t, n, STRING_TYPE);\n }\n break;\n case Token.GET:\n case Token.SET:\n break;\n case Token.ARRAYLIT:\n ensureTyped(t, n, ARRAY_TYPE);\n break;\n case Token.REGEXP:\n ensureTyped(t, n, REGEXP_TYPE);\n break;\n case Token.GETPROP:\n visitGetProp(t, n, parent);\n typeable = !(parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == n);\n break;\n case Token.GETELEM:\n visitGetElem(t, n);\n typeable = false;\n break;\n case Token.VAR:\n visitVar(t, n);\n typeable = false;\n break;\n case Token.NEW:\n visitNew(t, n);\n typeable = true;\n break;\n case Token.CALL:\n visitCall(t, n);\n typeable = !NodeUtil.isExpressionNode(parent);\n break;\n case Token.RETURN:\n visitReturn(t, n);\n typeable = false;\n break;\n case Token.DEC:\n case Token.INC:\n left = n.getFirstChild();\n validator.expectNumber(\n t, left, getJSType(left), \"increment/decrement\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.NOT:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.VOID:\n ensureTyped(t, n, VOID_TYPE);\n break;\n case Token.TYPEOF:\n ensureTyped(t, n, STRING_TYPE);\n break;\n case Token.BITNOT:\n childType = getJSType(n.getFirstChild());\n if (!childType.matchesInt32Context()) {\n report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()),\n childType.toString());\n }\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.POS:\n case Token.NEG:\n left = n.getFirstChild();\n validator.expectNumber(t, left, getJSType(left), \"sign operator\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.EQ:\n case Token.NE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n TernaryValue result =\n leftTypeRestricted.testForEquality(rightTypeRestricted);\n if (result != TernaryValue.UNKNOWN) {\n if (n.getType() == Token.NE) {\n result = result.not();\n }\n report(t, n, DETERMINISTIC_TEST, leftType.toString(),\n rightType.toString(), result.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.SHEQ:\n case Token.SHNE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n if (!leftTypeRestricted.canTestForShallowEqualityWith(\n rightTypeRestricted)) {\n report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(),\n rightType.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.LT:\n case Token.LE:\n case Token.GT:\n case Token.GE:\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n if (rightType.isNumber()) {\n validator.expectNumber(\n t, n, leftType, \"left side of numeric comparison\");\n } else if (leftType.isNumber()) {\n validator.expectNumber(\n t, n, rightType, \"right side of numeric comparison\");\n } else if (leftType.matchesNumberContext() &&\n rightType.matchesNumberContext()) {\n } else {\n String message = \"left side of comparison\";\n validator.expectString(t, n, leftType, message);\n validator.expectNotNullOrUndefined(\n t, n, leftType, message, getNativeType(STRING_TYPE));\n message = \"right side of comparison\";\n validator.expectString(t, n, rightType, message);\n validator.expectNotNullOrUndefined(\n t, n, rightType, message, getNativeType(STRING_TYPE));\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.IN:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right);\n validator.expectObject(t, n, rightType, \"'in' requires an object\");\n validator.expectString(t, left, leftType, \"left side of 'in'\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.INSTANCEOF:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right).restrictByNotNullOrUndefined();\n validator.expectAnyObject(\n t, left, leftType, \"deterministic instanceof yields false\");\n validator.expectActualObject(\n t, right, rightType, \"instanceof requires an object\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.ASSIGN:\n visitAssign(t, n);\n typeable = false;\n break;\n case Token.ASSIGN_LSH:\n case Token.ASSIGN_RSH:\n case Token.ASSIGN_URSH:\n case Token.ASSIGN_DIV:\n case Token.ASSIGN_MOD:\n case Token.ASSIGN_BITOR:\n case Token.ASSIGN_BITXOR:\n case Token.ASSIGN_BITAND:\n case Token.ASSIGN_SUB:\n case Token.ASSIGN_ADD:\n case Token.ASSIGN_MUL:\n case Token.LSH:\n case Token.RSH:\n case Token.URSH:\n case Token.DIV:\n case Token.MOD:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.BITAND:\n case Token.SUB:\n case Token.ADD:\n case Token.MUL:\n visitBinaryOperator(n.getType(), t, n);\n break;\n case Token.DELPROP:\n if (!isReference(n.getFirstChild())) {\n report(t, n, BAD_DELETE);\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.CASE:\n JSType switchType = getJSType(parent.getFirstChild());\n JSType caseType = getJSType(n.getFirstChild());\n validator.expectSwitchMatchesCase(t, n, switchType, caseType);\n typeable = false;\n break;\n case Token.WITH: {\n Node child = n.getFirstChild();\n childType = getJSType(child);\n validator.expectObject(\n t, child, childType, \"with requires an object\");\n typeable = false;\n break;\n }\n case Token.FUNCTION:\n visitFunction(t, n);\n break;\n case Token.LABEL:\n case Token.LABEL_NAME:\n case Token.SWITCH:\n case Token.BREAK:\n case Token.CATCH:\n case Token.TRY:\n case Token.SCRIPT:\n case Token.EXPR_RESULT:\n case Token.BLOCK:\n case Token.EMPTY:\n case Token.DEFAULT:\n case Token.CONTINUE:\n case Token.DEBUGGER:\n case Token.THROW:\n typeable = false;\n break;\n case Token.DO:\n case Token.FOR:\n case Token.IF:\n case Token.WHILE:\n typeable = false;\n break;\n case Token.AND:\n case Token.HOOK:\n case Token.OBJECTLIT:\n case Token.OR:\n if (n.getJSType() != null) { \n ensureTyped(t, n);\n } else {\n if ((n.getType() == Token.OBJECTLIT)\n && (parent.getJSType() instanceof EnumType)) {\n ensureTyped(t, n, parent.getJSType());\n } else {\n ensureTyped(t, n);\n }\n }\n if (n.getType() == Token.OBJECTLIT) {\n for (Node key : n.children()) {\n visitObjLitKey(t, key, n);\n }\n }\n break;\n default:\n report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType()));\n ensureTyped(t, n);\n break;\n }\n typeable = typeable && !inExterns;\n if (typeable) {\n doPercentTypedAccounting(t, n);\n }\n checkNoTypeCheckSection(n, false);\n }\n"}, "reference": " public void visit(NodeTraversal t, Node n, Node parent) {\n JSType childType;\n JSType leftType, rightType;\n Node left, right;\n boolean typeable = true;\n switch (n.getType()) {\n case Token.NAME:\n typeable = visitName(t, n, parent);\n break;\n case Token.LP:\n if (parent.getType() != Token.FUNCTION) {\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n } else {\n typeable = false;\n }\n break;\n case Token.COMMA:\n ensureTyped(t, n, getJSType(n.getLastChild()));\n break;\n case Token.TRUE:\n case Token.FALSE:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.THIS:\n ensureTyped(t, n, t.getScope().getTypeOfThis());\n break;\n case Token.REF_SPECIAL:\n ensureTyped(t, n);\n break;\n case Token.GET_REF:\n ensureTyped(t, n, getJSType(n.getFirstChild()));\n break;\n case Token.NULL:\n ensureTyped(t, n, NULL_TYPE);\n break;\n case Token.NUMBER:\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.STRING:\n if (!NodeUtil.isObjectLitKey(n, n.getParent())) {\n ensureTyped(t, n, STRING_TYPE);\n } else {\n typeable = false;\n }\n break;\n case Token.GET:\n case Token.SET:\n break;\n case Token.ARRAYLIT:\n ensureTyped(t, n, ARRAY_TYPE);\n break;\n case Token.REGEXP:\n ensureTyped(t, n, REGEXP_TYPE);\n break;\n case Token.GETPROP:\n visitGetProp(t, n, parent);\n typeable = !(parent.getType() == Token.ASSIGN &&\n parent.getFirstChild() == n);\n break;\n case Token.GETELEM:\n visitGetElem(t, n);\n typeable = false;\n break;\n case Token.VAR:\n visitVar(t, n);\n typeable = false;\n break;\n case Token.NEW:\n visitNew(t, n);\n typeable = true;\n break;\n case Token.CALL:\n visitCall(t, n);\n typeable = !NodeUtil.isExpressionNode(parent);\n break;\n case Token.RETURN:\n visitReturn(t, n);\n typeable = false;\n break;\n case Token.DEC:\n case Token.INC:\n left = n.getFirstChild();\n validator.expectNumber(\n t, left, getJSType(left), \"increment/decrement\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.NOT:\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.VOID:\n ensureTyped(t, n, VOID_TYPE);\n break;\n case Token.TYPEOF:\n ensureTyped(t, n, STRING_TYPE);\n break;\n case Token.BITNOT:\n childType = getJSType(n.getFirstChild());\n if (!childType.matchesInt32Context()) {\n report(t, n, BIT_OPERATION, NodeUtil.opToStr(n.getType()),\n childType.toString());\n }\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.POS:\n case Token.NEG:\n left = n.getFirstChild();\n validator.expectNumber(t, left, getJSType(left), \"sign operator\");\n ensureTyped(t, n, NUMBER_TYPE);\n break;\n case Token.EQ:\n case Token.NE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n TernaryValue result =\n leftTypeRestricted.testForEquality(rightTypeRestricted);\n if (result != TernaryValue.UNKNOWN) {\n if (n.getType() == Token.NE) {\n result = result.not();\n }\n report(t, n, DETERMINISTIC_TEST, leftType.toString(),\n rightType.toString(), result.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.SHEQ:\n case Token.SHNE: {\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n JSType leftTypeRestricted = leftType.restrictByNotNullOrUndefined();\n JSType rightTypeRestricted = rightType.restrictByNotNullOrUndefined();\n if (!leftTypeRestricted.canTestForShallowEqualityWith(\n rightTypeRestricted)) {\n report(t, n, DETERMINISTIC_TEST_NO_RESULT, leftType.toString(),\n rightType.toString());\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n }\n case Token.LT:\n case Token.LE:\n case Token.GT:\n case Token.GE:\n leftType = getJSType(n.getFirstChild());\n rightType = getJSType(n.getLastChild());\n if (rightType.isNumber()) {\n validator.expectNumber(\n t, n, leftType, \"left side of numeric comparison\");\n } else if (leftType.isNumber()) {\n validator.expectNumber(\n t, n, rightType, \"right side of numeric comparison\");\n } else if (leftType.matchesNumberContext() &&\n rightType.matchesNumberContext()) {\n } else {\n String message = \"left side of comparison\";\n validator.expectString(t, n, leftType, message);\n validator.expectNotNullOrUndefined(\n t, n, leftType, message, getNativeType(STRING_TYPE));\n message = \"right side of comparison\";\n validator.expectString(t, n, rightType, message);\n validator.expectNotNullOrUndefined(\n t, n, rightType, message, getNativeType(STRING_TYPE));\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.IN:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right);\n validator.expectObject(t, n, rightType, \"'in' requires an object\");\n validator.expectString(t, left, leftType, \"left side of 'in'\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.INSTANCEOF:\n left = n.getFirstChild();\n right = n.getLastChild();\n leftType = getJSType(left);\n rightType = getJSType(right).restrictByNotNullOrUndefined();\n validator.expectAnyObject(\n t, left, leftType, \"deterministic instanceof yields false\");\n validator.expectActualObject(\n t, right, rightType, \"instanceof requires an object\");\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.ASSIGN:\n visitAssign(t, n);\n typeable = false;\n break;\n case Token.ASSIGN_LSH:\n case Token.ASSIGN_RSH:\n case Token.ASSIGN_URSH:\n case Token.ASSIGN_DIV:\n case Token.ASSIGN_MOD:\n case Token.ASSIGN_BITOR:\n case Token.ASSIGN_BITXOR:\n case Token.ASSIGN_BITAND:\n case Token.ASSIGN_SUB:\n case Token.ASSIGN_ADD:\n case Token.ASSIGN_MUL:\n case Token.LSH:\n case Token.RSH:\n case Token.URSH:\n case Token.DIV:\n case Token.MOD:\n case Token.BITOR:\n case Token.BITXOR:\n case Token.BITAND:\n case Token.SUB:\n case Token.ADD:\n case Token.MUL:\n visitBinaryOperator(n.getType(), t, n);\n break;\n case Token.DELPROP:\n if (!isReference(n.getFirstChild())) {\n report(t, n, BAD_DELETE);\n }\n ensureTyped(t, n, BOOLEAN_TYPE);\n break;\n case Token.CASE:\n JSType switchType = getJSType(parent.getFirstChild());\n JSType caseType = getJSType(n.getFirstChild());\n validator.expectSwitchMatchesCase(t, n, switchType, caseType);\n typeable = false;\n break;\n case Token.WITH: {\n Node child = n.getFirstChild();\n childType = getJSType(child);\n validator.expectObject(\n t, child, childType, \"with requires an object\");\n typeable = false;\n break;\n }\n case Token.FUNCTION:\n visitFunction(t, n);\n break;\n case Token.LABEL:\n case Token.LABEL_NAME:\n case Token.SWITCH:\n case Token.BREAK:\n case Token.CATCH:\n case Token.TRY:\n case Token.SCRIPT:\n case Token.EXPR_RESULT:\n case Token.BLOCK:\n case Token.EMPTY:\n case Token.DEFAULT:\n case Token.CONTINUE:\n case Token.DEBUGGER:\n case Token.THROW:\n typeable = false;\n break;\n case Token.DO:\n case Token.FOR:\n case Token.IF:\n case Token.WHILE:\n typeable = false;\n break;\n case Token.AND:\n case Token.HOOK:\n case Token.OBJECTLIT:\n case Token.OR:\n if (n.getJSType() != null) { \n ensureTyped(t, n);\n } else {\n if ((n.getType() == Token.OBJECTLIT)\n && (parent.getJSType() instanceof EnumType)) {\n ensureTyped(t, n, parent.getJSType());\n } else {\n ensureTyped(t, n);\n }\n }\n if (n.getType() == Token.OBJECTLIT) {\n for (Node key : n.children()) {\n visitObjLitKey(t, key, n);\n }\n }\n break;\n default:\n report(t, n, UNEXPECTED_TOKEN, Token.name(n.getType()));\n ensureTyped(t, n);\n break;\n }\n typeable = typeable && !inExterns;\n if (typeable) {\n doPercentTypedAccounting(t, n);\n }\n checkNoTypeCheckSection(n, false);\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-66"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-66"}} {"sample_uid": "defects4j_function_repair::Closure-23", "benchmark_id": "defects4j_function_repair", "family": "code_generation_ref", "language": "java", "prompt": "Fix the following buggy Java function. Return only the corrected Java code.\n\n private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (isAssignmentTarget(n)) {\n return n;\n }\n if (!right.isNumber()) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node current = left.getFirstChild();\n Node elem = null;\n for (int i = 0; current != null && i < intIndex; i++) {\n elem = current;\n current = current.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.isEmpty()) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n", "context": {"source_dataset": "rufimelo/defects4j", "split": "train", "buggy_function": " private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (isAssignmentTarget(n)) {\n return n;\n }\n if (!right.isNumber()) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node current = left.getFirstChild();\n Node elem = null;\n for (int i = 0; current != null && i < intIndex; i++) {\n elem = current;\n current = current.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.isEmpty()) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n"}, "reference": " private Node tryFoldArrayAccess(Node n, Node left, Node right) {\n Node parent = n.getParent();\n if (isAssignmentTarget(n)) {\n return n;\n }\n if (!right.isNumber()) {\n return n;\n }\n double index = right.getDouble();\n int intIndex = (int) index;\n if (intIndex != index) {\n error(INVALID_GETELEM_INDEX_ERROR, right);\n return n;\n }\n if (intIndex < 0) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n Node current = left.getFirstChild();\n Node elem = null;\n for (int i = 0; current != null; i++) {\n if (i != intIndex) {\n if (mayHaveSideEffects(current)) {\n return n;\n }\n } else {\n elem = current;\n }\n current = current.getNext();\n }\n if (elem == null) {\n error(INDEX_OUT_OF_BOUNDS_ERROR, right);\n return n;\n }\n if (elem.isEmpty()) {\n elem = NodeUtil.newUndefinedNode(elem);\n } else {\n left.removeChild(elem);\n }\n n.getParent().replaceChild(n, elem);\n reportCodeChange();\n return elem;\n }\n", "tests": {}, "repo_meta": {"bug_id": "Closure-23"}, "metric_protocol": {"type": "reference_text", "family": "code_generation_ref"}, "raw_metadata": {"bug_id": "Closure-23"}}