auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Element encode(Object object, Document document, Element value) throws Exception { EObject eobject = (EObject) object; if (EMFUtils.has(eobject, "data")) { Object v = EMFUtils.get(((EObject) object), "data"); if (v != null && v instanceof EList) { EList data = (EList) v; if (!data.isEmpty() && data.get(0) instanceof EncoderDelegate) { EncoderDelegate encoder = (EncoderDelegate) data.get(0); StringWriter output = new StringWriter(); Transformer transformer = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformer(); SerializationHandler outputHandler = ((TransformerImpl)transformer).getOutputHandler(new StreamResult(output)); encoder.encode(outputHandler); <START> value.appendChild(document.createTextNode(cleanUpHeader(output.toString()))); <END> } } } return value; }</code><technical_language>Yep, find another breaking out Transformer SerializationHandler internal JVM packages. this quickly implement encoding</technical_language>

Target:
public Element encode(Object object, Document document, Element value) throws Exception { EObject eobject = (EObject) object; if (EMFUtils.has(eobject, "data")) { Object v = EMFUtils.get(((EObject) object), "data"); if (v != null && v instanceof EList) { EList data = (EList) v; if (!data.isEmpty() && data.get(0) instanceof EncoderDelegate) { EncoderDelegate encoder = (EncoderDelegate) data.get(0); StringWriter output = new StringWriter(); TransformerHandler serializer = ((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler(); serializer.setResult(new StreamResult(output)); encoder.encode(serializer); CDATASection cData = document.createCDATASection(WPS.cleanUpHeader(output.toString())); cData.normalize(); value.appendChild(cData); } } } return value; }
Source:
<code>protected final void setDatabaseUrl(final List<ServerAddress> databaseUrl) { if (!setup) { <START> throw new IllegalStateException("Can only set this variable during valid times"); <END> } this.databaseUrl = databaseUrl; }</code><technical_language>I "valid times" changed "setup time" "setup"</technical_language>

Target:
protected final void setDatabaseUrl(final List<ServerAddress> databaseUrl) { if (!setup) { throw new IllegalStateException("Can only set this variable during setup"); } this.databaseUrl = databaseUrl; }
Source:
<code>@Override public byte[] encode(ClientListenerResponse resp) { assert resp != null; BinaryHeapOutputStream outStream = new BinaryHeapOutputStream(32); BinaryRawWriterEx writer = marsh.writer(outStream); <START> assert resp instanceof ClientResponse || resp instanceof ClientNotification : "Unexpected response type: " + <END> resp.getClass(); if (resp instanceof ClientResponse) ((ClientResponse)resp).encode(ctx, writer); else if (resp instanceof ClientNotification) ((ClientNotification)resp).encode(ctx, writer); return outStream.arrayCopy(); }</code><technical_language>introduce interface avoid of instanceof checks</technical_language>

Target:
@Override public byte[] encode(ClientListenerResponse resp) { assert resp != null; BinaryHeapOutputStream outStream = new BinaryHeapOutputStream(32); BinaryRawWriterEx writer = marsh.writer(outStream); assert resp instanceof ClientOutgoingMessage : "Unexpected response type: " + resp.getClass(); ((ClientOutgoingMessage)resp).encode(ctx, writer); return outStream.arrayCopy(); }
Source:
<code>public PreparedAttachment(Attachment attachment, String attachmentsDir) throws AttachmentException { this.attachment = attachment; this.tempFile = new File(attachmentsDir, "temp" + UUID.randomUUID()); InputStream attachmentInStream = null; OutputStream tempFileOutStream = null; MessageDigest sha1 = null; try { attachmentInStream = attachment.getInputStream(); tempFileOutStream = FileUtils.openOutputStream(this.tempFile); sha1 = MessageDigest.getInstance("SHA-1"); int bufSiz = 1024; byte buf[] = new byte[bufSiz]; int bytesRead; int totalRead = 0; while ((bytesRead = attachmentInStream.read(buf)) != -1) { sha1.update(buf, 0, bytesRead); tempFileOutStream.write(buf, 0, bytesRead); totalRead += bytesRead; } <START> this.length = totalRead; <END> } catch (IOException e) { logger.log(Level.WARNING,"Problem reading input or output stream ",e); throw new AttachmentNotSavedException(e); } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING,"Problem calculating SHA1 for attachment stream ",e); throw new AttachmentNotSavedException(e); } finally { IOUtils.closeQuietly(attachmentInStream); IOUtils.closeQuietly(tempFileOutStream); } this.sha1 = sha1.digest(); }</code><technical_language>set this sha1 is set for object, for consistency</technical_language>

Target:
public PreparedAttachment(Attachment attachment, String attachmentsDir) throws AttachmentException { this.attachment = attachment; this.tempFile = new File(attachmentsDir, "temp" + UUID.randomUUID()); InputStream attachmentInStream = null; OutputStream tempFileOutStream = null; MessageDigest calculateSha1 = null; int totalRead = 0; try { attachmentInStream = attachment.getInputStream(); tempFileOutStream = FileUtils.openOutputStream(this.tempFile); calculateSha1 = MessageDigest.getInstance("SHA-1"); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int bytesRead; while ((bytesRead = attachmentInStream.read(buffer)) != -1) { calculateSha1.update(buffer, 0, bytesRead); tempFileOutStream.write(buffer, 0, bytesRead); totalRead += bytesRead; } } catch (IOException e) { logger.log(Level.WARNING, "Problem reading from input or writing to output stream ", e); throw new AttachmentNotSavedException(e); } catch (NoSuchAlgorithmException e) { logger.log(Level.WARNING, "Problem calculating SHA1 for attachment stream ", e); throw new AttachmentNotSavedException(e); } finally { IOUtils.closeQuietly(attachmentInStream); IOUtils.closeQuietly(tempFileOutStream); } this.length = totalRead; this.sha1 = calculateSha1.digest(); }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTION_WIFI_CODE) { if (resultCode == RESULT_OK) { info("wifi turned on"); } else { <START> info("wifi NOT turned on"); <END> } } }</code><technical_language>log result code other junk in response</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTION_WIFI_CODE) { if (resultCode == RESULT_OK) { info("wifi turned on"); } else { info("wifi NOT turned on, resultCode: " + resultCode); } } else { info("MainActivity: Unhandled requestCode: " + requestCode + " resultCode: " + resultCode); } }
Source:
<code>protected FilterChainResolver createInstance(ServletContext servletContext) throws Exception { PathMatchingFilterChainResolver resolver = new PathMatchingFilterChainResolver(servletContext); FilterChainManager mgr = getConfig().getFilterChainManager(); resolver.setFilterChainManager(mgr); AccountResolverFilterFactory factory = new AccountResolverFilterFactory(); factory.init(servletContext); Filter accountFilter = factory.getInstance(); <START> final List<Filter> priorityFilters = new ArrayList<>(); <END> priorityFilters.add(accountFilter); if (getConfig().isCorsEnabled()) { CORSFilterFactory corsFilterFactory = new CORSFilterFactory(); corsFilterFactory.init(servletContext); priorityFilters.add(corsFilterFactory.getInstance()); } return new PrioritizedFilterChainResolver(resolver, priorityFilters); }</code><technical_language>This is right place add filter chain. added other fillers added in DefaultFilterChainManagerConfigurer AbstractStormpathWebMvcConfiguration (the is for Servlet, is for Spring Spring Boot)</technical_language>

Target:
protected FilterChainResolver createInstance(ServletContext servletContext) throws Exception { PathMatchingFilterChainResolver resolver = new PathMatchingFilterChainResolver(servletContext); FilterChainManager mgr = getConfig().getFilterChainManager(); resolver.setFilterChainManager(mgr); AccountResolverFilterFactory factory = new AccountResolverFilterFactory(); factory.init(servletContext); Filter accountFilter = factory.getInstance(); final List<Filter> priorityFilters = new ArrayList<>(); priorityFilters.add(accountFilter); if (getConfig().isCorsEnabled()) { CorsFilterFactory corsFilterFactory = new CorsFilterFactory(); corsFilterFactory.init(servletContext); priorityFilters.add(corsFilterFactory.getInstance()); } return new PrioritizedFilterChainResolver(resolver, priorityFilters); }
Source:
<code>private static IASTInitializerClause getInitializerClauseForDecltypeAuto(IASTDeclarator declarator) { IASTInitializer initializer = declarator.getInitializer(); if (initializer == null) { ICPPASTNewExpression newExpression = CPPVisitor.findAncestorWithType(declarator, ICPPASTNewExpression.class); if (newExpression != null) { initializer = newExpression.getInitializer(); } } if (initializer instanceof IASTEqualsInitializer) { return ((IASTEqualsInitializer) initializer).getInitializerClause(); } else if (initializer instanceof ICPPASTConstructorInitializer) { ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; IASTInitializerClause[] arguments = constructorInitializer.getArguments(); if (arguments.length == 1) { return arguments[0]; } } <START> if (initializer <END> instanceof IASTInitializerList) { IASTInitializerList initializerList = (IASTInitializerList) initializer; IASTInitializerClause[] clauses = initializerList.getClauses(); if (clauses.length == 1) { return clauses[0]; } } return null; }</code><technical_language>write "else if" here</technical_language>

Target:
private static IASTInitializerClause getInitializerClauseForDecltypeAuto(IASTDeclarator declarator) { IASTInitializer initializer = declarator.getInitializer(); if (initializer == null) { ICPPASTNewExpression newExpression = CPPVisitor.findAncestorWithType(declarator, ICPPASTNewExpression.class); if (newExpression != null) { initializer = newExpression.getInitializer(); } } if (initializer instanceof IASTEqualsInitializer) { return ((IASTEqualsInitializer) initializer).getInitializerClause(); } else if (initializer instanceof ICPPASTConstructorInitializer) { ICPPASTConstructorInitializer constructorInitializer = (ICPPASTConstructorInitializer) initializer; IASTInitializerClause[] arguments = constructorInitializer.getArguments(); if (arguments.length == 1) { return arguments[0]; } } else if (initializer instanceof IASTInitializerList) { IASTInitializerList initializerList = (IASTInitializerList) initializer; IASTInitializerClause[] clauses = initializerList.getClauses(); if (clauses.length == 1) { return clauses[0]; } } return null; }
Source:
<code>public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { <START> set(kind, value); <END> fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }</code><technical_language>cleaner replace this line with: fKind = kind; fSuffix = getSuffix(kind, value, CharArrayUtils.EMPTY); fLiteral = getLiteral(value, fSuffix); is need call resetLazyFields in constructor</technical_language>

Target:
public CPPASTLiteralExpression(int kind, char[] value, char[] numericCompilerSuffixes) { fKind = kind; fSuffix = getSuffix(kind, value, fSuffix); fLiteral = getLiteral(value, fSuffix); fNumericCompilerSuffixes = (numericCompilerSuffixes == null) ? CharArrayUtils.EMPTY : numericCompilerSuffixes; }
Source:
<code>public boolean getRequestParamAsBoolean(String paramName) { String paramValue = getRequestParamValue(paramName); <START> if (paramValue == null || paramValue.equals("off")) { <END> return false; } else if (paramValue.equals("on")) { return true; } else { return Boolean.parseBoolean(getRequestParamValue(paramName)); } }</code><technical_language>equalling true false applicable HTML forms, this generalized here</technical_language>

Target:
public boolean getRequestParamAsBoolean(String paramName) { return Boolean.parseBoolean(getRequestParamValue(paramName)); }
Source:
<code>public RevertResult revert(String commit) throws GitException { RevCommit revCommit; RevertCommand revertCommand = getGit().revert(); try { revertCommand.include(this.repository.resolve(commit)); revCommit = revertCommand.call(); } catch (IOException | GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } <START> Map<String, RevertResult.RevertStatus> conflicts = new HashMap<>(); <END> if (revertCommand.getFailingResult() != null) { Map<String, MergeFailureReason> failingPaths = revertCommand.getFailingResult().getFailingPaths(); if (failingPaths != null && !failingPaths.isEmpty()) { failingPaths .entrySet() .forEach( failure -> conflicts.put( failure.getKey(), getRevertStatusFromMergeFailureReason(failure.getValue()))); } } List<String> unmergedPaths = revertCommand.getUnmergedPaths(); if (unmergedPaths != null && !unmergedPaths.isEmpty()) { unmergedPaths .stream() .filter(unmergedPath -> !conflicts.containsKey(unmergedPath)) .forEach(unmergedPath -> conflicts.put(unmergedPath, RevertResult.RevertStatus.FAILED)); } List<Ref> jGitRevertedCommits = revertCommand.getRevertedRefs(); List<String> revertedCommits = new ArrayList<String>(); if (jGitRevertedCommits != null) { jGitRevertedCommits.forEach(ref -> revertedCommits.add(ref.getObjectId().name())); } String newHead = null; if (revCommit != null) { newHead = revCommit.getId().getName(); } return newDto(RevertResult.class) .withRevertedCommits(revertedCommits) .withConflicts(conflicts) .withNewHead(newHead); }</code><technical_language>Method is complicate understand, pls split methods</technical_language>

Target:
public RevertResult revert(String commit) throws GitException { RevCommit revCommit; RevertCommand revertCommand = getGit().revert(); try { revertCommand.include(this.repository.resolve(commit)); revCommit = revertCommand.call(); } catch (IOException | GitAPIException exception) { throw new GitException(exception.getMessage(), exception); } return newDto(RevertResult.class) .withRevertedCommits(getRevertedCommits(revertCommand)) .withConflicts(getRevertConflicts(revertCommand)) .withNewHead(revCommit != null ? revCommit.getId().getName() : null); }
Source:
<code>public void testValidateLabelsForVlan(){ <START> Nic nic = new Nic(); <END> nic.setName("eth0"); NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, "eth0", "labelOnUnmanaged"); Set<NicLabel> labels = new HashSet<>(Arrays.asList(label, labelWithUnmanagedNetwork)); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100); ValidationResult result = validator.validateLabels(vlanNic, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Set<NicLabel> labelsNotOnUnmanagedNetwork = new HashSet<>(Arrays.asList(labelWithoutUnmanaged)); result = validator.validateLabels(vlanNic, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }</code><technical_language>'createNic(..);</technical_language>

Target:
public void testValidateLabelsForVlan(){ Nic nic = createNic("eth0"); NicLabel label = new NicLabel(null, "eth1", "label1"); NicLabel labelWithUnmanagedNetwork = new NicLabel(null, "eth0", "labelOnUnmanaged"); Collection<NicLabel> labels = Arrays.asList(label, labelWithUnmanagedNetwork); VdsNetworkInterface vlanNic = createVlanNic(nic, "eth0.100", 100, false); List<VdsNetworkInterface> existingInterfaces = Arrays.asList(vlanNic); Set<String> nicsWithUnmanagedNetworks = validator.filterNicsWithUnmanagedNetworks(existingInterfaces, Collections.emptySet()); assertEquals(1, nicsWithUnmanagedNetworks.size()); String vlanNicName = nicsWithUnmanagedNetworks.iterator().next(); ValidationResult result = validator.validateLabels(vlanNicName, labels); assertThat(result, failsWith(EngineMessage.ACTION_TYPE_FAILED_HOST_NETWORK_LABEL_ON_UNMANAGED_NETWORK, ReplacementUtils.createSetVariableString(LABEL, "labelOnUnmanaged"), ReplacementUtils.createSetVariableString(NIC, "eth0"))); NicLabel labelWithoutUnmanaged = new NicLabel(null, "eth_other", "label1"); Collection<NicLabel> labelsNotOnUnmanagedNetwork = Arrays.asList(labelWithoutUnmanaged); result = validator.validateLabels(vlanNicName, labelsNotOnUnmanagedNetwork); assertTrue(result.isValid()); }
Source:
<code>protected void validate() { super.validate(); <START> if (recordReader == null) { <END> throw new SamzaException("Record reader is required."); } }</code><technical_language>Preconditions.* for consistency null-checks a caller expects a SamzaException treated differently</technical_language>

Target:
protected void validate() { super.validate(); Preconditions.checkNotNull(readFn, "TableReadFunction is required."); Preconditions.checkArgument(rateLimiter == null || tagCreditsMap.isEmpty(), "Only one of rateLimiter instance or read/write limits can be specified"); }
Source:
<code>private static void closeContext(BoundedContext boundedContext) { checkNotNull(boundedContext); try { boundedContext.close(); } catch (Exception e) { <START> throw Exceptions.illegalStateWithCauseOf(e); <END> } }</code><technical_language>Please add a static import for this method</technical_language>

Target:
private static void closeContext(BoundedContext boundedContext) { checkNotNull(boundedContext); try { boundedContext.close(); } catch (Exception e) { throw illegalStateWithCauseOf(e); } }
Source:
<code>static InetSocketAddress getBindAddress(final ModelNode operation, final OperationContext context) throws OperationFailedException { return new InetSocketAddress(Inet.parseInetAddress( OutboundBindAddressResourceDefinition.BIND_ADDRESS.resolveModelAttribute(context, operation).asString()), <START> OutboundBindAddressResourceDefinition.BIND_PORT.resolveModelAttribute(context, operation).asInt() <END> ); }</code><technical_language>This attribute is required, needs a default</technical_language>

Target:
static InetSocketAddress getBindAddress(final ModelNode operation, final OperationContext context) throws OperationFailedException { return new InetSocketAddress(Inet.parseInetAddress( OutboundBindAddressResourceDefinition.BIND_ADDRESS.resolveModelAttribute(context, operation).asString()), OutboundBindAddressResourceDefinition.BIND_PORT.resolveModelAttribute(context, operation).asInt(0) ); }
Source:
<code>public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { if(server.isStarted()) <START> ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(failedOver); <END> synchronized (connectionGuard) { keepConnecting = true; } try { if (producer != null) { producer.close(); } cleanUpSessionFactory(csf); } catch (Throwable dontCare) { } try { session.cleanUp(false); } catch (Throwable dontCare) { } if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID.toString())) { synchronized (this) { try { logger.debug("Moving " + queue.getMessageCount() + " messages from " + queue.getName() + " to " + scaleDownTargetNodeID); ((QueueImpl) queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); fail(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } else if (scaleDownTargetNodeID != null) { logger.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect."); fail(true); } else { logger.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID); fail(me.getType() == ActiveMQExceptionType.DISCONNECTED); } tryScheduleRetryReconnect(me.getType()); }</code><technical_language>out of alignment me.. this fail checkstyle apparently</technical_language>

Target:
public void connectionFailed(final ActiveMQException me, boolean failedOver, String scaleDownTargetNodeID) { if (server.isStarted()) { ActiveMQServerLogger.LOGGER.bridgeConnectionFailed(failedOver); } synchronized (connectionGuard) { keepConnecting = true; } try { if (producer != null) { producer.close(); } cleanUpSessionFactory(csf); } catch (Throwable dontCare) { } try { session.cleanUp(false); } catch (Throwable dontCare) { } if (scaleDownTargetNodeID != null && !scaleDownTargetNodeID.equals(nodeUUID.toString())) { synchronized (this) { try { logger.debug("Moving " + queue.getMessageCount() + " messages from " + queue.getName() + " to " + scaleDownTargetNodeID); ((QueueImpl) queue).moveReferencesBetweenSnFQueues(SimpleString.toSimpleString(scaleDownTargetNodeID)); fail(true); } catch (Exception e) { ActiveMQServerLogger.LOGGER.warn(e.getMessage(), e); } } } else if (scaleDownTargetNodeID != null) { logger.debug("Received scaleDownTargetNodeID: " + scaleDownTargetNodeID + "; cancelling reconnect."); fail(true); } else { logger.debug("Received invalid scaleDownTargetNodeID: " + scaleDownTargetNodeID); fail(me.getType() == ActiveMQExceptionType.DISCONNECTED); } tryScheduleRetryReconnect(me.getType()); }
Source:
<code>public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); <START> Assert.assertThat(passiveMessageHandler.getTrackedClients().count(), is(1L)); END> Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }</code><technical_language>this assertion is pretty popular, I guess refactor in method. assertThat(passiveMessageHandler.getTrackerClients().count()).is(x)</technical_language>

Target:
public void trackedMessagesReplicatedToPassive() throws Exception { clusterControl.terminateOnePassive(); storeProxy.getAndAppend(42L, createPayload(42L)); clusterControl.startOneServer(); clusterControl.waitForRunningPassivesInStandby(); passiveEntity = observableClusterTierServerEntityService.getServedPassiveEntities().get(1); passiveMessageHandler = passiveEntity.getMessageHandler(); assertThat(passiveMessageHandler.getTrackedClients().count()).isEqualTo(1L); Map<Long, EhcacheEntityResponse> responses = passiveMessageHandler.getTrackedResponsesForSegment(KEY_ENDS_UP_IN_SEGMENT_11, passiveMessageHandler.getTrackedClients().findFirst().get()); assertThat(responses).hasSize(1); }
Source:
<code><START> protected File writeMergedFile(MergeResult<RawText> result) <END> throws FileNotFoundException, IOException { MergeFormatter fmt = new MergeFormatter(); File of = null; FileOutputStream fos; if (!inCore) { File workTree = db.getWorkTree(); if (workTree == null) throw new UnsupportedOperationException(); of = new File(workTree, tw.getPathString()); File parentFolder = of.getParentFile(); if (!parentFolder.exists()) parentFolder.mkdirs(); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } else if (!result.containsConflicts()) { of = File.createTempFile("merge_", "_temp", null); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } return of; }</code><technical_language>need change this method signature. I leave this method private</technical_language>

Target:
private File writeMergedFile(MergeResult<RawText> result) throws FileNotFoundException, IOException { MergeFormatter fmt = new MergeFormatter(); File of = null; FileOutputStream fos; if (!inCore) { File workTree = db.getWorkTree(); if (workTree == null) throw new UnsupportedOperationException(); of = new File(workTree, tw.getPathString()); File parentFolder = of.getParentFile(); if (!parentFolder.exists()) parentFolder.mkdirs(); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } else if (!result.containsConflicts()) { of = File.createTempFile("merge_", "_temp", null); fos = new FileOutputStream(of); try { fmt.formatMerge(fos, result, Arrays.asList(commitNames), Constants.CHARACTER_ENCODING); } finally { fos.close(); } } return of; }
Source:
<code>private DataAccessRequest updateDarWithDocumentContents( DarDocumentType type, User user, DataAccessRequest dar, InputStream uploadInputStream, FormDataContentDisposition fileDetail) throws IOException { String fileName = fileDetail.getFileName(); String toStoreFileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(fileName); BlobId blobId = gcsService.storeDocument(uploadInputStream, fileDetail.getType(), toStoreFileName); switch (type) { case IRB: if (Objects.nonNull(dar.getData().getIrbDocumentLocation())) { deleteDarDocument(dar, dar.getData().getIrbDocumentLocation()); } dar.getData().setIrbDocumentLocation(blobId.getName()); dar.getData().setIrbDocumentName(fileName); break; case COLLABORATION: if (Objects.nonNull(dar.getData().getCollaborationLetterLocation())) { deleteDarDocument(dar, dar.getData().getCollaborationLetterLocation()); } dar.getData().setCollaborationLetterLocation(blobId.getName()); dar.getData().setCollaborationLetterName(fileName); break; default: break; } <START> dataAccessRequestService.updateByReferenceIdVersion2(user, dar); <END> return dataAccessRequestService.findByReferenceId(dar.getReferenceId()); }</code><technical_language>This function calls findByReferenceId return need call dataAccessRequestService.findByReferenceId()</technical_language>

Target:
private DataAccessRequest updateDarWithDocumentContents( DarDocumentType type, User user, DataAccessRequest dar, InputStream uploadInputStream, FormDataContentDisposition fileDetail) throws IOException { validateFileDetails(fileDetail); String fileName = fileDetail.getFileName(); String blobFileName = UUID.randomUUID().toString(); BlobId blobId = gcsService.storeDocument(uploadInputStream, fileDetail.getType(), blobFileName); switch (type) { case IRB: if (Objects.nonNull(dar.getData().getIrbDocumentLocation())) { deleteDarDocument(dar, dar.getData().getIrbDocumentLocation()); } dar.getData().setIrbDocumentLocation(blobId.getName()); dar.getData().setIrbDocumentName(fileName); break; case COLLABORATION: if (Objects.nonNull(dar.getData().getCollaborationLetterLocation())) { deleteDarDocument(dar, dar.getData().getCollaborationLetterLocation()); } dar.getData().setCollaborationLetterLocation(blobId.getName()); dar.getData().setCollaborationLetterName(fileName); break; default: break; } return dataAccessRequestService.updateByReferenceIdVersion2(user, dar); }
Source:
<code><START> protected String getMinGDBVersionSupported() { return GdbDebugServicesFactory.GDB_7_7_VERSION; } <END></code><technical_language>update this GDB_7_12_VERSION</technical_language>

Target:
protected String getMinGDBVersionSupported() { return GdbDebugServicesFactory.GDB_7_12_VERSION; }
Source:
<code>private DatabaseType getDatabaseType() { if (databaseType == null) { Connection conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDatabaseProductName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC metadata.", e); } finally { <START> if (conn != null) { <END> connectionFactory.releaseConnection(conn); } } if (databaseType == null) { log.debug("Unable to detect database type using connection metadata. Attempting to guess on driver name."); conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDriverName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC driver name.", e); } finally { if (conn != null) { connectionFactory.releaseConnection(conn); } } } if (databaseType == null) { throw new ConfigurationException("Unable to detect database type from JDBC driver name or connection metadata. Please provide this manually using the 'databaseType' property in your configuration. Supported database type strings are " + Arrays.toString(DatabaseType.values())); } else { log.debugf("Guessing database type as '%s'. If this is incorrect, please specify the correct type using the 'databaseType' property in your configuration. Supported database type strings are %s", databaseType, Arrays.toString(DatabaseType.values())); } } return databaseType; }</code><technical_language>need check for null, releaseConnection</technical_language>

Target:
private DatabaseType getDatabaseType() { if (databaseType == null) { Connection conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDatabaseProductName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC metadata.", e); } finally { connectionFactory.releaseConnection(conn); } if (databaseType == null) { log.debug("Unable to detect database type using connection metadata. Attempting to guess on driver name."); conn = null; try { conn = connectionFactory.getConnection(); String dbProduct = conn.getMetaData().getDriverName(); databaseType = guessDatabaseType(dbProduct); } catch (Exception e) { log.debug("Unable to guess database type from JDBC driver name.", e); } finally { connectionFactory.releaseConnection(conn); } } if (databaseType == null) { throw new ConfigurationException("Unable to detect database type from JDBC driver name or connection metadata. Please provide this manually using the 'databaseType' property in your configuration. Supported database type strings are " + Arrays.toString(DatabaseType.values())); } else { log.debugf("Guessing database type as '%s'. If this is incorrect, please specify the correct type using the 'databaseType' property in your configuration. Supported database type strings are %s", databaseType, Arrays.toString(DatabaseType.values())); } } return databaseType; }
Source:
<code>public void collectionWithDifferentJobNamesProducesUnqiueEntries() { List<BuildResult> results = new ArrayList<BuildResult>(); results.add(new BuildResult(0, "", BuildStatus.STARTED, 1, "SameJob")); results.add(new BuildResult(1, "", BuildStatus.STARTED, 1, "DifferentJob")); TaskBuildStatusMapper mapper = new TaskBuildStatusMapper(results); TaskAttribute root = createRootAttribute(); mapper.applyTo(root); assertEquals(2, root.getAttributes().size()); <START> assertNotNull(root.getAttribute("BUILD_RESULT-0")); <END> assertNotNull(root.getAttribute("BUILD_RESULT-1")); }</code><technical_language>mean. concerned lots of small, fine-grained tests, a smaller number of tests test a more complete scenario, should, somewhere, testing child attributes mapper creates in fact created correctly. includes testing attributes multiple jobs name; I imagine a bug some attributes correct job</technical_language>

Target:
public void collectionWithDifferentJobNamesProducesUnqiueEntries() { List<BuildResult> results = new ArrayList<BuildResult>(); results.add(new BuildResult(0, "", BuildStatus.STARTED, 1, "SameJob")); results.add(new BuildResult(1, "", BuildStatus.STARTED, 1, "DifferentJob")); TaskBuildStatusMapper mapper = new TaskBuildStatusMapper(results); TaskAttribute root = createRootAttribute(); mapper.applyTo(root); assertEquals(2, root.getAttributes().size()); TaskAttribute firstBuildResultAttribute = root.getAttribute("BUILD_RESULT-0"); assertNotNull(firstBuildResultAttribute); assertEquals(0, firstBuildResultAttribute.getAttribute("NUMBER")); TaskAttribute secondBuildResultAttribute = root.getAttribute("BUILD_RESULT-1"); assertNotNull(secondBuildResultAttribute); assertEquals(1, secondBuildResultAttribute.getAttribute("NUMBER")); }
Source:
<code>private void waitForFinishedNotification() { waitForTransportState("PLAYING"); String notificationTitle = stateMap.get("CurrentTitle"); long playstart = System.currentTimeMillis(); <START> while (System.currentTimeMillis() - playstart < (this.notificationTimeout.longValue() * 1000)) { <END> try { Thread.sleep(50); if (!notificationTitle.equals(stateMap.get("CurrentTitle")) || !"PLAYING".equals(stateMap.get("TransportState"))) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } }</code><technical_language>adding unneeded braces</technical_language>

Target:
private void waitForFinishedNotification() { waitForTransportState("PLAYING"); String notificationTitle = stateMap.get("CurrentTitle"); long playstart = System.currentTimeMillis(); while (System.currentTimeMillis() - playstart < this.notificationTimeout.longValue() * 1000) { try { Thread.sleep(50); if (!notificationTitle.equals(stateMap.get("CurrentTitle")) || !"PLAYING".equals(stateMap.get("TransportState"))) { break; } } catch (InterruptedException e) { logger.error("InterruptedException during playing a notification sound"); } } }
Source:
<code>public void propertyChange(PropertyChangeEvent event) { for (final SelectLocationPage page : getNotVisitedLocationPages()) { final GenerationInfo generationInfo = page.getGenerationInfo(); generationInfo.removePropertyChangeListener(this); if <START> ("location".equals(event.getPropertyName())) { <END> final URI newLocation = getNewLocationProposal((URI) event.getNewValue(), generationInfo.getNameProposal()); generationInfo.setLocation(newLocation); } if ("wrap".equals(event.getPropertyName())) { generationInfo.setWrap((Boolean) event.getNewValue()); } generationInfo.addPropertyChangeListener(this); page.getBindingContext().updateTargets(); } }</code><technical_language>personal preference, switch operands of readability reasons (i.e. event.getPropertyName().equals("location"))</technical_language>

Target:
public void propertyChange(PropertyChangeEvent event) { for (final SelectLocationPage page : getNotVisitedLocationPages()) { final GenerationInfo generationInfo = page.getGenerationInfo(); generationInfo.removePropertyChangeListener(this); if ("location".equals(event.getPropertyName())) { final URI newLocation = getNewLocationProposal(URI.class.cast(event.getNewValue()), generationInfo.getNameProposal()); generationInfo.setLocation(newLocation); } if ("wrap".equals(event.getPropertyName())) { generationInfo.setWrap(Boolean.class.cast(event.getNewValue())); } generationInfo.addPropertyChangeListener(this); page.getBindingContext().updateTargets(); } }
Source:
<code>protected String selectSQL(SimpleFeatureType featureType, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, query.getHints()); Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); filter(featureType, filter, sql); } else { <START> removeWhereClausePlaceHolder(sql); <END> } sort(featureType, query.getSortBy(), null, sql); applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); applySearchHints(featureType, query, sql); return sql.toString(); }</code><technical_language>chance ":where_clause:" ends a valid token in request? ensure removed in sqlview definition merging in query instead of building a query bits coming user. happen, filter encoding is DBMS, custom functions encoding, this a base class for databases... while ":where_clause:" is pretty specific, changes of conflicts zero. Also, if remove in sql_view expansion, is need sprinkle calls "removeWherePlaceholder". Idea, get filter, pass encodeTableName (or pass full query encodeTableName) handle removal instead. Mind joins, there... actually, happen in VirtualTable.expandParameters for effect. Or, avoid changing existing API, option add removal of placeholder a hint</technical_language>

Target:
protected String selectSQL(SimpleFeatureType featureType, Query query) throws IOException, SQLException { StringBuffer sql = new StringBuffer(); sql.append("SELECT "); selectColumns(featureType, null, query, sql); sql.setLength(sql.length() - 1); dialect.encodePostSelect(featureType, sql); sql.append(" FROM "); encodeTableName(featureType.getTypeName(), sql, setKeepWhereClausePlaceHolderHint(query)); Filter filter = query.getFilter(); if (filter != null && !Filter.INCLUDE.equals(filter)) { sql.append(" WHERE "); filter(featureType, filter, sql); } sort(featureType, query.getSortBy(), null, sql); applyLimitOffset(sql, query.getStartIndex(), query.getMaxFeatures()); applySearchHints(featureType, query, sql); return sql.toString(); }
Source:
<code>public void updateWorkflowInstanceAfterExecution(WorkflowInstance instance, WorkflowInstanceAction action, List<WorkflowInstance> childWorkflows) { Assert.isTrue(action != null, "action can not be null"); <START> Assert.isTrue(action != null, "childWorkflows can not be null"); <END> if (sqlVariants.hasUpdateableCTE() && childWorkflows.isEmpty()) { updateWorkflowInstanceWithCTE(instance, action); } else { updateWorkflowInstanceWithTransaction(instance, action, childWorkflows); } }</code><technical_language>copy paste bug: childWorkflows != null</technical_language>

Target:
public void updateWorkflowInstanceAfterExecution(WorkflowInstance instance, WorkflowInstanceAction action, List<WorkflowInstance> childWorkflows) { Assert.isTrue(action != null, "action can not be null"); Assert.isTrue(childWorkflows != null, "childWorkflows can not be null"); if (sqlVariants.hasUpdateableCTE() && childWorkflows.isEmpty()) { updateWorkflowInstanceWithCTE(instance, action); } else { updateWorkflowInstanceWithTransaction(instance, action, childWorkflows); } }
Source:
<code>public String toPath(Class<?> classOfPackagingContainingFile, String filename) { String path = classOfPackagingContainingFile.getResource(filename).getPath(); <START> if (path.endsWith(".java.template")) { <END> String javaPath = path.substring(0, path.length() - 9); File target = new File(javaPath); if (!target.exists()) { try { Files.copy(new File(path).toPath(), target.toPath()); } catch (IOException e) { throw new IllegalStateException("unable to copy file", e); } } return javaPath; } return path; }</code><technical_language>Hmm, is this? is a java template</technical_language>

Target:
public String toPath(Class<?> classOfPackagingContainingFile, String filename) { return classOfPackagingContainingFile.getResource(filename).getPath(); }
Source:
<code>public void initRepo() throws Exception { <START> session.removeChildren(session.getRootDocument().getRef()); <END> session.save(); folder = session.createDocumentModel("/", "Folder", "Folder"); folder.setPropertyValue("dc:title", "Folder"); folder = session.createDocument(folder); session.save(); folder = session.getDocument(folder.getRef()); docNoFacet = session.createDocumentModel("/Folder", "DocNoFacet", "File"); docNoFacet.setPropertyValue("dc:title", "DocNotFacet"); docNoFacet = session.createDocument(docNoFacet); session.save(); docNoFacet = session.getDocument(docNoFacet.getRef()); docWithFacet = session.createDocumentModel("/Folder", "DocWithFacet", "File"); docWithFacet.setPropertyValue("dc:title", "DocWithFacet"); docWithFacet = session.createDocument(docWithFacet); session.save(); docWithFacet = session.getDocument(docWithFacet.getRef()); docWithFacet.addFacet(THE_FACET); docWithFacet = session.saveDocument(docWithFacet); session.save(); }</code><technical_language>Do need clear repository ? tear in clearRepo</technical_language>

Target:
public void initRepo() throws Exception { folder = session.createDocumentModel("/", "Folder", "Folder"); folder.setPropertyValue("dc:title", "Folder"); folder = session.createDocument(folder); session.save(); docNoFacet = session.createDocumentModel("/Folder", "DocNoFacet", "File"); docNoFacet.setPropertyValue("dc:title", "DocNotFacet"); docNoFacet = session.createDocument(docNoFacet); session.save(); docNoFacet = session.getDocument(docNoFacet.getRef()); docWithFacet = session.createDocumentModel("/Folder", "DocWithFacet", "File"); docWithFacet.setPropertyValue("dc:title", "DocWithFacet"); docWithFacet = session.createDocument(docWithFacet); session.save(); docWithFacet = session.getDocument(docWithFacet.getRef()); docWithFacet.addFacet(THE_FACET); docWithFacet = session.saveDocument(docWithFacet); session.save(); }
Source:
<code><START> public List<Map> getStageReachedCounts(Context context) throws SQLException { <END> return workspaceItemDAO.getStageReachedCounts(context); }</code><technical_language>great if this map generics contains</technical_language>

Target:
public List<Map.Entry<Integer, Long>> getStageReachedCounts(Context context) throws SQLException { return workspaceItemDAO.getStageReachedCounts(context); }
Source:
<code>public String getHref() { <START> return "/entitlements/" + getId(); <END> }</code><technical_language>Need update this safe URI generation</technical_language>

Target:
public String getHref() { return this.getId() != null ? String.format("/entitlements/%s", this.getId()) : null; }
Source:
<code>private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); if (memberList.isEmpty()) { break; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } Connection ownerConnection = this.ownerConnection; if (ownerConnection == null) { <START> continue; <END> } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null, ownerConnection).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }</code><technical_language>this busy-loop</technical_language>

Target:
private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); Connection ownerConnection = this.ownerConnection; if (memberList.isEmpty() || ownerConnection == null) { sleepBeforeNextTry(); continue; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null, ownerConnection).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }
Source:
<code>private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException { String srcExt = FileUtils.getFileExtension(srcFile.getName()); String dstExt = FileUtils.getFileExtension(dstFile.getName()); if (!StringUtils.equalsIgnoreCase(srcExt, dstExt)) { throw new IOException("Source and destination files have different extensions."); } switch (srcExt != null ? srcExt.toLowerCase() : "") { <START> case "json": <END> ObjectMapper m = new ObjectMapper(); ObjectNode destNode = m.readValue(dstFile, ObjectNode.class); ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class); destNode.setAll(srcNode); m.writeValue(dstFile, destNode); break; default: FileUtils.append(srcFile, dstFile, appendNewLine); } }</code><technical_language>Do expect this switch grow new cases? a simple if ("json".equalsIgnoreCase(srcExt)) is simpler</technical_language>

Target:
private void append(File srcFile, File dstFile, boolean appendNewLine) throws IOException { String srcExt = FileUtils.getFileExtension(srcFile.getName()); String dstExt = FileUtils.getFileExtension(dstFile.getName()); if (StringUtils.equalsIgnoreCase(srcExt, dstExt) && "json".equalsIgnoreCase(srcExt)) { ObjectMapper m = new ObjectMapper(); ObjectNode destNode = m.readValue(dstFile, ObjectNode.class); ObjectNode srcNode = m.readValue(srcFile, ObjectNode.class); destNode.setAll(srcNode); m.writeValue(dstFile, destNode); } else { FileUtils.append(srcFile, dstFile, appendNewLine); } }
Source:
<code>public boolean verifyTopicCleanupPolicyOnlyCompact(String topic, String workerTopicConfig, String topicPurpose) { Set<String> cleanupPolicies = topicCleanupPolicy(topic); if (cleanupPolicies == null || cleanupPolicies.isEmpty()) { log.debug("Unable to use admin client to verify the cleanup policy of '{}' " + "topic is '{}', either because the broker is an older " + "version or because the Kafka principal used for Connect " + "internal topics does not have the required permission to " + "describe topic configurations.", topic, TopicConfig.CLEANUP_POLICY_COMPACT); return false; } String cleanupPolicyStr = String.join(",", cleanupPolicies); log.debug("Found cleanup policy for '{}' topic is '{}'", topic, cleanupPolicyStr); Set<String> expectedPolicies = Collections.singleton(TopicConfig.CLEANUP_POLICY_COMPACT); String expectedPolicyStr = String.join(",", expectedPolicies); if (cleanupPolicies != null && !cleanupPolicies.equals(expectedPolicies)) { String msg = String.format("Topic '%s' supplied via the '%s' property is required " <START> + "to have '%s=%s' to guarantee consistency and durability of " + "%s, but found '%s'. " + "Correct the topic before restarting Connect.", <END> topic, workerTopicConfig, TopicConfig.CLEANUP_POLICY_CONFIG, expectedPolicyStr, topicPurpose, cleanupPolicyStr); throw new ConfigException(msg); } return true; }</code><technical_language>nit: 2 tabs alignment for everything</technical_language>

Target:
public boolean verifyTopicCleanupPolicyOnlyCompact(String topic, String workerTopicConfig, String topicPurpose) { Set<String> cleanupPolicies = topicCleanupPolicy(topic); if (cleanupPolicies.isEmpty()) { log.info("Unable to use admin client to verify the cleanup policy of '{}' " + "topic is '{}', either because the broker is an older " + "version or because the Kafka principal used for Connect " + "internal topics does not have the required permission to " + "describe topic configurations.", topic, TopicConfig.CLEANUP_POLICY_COMPACT); return false; } Set<String> expectedPolicies = Collections.singleton(TopicConfig.CLEANUP_POLICY_COMPACT); if (!cleanupPolicies.equals(expectedPolicies)) { String expectedPolicyStr = String.join(",", expectedPolicies); String cleanupPolicyStr = String.join(",", cleanupPolicies); String msg = String.format("Topic '%s' supplied via the '%s' property is required " + "to have '%s=%s' to guarantee consistency and durability of " + "%s, but found the topic currently has '%s=%s'. Continuing would likely " + "result in eventually losing %s and problems restarting this Connect " + "cluster in the future. Change the '%s' property in the " + "Connect worker configurations to use a topic with '%s=%s'.", topic, workerTopicConfig, TopicConfig.CLEANUP_POLICY_CONFIG, expectedPolicyStr, topicPurpose, TopicConfig.CLEANUP_POLICY_CONFIG, cleanupPolicyStr, topicPurpose, workerTopicConfig, TopicConfig.CLEANUP_POLICY_CONFIG, expectedPolicyStr); throw new ConfigException(msg); } return true; }