auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { <START> final ServletContext forwardContext = getServletContext().getContext(targetContext); <END> final RequestDispatcher dispatcher = forwardContext.getRequestDispatcher(pageNotFoundURI); dispatcher.forward(request, response); }</code><technical_language>forwardContext null, check it</technical_language>

Target:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext forwardContext = getServletContext().getContext(targetContext); if (forwardContext != null) { final RequestDispatcher dispatcher = forwardContext.getRequestDispatcher(pageNotFoundURI); if (dispatcher != null) { dispatcher.forward(request, response); } else { log.error("Unable to determine dispatcher"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to determine dispatcher"); } } else { log.error("Unable to determine forwarding context"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "unable to determine forward context"); } }
Source:
<code>public synchronized void get(App.Callback<BaseChangeEvent<T>> callback) throws IllegalStateException { Util.checkNull(callback, "callback"); if (thread != null) { throw new IllegalStateException("Resource already open"); } else { thread = new Thread(new Runnable() { @Override public void run() { try { eventStream = executor.run(); while (true) { BaseChangeEvent<T> nextEvent = eventStream.getNextEvent(); callback.onResult(App.Result.withResult(nextEvent)); } } catch (IOException exception) { callback.onResult(App.Result.withError(new AppException(ErrorCode.NETWORK_IO_EXCEPTION, exception))); } <START> } <END> }, String.format("RealmStreamTask|%s", name)); thread.start(); } }</code><technical_language>guard this catching IOExceptions emit some other error prevents accidential crashes</technical_language>

Target:
public synchronized void get(App.Callback<BaseChangeEvent<T>> callback) throws IllegalStateException { Util.checkNull(callback, "callback"); if (thread != null) { throw new IllegalStateException("Resource already open"); } else { thread = new Thread(new Runnable() { @Override public void run() { try { eventStream = executor.run(); while (true) { BaseChangeEvent<T> nextEvent = eventStream.getNextEvent(); callback.onResult(App.Result.withResult(nextEvent)); } } catch (AppException exception) { callback.onResult(App.Result.withError(exception)); } catch (IOException exception) { AppException appException = new AppException(ErrorCode.NETWORK_IO_EXCEPTION, exception); callback.onResult(App.Result.withError(appException)); } } }, String.format("RealmStreamTask|%s", name)); thread.start(); } }
Source:
<code>public static RefundResponse valueOf(RefundEntity refundEntity, UriInfo uriInfo) { Long accountId = refundEntity.getChargeEntity().getGatewayAccount().getId(); String externalChargeId = refundEntity.getChargeEntity().getExternalId(); String externalRefundId = refundEntity.getExternalId(); URI selfLink = uriInfo.getBaseUriBuilder() .path(REFUND_API_PATH) .build(accountId, externalChargeId, externalRefundId); URI paymentLink = uriInfo.getBaseUriBuilder() .path(CHARGE_API_PATH) .build(accountId, externalChargeId); return new RefundResponse(HalRepresentation.builder() .addProperty("refund_id", refundEntity.getExternalId()) .addProperty("amount", refundEntity.getAmount()) .addProperty("status", refundEntity.getStatus().toExternal().getStatus()) .addProperty("created_date", DateTimeUtils.toUTCDateTimeString(refundEntity.getCreatedDate())) <START> .addProperty("refunded_by", refundEntity.getRefundedBy()) <END> .addLink("self", selfLink) .addLink("payment", paymentLink), selfLink); }</code><technical_language>Another place name updated</technical_language>

Target:
public static RefundResponse valueOf(RefundEntity refundEntity, UriInfo uriInfo) { Long accountId = refundEntity.getChargeEntity().getGatewayAccount().getId(); String externalChargeId = refundEntity.getChargeEntity().getExternalId(); String externalRefundId = refundEntity.getExternalId(); URI selfLink = uriInfo.getBaseUriBuilder() .path(REFUND_API_PATH) .build(accountId, externalChargeId, externalRefundId); URI paymentLink = uriInfo.getBaseUriBuilder() .path(CHARGE_API_PATH) .build(accountId, externalChargeId); return new RefundResponse(HalRepresentation.builder() .addProperty("refund_id", refundEntity.getExternalId()) .addProperty("amount", refundEntity.getAmount()) .addProperty("status", refundEntity.getStatus().toExternal().getStatus()) .addProperty("created_date", DateTimeUtils.toUTCDateTimeString(refundEntity.getCreatedDate())) .addProperty("user_external_id", refundEntity.getUserExternalId()) .addLink("self", selfLink) .addLink("payment", paymentLink), selfLink); }
Source:
<code>private Result updateImpl(final RevWalk walk, final Store store) throws IOException { RevObject newObj; RevObject oldObj; if (getRefDatabase().isNameConflicting(getName())) return Result.LOCK_FAILURE; try { if (!tryLock(true)) return Result.LOCK_FAILURE; boolean isTag = ref.getName().startsWith(Constants.R_TAGS); if (expValue != null && !isTag) { final ObjectId o; o = oldValue != null ? oldValue : ObjectId.zeroId(); if (!AnyObjectId.equals(expValue, o)) return Result.LOCK_FAILURE; } if (oldValue == null) return store.execute(Result.NEW); newObj = safeParse(walk, newValue); oldObj = safeParse(walk, oldValue); if (newObj == oldObj && !detachingSymbolicRef) return store.execute(Result.NO_CHANGE); if (newObj instanceof RevCommit && oldObj instanceof RevCommit) { if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) return store.execute(Result.FAST_FORWARD); } <START> if (isForceUpdate() || isTag) <END> return store.execute(Result.FORCED); return Result.REJECTED; } finally { unlock(); } }</code><technical_language>I this is wrong, git reference manual for git-tag [1] says: "Unless -f is given, tag created exist in .git/refs/tags/ directory." [1] <LINK_0></technical_language>

Target:
private Result updateImpl(final RevWalk walk, final Store store) throws IOException { RevObject newObj; RevObject oldObj; if (getRefDatabase().isNameConflicting(getName())) return Result.LOCK_FAILURE; try { if (!tryLock(true)) return Result.LOCK_FAILURE; if (expValue != null) { final ObjectId o; o = oldValue != null ? oldValue : ObjectId.zeroId(); if (!AnyObjectId.equals(expValue, o)) return Result.LOCK_FAILURE; } if (oldValue == null) return store.execute(Result.NEW); newObj = safeParse(walk, newValue); oldObj = safeParse(walk, oldValue); if (newObj == oldObj && !detachingSymbolicRef) return store.execute(Result.NO_CHANGE); if (newObj instanceof RevCommit && oldObj instanceof RevCommit) { if (walk.isMergedInto((RevCommit) oldObj, (RevCommit) newObj)) return store.execute(Result.FAST_FORWARD); } if (isForceUpdate()) return store.execute(Result.FORCED); return Result.REJECTED; } finally { unlock(); } }
Source:
<code>private List<String> getSyncthingPIDs() { List<String> mLibSyncthingPID = new ArrayList<String>(); Process ps = null; DataOutputStream psOut = null; BufferedReader br = null; <START> mLibSyncthingPID.clear(); <END> try { ps = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); psOut = new DataOutputStream(ps.getOutputStream()); psOut.writeBytes("ps\n"); psOut.writeBytes("exit\n"); psOut.flush(); ps.waitFor(); br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.contains(Constants.FILENAME_SYNCTHING_BINARY)) { String syncthingPID = line.trim().split("\\s+")[1]; Log.v(TAG, "getSyncthingPIDs: Found process PID [" + syncthingPID + "]"); mLibSyncthingPID.add(syncthingPID); } } } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed list Syncthing processes", e); } finally { try { if (br != null) { br.close(); } if (psOut != null) { psOut.close(); } } catch (IOException e) { Log.w(TAG_KILL, "Failed close the psOut stream", e); } if (ps != null) { ps.destroy(); } } return mLibSyncthingPID; }</code><technical_language>needed, also, m prefix sense now</technical_language>

Target:
private List<String> getSyncthingPIDs() { List<String> libSyncthingPID = new ArrayList<String>(); Process ps = null; DataOutputStream psOut = null; BufferedReader br = null; try { ps = Runtime.getRuntime().exec((mUseRoot) ? "su" : "sh"); psOut = new DataOutputStream(ps.getOutputStream()); psOut.writeBytes("ps\n"); psOut.writeBytes("exit\n"); psOut.flush(); ps.waitFor(); br = new BufferedReader(new InputStreamReader(ps.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.contains(Constants.FILENAME_SYNCTHING_BINARY)) { String syncthingPID = line.trim().split("\\s+")[1]; Log.v(TAG, "getSyncthingPIDs: Found process PID [" + syncthingPID + "]"); libSyncthingPID.add(syncthingPID); } } } catch (IOException | InterruptedException e) { Log.w(TAG_KILL, "Failed list Syncthing processes", e); } finally { try { if (br != null) { br.close(); } if (psOut != null) { psOut.close(); } } catch (IOException e) { Log.w(TAG_KILL, "Failed close the psOut stream", e); } if (ps != null) { ps.destroy(); } } return libSyncthingPID; }
Source:
<code>public void runJob() { PID depositPID = getDepositPID(); Model model = getWritableModel(); Bag depositBag = model.createBag(depositPID.getURI().toString()); PID primaryPID = new PID("uuid:" + UUID.randomUUID()); Map<String, String> depositStatus = getDepositStatus(); String filename = depositStatus.get(DepositField.fileName.name()); String slug = depositStatus.get(DepositField.depositSlug.name()); String mimetype = depositStatus.get(DepositField.fileMimetype.name()); <START> String contentModel = depositStatus.get(RDF.type.toString()); <END> Resource primaryResource = model.createResource(primaryPID.getURI()); if (contentModel == null || Cdr.FileObject.equals(contentModel)) { populateSimple(model, primaryResource, slug, filename, mimetype); } else { populateContainer(model, primaryResource, primaryPID, slug, contentModel); } depositBag.add(primaryResource); if (!this.getDepositDirectory().exists()) { log.info("Creating deposit dir {}", this.getDepositDirectory().getAbsolutePath()); this.getDepositDirectory().mkdir(); } PremisLogger premisDepositLogger = getPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Normalized deposit package from {0} to {1}", PackagingType.SIMPLE_OBJECT.getUri(), PackagingType.BAG_WITH_N3.getUri()) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }</code><technical_language>pretty this work right out of box. try resolve it, I suggest removing this rid of code related populateContainer, assume creating a FileObject. pretty populateContainer is dead code this create new folders collections presently (it deposit pipeline)</technical_language>

Target:
public void runJob() { PID depositPID = getDepositPID(); Model model = getWritableModel(); Bag depositBag = model.createBag(depositPID.getURI().toString()); PID mainPID = repository.mintContentPid(); Map<String, String> depositStatus = getDepositStatus(); String filename = depositStatus.get(DepositField.fileName.name()); String slug = depositStatus.get(DepositField.depositSlug.name()); String mimetype = depositStatus.get(DepositField.fileMimetype.name()); Resource mainResource = model.createResource(mainPID.getURI()); populateFileObject(model, mainResource, slug, filename, mimetype); depositBag.add(mainResource); if (!this.getDepositDirectory().exists()) { log.info("Creating deposit dir {}", this.getDepositDirectory().getAbsolutePath()); this.getDepositDirectory().mkdir(); } PremisLogger premisDepositLogger = getPremisLogger(depositPID); Resource premisDepositEvent = premisDepositLogger.buildEvent(Premis.Normalization) .addEventDetail("Normalized deposit package from {0} to {1}", PackagingType.SIMPLE_OBJECT.getUri(), PackagingType.BAG_WITH_N3.getUri()) .addSoftwareAgent(SoftwareAgent.depositService.getFullname()) .create(); premisDepositLogger.writeEvent(premisDepositEvent); }
Source:
<code>public MessageStream<M> merge(Collection<? extends MessageStream<? extends M>> otherStreams) { MessageStreamImpl<M> nextStream = new MessageStreamImpl<>(this.graph); <START> List<MessageStream<M>> streamsToMerge = new ArrayList<>(); <END> streamsToMerge.add(this); streamsToMerge.addAll((Collection<MessageStream<M>>) otherStreams); streamsToMerge.forEach(stream -> { OperatorSpec mergeOperatorSpec = OperatorSpecs.createMergeOperatorSpec(nextStream, this.graph.getNextOpId()); ((MessageStreamImpl<M>) stream).registeredOperatorSpecs.add(mergeOperatorSpec); }); return nextStream; }</code><technical_language>leverage ArrayList constructor (e.g. new ArrayList<>(otherStreams)) copy otherStreams collection add "this"</technical_language>

Target:
public MessageStream<M> merge(Collection<? extends MessageStream<? extends M>> otherStreams) { MessageStreamImpl<M> nextStream = new MessageStreamImpl<>(this.graph); List<MessageStream<M>> streamsToMerge = new ArrayList<>((Collection<MessageStream<M>>) otherStreams); streamsToMerge.add(this); streamsToMerge.forEach(stream -> { OperatorSpec mergeOperatorSpec = OperatorSpecs.createMergeOperatorSpec(nextStream, this.graph.getNextOpId()); ((MessageStreamImpl<M>) stream).registeredOperatorSpecs.add(mergeOperatorSpec); }); return nextStream; }
Source:
<code>public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { ITmfStateInterval interval = null; try { <START> interval = getRelevantInterval(t, attributeQuark); <END> } catch (ClosedChannelException e) { e.printStackTrace(); } return interval; }</code><technical_language>return getRelevant..</technical_language>

Target:
public ITmfStateInterval doSingularQuery(long t, int attributeQuark) throws TimeRangeException, StateSystemDisposedException { try { return getRelevantInterval(t, attributeQuark); } catch (ClosedChannelException e) { throw new StateSystemDisposedException(e); } }
Source:
<code>protected void filter(GenericResourceMethod genericResourceMethod, Object[] arguments) throws ApiException { final String methodName = genericResourceMethod.getMethod().getName(); final Subject subject = EnvironmentContext.getCurrent().getSubject(); switch (methodName) { case "getCurrent": case "updatePassword": case "getById": case "find": <START> case "test": <END> case "getSettings": return; case "create": final String token = (String) arguments[1]; if (token != null) { if (!userSelfCreationAllowed && !subject.hasPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION)) { throw new ForbiddenException( "Currently only admins can create accounts. Please contact our Admin Team for further info."); } return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; case "remove": final String userToRemove = (String) arguments[0]; if (subject.getUserId().equals(userToRemove)) { return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; default: throw new ForbiddenException("User is not authorized to perform this operation"); } }</code><technical_language>Please revert this change</technical_language>

Target:
protected void filter(GenericResourceMethod genericResourceMethod, Object[] arguments) throws ApiException { final String methodName = genericResourceMethod.getMethod().getName(); final Subject subject = EnvironmentContext.getCurrent().getSubject(); switch (methodName) { case "getCurrent": case "updatePassword": case "getById": case "find": case "getSettings": return; case "create": final String token = (String) arguments[1]; if (token != null) { if (!userSelfCreationAllowed && !subject.hasPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION)) { throw new ForbiddenException( "Currently only admins can create accounts. Please contact our Admin Team for further info."); } return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; case "remove": final String userToRemove = (String) arguments[0]; if (subject.getUserId().equals(userToRemove)) { return; } subject.checkPermission(SystemDomain.DOMAIN_ID, null, MANAGE_USERS_ACTION); break; default: throw new ForbiddenException("User is not authorized to perform this operation"); } }
Source:
<code>private Pair<Long, Long> nibbleDeleteReplicated(ComparisonConstant op, int ts, long numberOfItems) throws NoConnectionsException, IOException { TimestampType value = new TimestampType(ts); VoltTable table = new VoltTable(new ColumnInfo[] { new ColumnInfo("col1", VoltType.typeFromObject(value)), }); table.addRow(value); long deleted = 0; long toBeDeleted = 0; long start = System.currentTimeMillis(); try { ClientResponse response = m_client.callProcedure("@NibbleDeleteMP", "rep", "ts", op.ordinal(), table, 500); VoltTable result = response.getResults()[0]; assertEquals(1, result.getRowCount()); result.advanceRow(); deleted = result.getLong("DELETED_ROWS"); long leftoverRows = result.getLong("LEFTOVER_ROWS"); toBeDeleted += leftoverRows; } catch (ProcCallException e) { <START> fail("Fail to run NibbleDeleteSP: " + e.getMessage()); <END> } System.out.println("Delete " + deleted + " rows on replicated table, " + toBeDeleted + " rows pending, cost " + (System.currentTimeMillis() - start) + " ms"); try { long rowCount = m_client.callProcedure("repcount").getResults()[0].asScalarLong(); assertEquals(numberOfItems - deleted, rowCount); } catch (ProcCallException e) { fail("Failed to get row count from Table part"); } return new Pair<>(deleted, toBeDeleted); }</code><technical_language>NibbleDeleteMP</technical_language>

Target:
private Pair<Long, Long> nibbleDeleteReplicated(ComparisonConstant op, int ts, long numberOfItems) throws NoConnectionsException, IOException { TimestampType value = new TimestampType(ts); VoltTable table = new VoltTable(new ColumnInfo[] { new ColumnInfo("col1", VoltType.typeFromObject(value)), }); table.addRow(value); long deleted = 0; long toBeDeleted = 0; long start = System.currentTimeMillis(); try { ClientResponse response = m_client.callProcedure("@NibbleDeleteMP", "rep", "ts", op.ordinal(), table, 500); VoltTable result = response.getResults()[0]; assertEquals(1, result.getRowCount()); result.advanceRow(); deleted = result.getLong("DELETED_ROWS"); long leftoverRows = result.getLong("LEFTOVER_ROWS"); toBeDeleted += leftoverRows; } catch (ProcCallException e) { fail("Fail to run NibbleDeleteMP: " + e.getMessage()); } System.out.println("Delete " + deleted + " rows on replicated table, " + toBeDeleted + " rows pending, cost " + (System.currentTimeMillis() - start) + " ms"); try { long rowCount = m_client.callProcedure("repcount").getResults()[0].asScalarLong(); assertEquals(numberOfItems - deleted, rowCount); } catch (ProcCallException e) { fail("Failed to get row count from Table part"); } return new Pair<>(deleted, toBeDeleted); }
Source:
<code>public void changesTheDirectionFromNorthToEast() { GridPosition initialGridPosition = new GridPosition(0, 0); Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnRight(); Orientation expectedOrientation = Orientation.EAST; <START> assertEquals(robot.getGridPosition(), initialGridPosition); <END> assertEquals(robot.getOrientation(), expectedOrientation); }</code><technical_language>noticed of assertions other assertEquals(expected, actual) if sense? do in this PR if want I open a new issue for related this change. you</technical_language>

Target:
public void changesTheDirectionFromNorthToEast() { GridPosition initialGridPosition = new GridPosition(0, 0); Robot robot = new Robot(initialGridPosition, Orientation.NORTH); robot.turnRight(); Orientation expectedOrientation = Orientation.EAST; assertEquals(initialGridPosition, robot.getGridPosition()); assertEquals(expectedOrientation, robot.getOrientation()); }
Source:
<code><START> public Optional<T> get(Random rand) { <END> int target = rand.nextInt(this.totalWeight); int current = 0; for (T obj : this) { current += obj.getWeight(); if (current > target) { return Optional.of(obj); } } return Optional.empty(); }</code><technical_language>@Deamon5550 if fine it</technical_language>

Target:
public T get(Random rand) { int target = rand.nextInt(this.totalWeight); int current = 0; for (T obj : this) { current += obj.getWeight(); if (current > target) { return obj; } } return null; }
Source:
<code>public RequestResponseHandlerController(int handlerCount, RestServerMetrics restServerMetrics) { if (handlerCount > 0) { this.restServerMetrics = restServerMetrics; <START> createRequestHandlers(handlerCount); <END> restServerMetrics.trackRequestHandlerHealth(requestResponseHandlers); } else { restServerMetrics.requestHandlerControllerInstantiationError.inc(); throw new IllegalArgumentException("Handlers to be created has to be > 0. Is " + handlerCount); } logger.trace("Instantiated RequestResponseHandlerController"); }</code><technical_language>I call this createRequestResponseHandlers(). distinction earlier requestHandlers responseHandlers, I explicit clear</technical_language>

Target:
public RequestResponseHandlerController(int handlerCount, RestServerMetrics restServerMetrics) { if (handlerCount > 0) { this.restServerMetrics = restServerMetrics; createRequestResponseHandlers(handlerCount); restServerMetrics.trackRequestHandlerHealth(asyncRequestResponseHandlers); } else { restServerMetrics.requestHandlerControllerInstantiationError.inc(); throw new IllegalArgumentException("Handlers to be created has to be > 0. Is " + handlerCount); } logger.trace("Instantiated RequestResponseHandlerController"); }
Source:
<code>public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDocumentExtractor extractor = context.get( EmbeddedDocumentExtractor.class, new ParsingEmbeddedDocumentExtractor(context)); TemporaryResources tmp = new TemporaryResources(); Archive rar = null; try { TikaInputStream tis = TikaInputStream.get(stream, tmp); rar = new Archive(tis.getFile()); if (rar.isEncrypted()) { throw new EncryptedDocumentException(); } xhtml.element("div", " "); FileHeader header = rar.nextFileHeader(); while (header != null && !Thread.currentThread().isInterrupted()) { if (!header.isDirectory()) { InputStream subFile = null; try { subFile = rar.getInputStream(header); Metadata entrydata = PackageParser.handleEntryMetadata( <START> header.getFileNameW().equals("")?header.getFileNameString():header.getFileNameW(), <END> header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml ); if (extractor.shouldParseEmbedded(entrydata)) { extractor.parseEmbedded(subFile, handler, entrydata, true); } } finally { if (subFile != null) subFile.close(); } } header = rar.nextFileHeader(); } } catch (RarException e) { throw new TikaException("RarParser Exception", e); } finally { if (rar != null) rar.close(); tmp.close(); } xhtml.endDocument(); }</code><technical_language>"".equals(header.getFileName()) syntax, this NullPointerException if wide file name is available. Alternatively add a null check</technical_language>

Target:
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); EmbeddedDocumentExtractor extractor = context.get( EmbeddedDocumentExtractor.class, new ParsingEmbeddedDocumentExtractor(context)); TemporaryResources tmp = new TemporaryResources(); Archive rar = null; try { TikaInputStream tis = TikaInputStream.get(stream, tmp); rar = new Archive(tis.getFile()); if (rar.isEncrypted()) { throw new EncryptedDocumentException(); } xhtml.element("div", " "); FileHeader header = rar.nextFileHeader(); while (header != null && !Thread.currentThread().isInterrupted()) { if (!header.isDirectory()) { InputStream subFile = null; try { subFile = rar.getInputStream(header); Metadata entrydata = PackageParser.handleEntryMetadata( "".equals(header.getFileNameW())?header.getFileNameString():header.getFileNameW(), header.getCTime(), header.getMTime(), header.getFullUnpackSize(), xhtml ); if (extractor.shouldParseEmbedded(entrydata)) { extractor.parseEmbedded(subFile, handler, entrydata, true); } } finally { if (subFile != null) subFile.close(); } } header = rar.nextFileHeader(); } } catch (RarException e) { throw new TikaException("RarParser Exception", e); } finally { if (rar != null) rar.close(); tmp.close(); } xhtml.endDocument(); }
Source:
<code>protected void onAttach() { super.onAttach(); register(EventController.get().addHandlerToSource(GetForumsEventHandler.TYPE, ForumController.get(), this)); register(EventController.get().addHandlerToSource(NavigationEventHandler.TYPE, NavigationController.get(), this)); <START> topics.redraw(); END> }</code><technical_language>Is this required</technical_language>

Target:
protected void onAttach() { super.onAttach(); register(EventController.get().addHandlerToSource(GetForumsEventHandler.TYPE, ForumController.get(), this)); register(EventController.get().addHandlerToSource(NavigationEventHandler.TYPE, NavigationController.get(), this)); }
Source:
<code>public List<DiagnosticsElement> getDiagnostics() { List<DiagnosticsElement> diagnosticsElements = new ArrayList<>(); Iterator<String> fieldNames = getJson().fieldNames(); boolean isHealthy = false; <START> String message = null; <END> while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode jsonNode = getJson().get(fieldName); if (jsonNode != null) { if (jsonNode.get(HEALTHY) != null) { isHealthy = jsonNode.get(HEALTHY).asBoolean(); } if (jsonNode.get(MESSAGE) != null) { message = jsonNode.get(MESSAGE).asText(); } diagnosticsElements.add(new DiagnosticsElement(fieldName, isHealthy, message)); } } return diagnosticsElements; }</code><technical_language>move block scope of jsonNode != null check</technical_language>

Target:
public List<DiagnosticsElement> getDiagnostics() { List<DiagnosticsElement> diagnosticsElements = new ArrayList<>(); if (getJson() != null) { Iterator<String> fieldNames = getJson().fieldNames(); while (fieldNames.hasNext()) { boolean isHealthy = false; String message = null; String fieldName = fieldNames.next(); JsonNode jsonNode = getJson().get(fieldName); if (jsonNode != null) { if (jsonNode.get(HEALTHY) != null) { isHealthy = jsonNode.get(HEALTHY).asBoolean(); } if (jsonNode.get(MESSAGE) != null) { message = jsonNode.get(MESSAGE).asText(); } else { message = new String("Message Unavailable"); } diagnosticsElements.add(new DiagnosticsElement(fieldName, isHealthy, message)); } } } return diagnosticsElements; }
Source:
<code>public void stop(StopContext context) { super.stop(context); <START> System.clearProperty("wildfly.test.boot.disable.rollback"); <END> }</code><technical_language>This out of sync I reverted WFCORE-307 fix. correct property is "jboss.as.test.disable.runtime"</technical_language>

Target:
public void stop(StopContext context) { super.stop(context); System.clearProperty("jboss.as.test.disable.runtime"); }
Source:
<code>public void hideKeyboard(View view) { InputMethodManager inputManager = (InputMethodManager) this .getSystemService(Context.INPUT_METHOD_SERVICE); View focusedView = this.getCurrentFocus(); <START> if (focusedView != null) { <END> inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN); } }</code><technical_language>1. This change is related AndroidX porting. So, here. 2. if view is null</technical_language>

Target:
public void hideKeyboard(View view) { InputMethodManager inputManager = (InputMethodManager) this .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager .RESULT_UNCHANGED_SHOWN); }
Source:
<code>public void fillMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size, int count, byte[] pattern, RequestMonitor rm) { if (memoryDMC == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Unknown context type", null)); rm.done(); return; } if (word_size < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Word size not supported (< 1)", null)); rm.done(); return; } if (count < 0) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Invalid repeat count (< 0)", null)); rm.done(); return; } if (pattern.length < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Empty pattern", null)); rm.done(); return; } int length = pattern.length; byte[] buffer = new byte[count * length]; for (int i = 0; i < count; i++) { System.arraycopy(pattern, 0, buffer, i * length, length); } <START> getMemoryCache(memoryDMC).setMemory(memoryDMC, address, offset, word_size, count * length, buffer, rm); <END> }</code><technical_language>I a count issue here. other places, this count is completely different. I 'count*length' param 'count*length/word_size' checking if +1 is needed. do think? Note this method called tests, explain noticed before</technical_language>

Target:
public void fillMemory(IMemoryDMContext memoryDMC, IAddress address, long offset, int word_size, int count, byte[] pattern, RequestMonitor rm) { if (memoryDMC == null) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Unknown context type", null)); rm.done(); return; } if (word_size < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Word size not supported (< 1)", null)); rm.done(); return; } if (count < 0) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Invalid repeat count (< 0)", null)); rm.done(); return; } if (pattern.length < 1) { rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, IDsfStatusConstants.INTERNAL_ERROR, "Empty pattern", null)); rm.done(); return; } int length = pattern.length; byte[] buffer = new byte[count * length]; for (int i = 0; i < count; i++) { System.arraycopy(pattern, 0, buffer, i * length, length); } int word_count = buffer.length / word_size; if (buffer.length % word_size != 0) { word_count ++; } getMemoryCache(memoryDMC).setMemory(memoryDMC, address, offset, word_size, word_count, buffer, rm); }
Source:
<code>public List<DataSegment> getUsedSegmentsForIntervals( final String dataSource, final List<Interval> intervals ) throws IOException { final StringBuilder sb = new StringBuilder(); sb.append("SELECT payload FROM %s WHERE used = true AND dataSource = :dataSource AND ("); for (int i = 0; i < intervals.size(); i++) { Interval interval = intervals.get(i); sb.append("(start <= '" + interval.getEnd().toString() + "' AND \"end\" >= '" + interval.getStart().toString() + "')"); <START> if (i == intervals.size()-1) { <END> sb.append(")"); } else { sb.append(" OR "); } } final VersionedIntervalTimeline<String, DataSegment> timeline = connector.getDBI().withHandle( new HandleCallback<VersionedIntervalTimeline<String, DataSegment>>() { @Override public VersionedIntervalTimeline<String, DataSegment> withHandle(Handle handle) throws IOException { final VersionedIntervalTimeline<String, DataSegment> timeline = new VersionedIntervalTimeline<String, DataSegment>( Ordering.natural() ); final ResultIterator<byte[]> dbSegments = handle.createQuery( String.format( sb.toString(), dbTables.getSegmentsTable() ) ) .bind("dataSource", dataSource) .map(ByteArrayMapper.FIRST) .iterator(); while (dbSegments.hasNext()) { final byte[] payload = dbSegments.next(); DataSegment segment = jsonMapper.readValue( payload, DataSegment.class ); timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); } dbSegments.close(); return timeline; } } ); return Lists.newArrayList( Iterables.concat( Iterables.transform( Iterables.concat( Iterables.transform( intervals, new Function<Interval, Iterable<TimelineObjectHolder<String, DataSegment>>>() { @Override public Iterable<TimelineObjectHolder<String, DataSegment>> apply(Interval interval) { return timeline.lookup(interval); } } ) ), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); }</code><technical_language>formatting</technical_language>

Target:
public List<DataSegment> getUsedSegmentsForIntervals( final String dataSource, final List<Interval> intervals ) throws IOException { return connector.retryWithHandle( new HandleCallback<List<DataSegment>>() { @Override public List<DataSegment> withHandle(Handle handle) throws Exception { final VersionedIntervalTimeline<String, DataSegment> timeline = getTimelineForIntervalsWithHandle( handle, dataSource, intervals ); Set<DataSegment> segments = Sets.newHashSet( Iterables.concat( Iterables.transform( Iterables.concat( Iterables.transform( intervals, new Function<Interval, Iterable<TimelineObjectHolder<String, DataSegment>>>() { @Override public Iterable<TimelineObjectHolder<String, DataSegment>> apply(Interval interval) { return timeline.lookup(interval); } } ) ), new Function<TimelineObjectHolder<String, DataSegment>, Iterable<DataSegment>>() { @Override public Iterable<DataSegment> apply(TimelineObjectHolder<String, DataSegment> input) { return input.getObject().payloads(); } } ) ) ); return new ArrayList<>(segments); } } ); }
Source:
<code>public String docs() { <START> return "void {[player], flight} Sets whether or not this player is flying. Requires player to have the ability to fly."; <END> }</code><technical_language>put player get ability (mention set_pflight)</technical_language>

Target:
public String docs() { return "void {[player], flight} Sets whether or not this player is flying." + "Requires player to have the ability to fly, which is set with set_pflight()."; }
Source:
<code>public void shouldReportXssInLocationHashAssign(String browser) throws NullPointerException, IOException { String test = "/shouldReportXssInLocationHashAssign/"; this.nano.addHandler( <START> new NanoServerHandler(test) { <END> @Override protected Response serve(IHTTPSession session) { String response = getHtml("LocationHashAssign.html"); return newFixedLengthResponse(response); } }); HttpMessage msg = this.getHttpMessage(test); this.rule.getConfig().setProperty("rules.domxss.browserid", browser); this.rule.init(msg, this.parent); this.rule.scan(); assertAlertsRaised(); }</code><technical_language>Worth extracting a class</technical_language>

Target:
public void shouldReportXssInLocationHashAssign(String browser) throws NullPointerException, IOException { String test = "/shouldReportXssInLocationHashAssign/"; this.nano.addHandler(new TestNanoServerHandler(test, "LocationHashAssign.html")); HttpMessage msg = this.getHttpMessage(test); this.rule.getConfig().setProperty("rules.domxss.browserid", browser); this.rule.init(msg, this.parent); this.rule.scan(); assertAlertsRaised(); }
Source:
<code>public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart)part).findReplacement(true); } if (null != replacement) { if(replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement.getId()); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement.getId()); } } else { newShoppingList.add(part); } } } boolean missingAmmo = false; for (int pid : newUnitParts) { Part part = getCampaign().getPart(pid); if (part instanceof AmmoBin) { AmmoBin bin = (AmmoBin) part; Part foundAmmo = getCampaign().findSparePart(campaignPart -> AmmoStorage.IsRightAmmo(campaignPart, (AmmoType) bin.getType())); <START> if (foundAmmo == null || (((AmmoStorage) foundAmmo).getShots() < bin.getShotsNeeded())) { <END> missingAmmo = true; break; } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && !missingAmmo && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }</code><technical_language>suggestion if ((foundAmmo == null) || (((AmmoStorage) foundAmmo).getShots() < bin.getShotsNeeded())) {</technical_language>

Target:
public boolean acquireParts() { if (!customJob) { checkForArmorSupplies(); return kitFound && !partsInTransit() && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); } ArrayList<Part> newShoppingList = new ArrayList<>(); for (Part part : shoppingList) { if (part instanceof IAcquisitionWork) { Part replacement = part; if (part instanceof MissingPart) { replacement = ((MissingPart)part).findReplacement(true); } if (null != replacement) { if(replacement.getQuantity() > 1) { Part actualReplacement = replacement.clone(); actualReplacement.setRefitId(oldUnit.getId()); oldUnit.getCampaign().addPart(actualReplacement, 0); newUnitParts.add(actualReplacement.getId()); replacement.decrementQuantity(); } else { replacement.setRefitId(oldUnit.getId()); newUnitParts.add(replacement.getId()); } } else { newShoppingList.add(part); } } } boolean missingAmmo = false; for (int pid : newUnitParts) { Part part = getCampaign().getPart(pid); if (part instanceof AmmoBin) { AmmoBin bin = (AmmoBin) part; Part foundAmmo = getCampaign().findSparePart(campaignPart -> AmmoStorage.IsRightAmmo(campaignPart, (AmmoType) bin.getType())); if ((foundAmmo == null) || (((AmmoStorage) foundAmmo).getShots() < bin.getShotsNeeded())) { missingAmmo = true; break; } } } checkForArmorSupplies(); shoppingList = newShoppingList; if (partsInTransit()) { return false; } return shoppingList.size() == 0 && !missingAmmo && (null == newArmorSupplies || (armorNeeded - newArmorSupplies.getAmount()) <= 0); }
Source:
<code>protected List<SinkRecord> createStringRecords( int size, Set<TopicPartition> partitions ) { String key = "key"; List<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0, total = 0; total < size; ++offset) { for (TopicPartition tp : partitions) { <START> String record = "Some random text..."; <END> sinkRecords.add(new SinkRecord(TOPIC, tp.partition(), null, key, null, record, offset)); if (++total >= size) { break; } } } return sinkRecords; }</code><technical_language>include offset in text message produce content in record</technical_language>

Target:
protected List<SinkRecord> createStringRecords( int size, Set<TopicPartition> partitions ) { String key = "key"; List<SinkRecord> sinkRecords = new ArrayList<>(); for (long offset = 0, total = 0; total < size; ++offset) { for (TopicPartition tp : partitions) { String record = "Some random text. Offset: " + offset; sinkRecords.add(new SinkRecord(TOPIC, tp.partition(), null, key, null, record, offset)); if (++total >= size) { break; } } } return sinkRecords; }
Source:
<code>private int measureIfRoomItems(int widthUsed, int alwaysItemsWidth, int widthMeasureSpec, int heightMeasureSpec) { int width = 0; boolean <START> widthUnspecified = <END> MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED; int widthCapacity = (MeasureSpec.getSize(widthMeasureSpec) / 2) - alwaysItemsWidth; int allowedCount = ACTION_ITEM_COUNT_LIMIT - mAlwaysItemCount; for (InflatedMenuItem inflatedItem : mAllMenuItems) { if (allowedCount == 0 || (!widthUnspecified && widthCapacity <= mMinActionButtonWidth)) { break; } if (inflatedItem.mItem.getDisplayBehavior() == CarMenuItem.DisplayBehavior.IF_ROOM) { View action = inflatedItem.mView; measureChild(action, widthMeasureSpec, widthUsed + width, heightMeasureSpec, 0); int viewWidth = action.getMeasuredWidth() + getHorizontalMargins(action); if (widthUnspecified || widthCapacity - viewWidth > 0) { allowedCount--; widthCapacity -= viewWidth; width += viewWidth; inflatedItem.mIsDisplayedOnToolbar = true; addView(action); } } } return width; }</code><technical_language>isWidthUnspecified* instead</technical_language>

Target:
private int measureIfRoomItems(int widthUsed, int alwaysItemsWidth, int widthMeasureSpec, int heightMeasureSpec) { int width = 0; boolean isWidthUnspecified = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.UNSPECIFIED; int widthCapacity = (MeasureSpec.getSize(widthMeasureSpec) / 2) - alwaysItemsWidth; int allowedCount = ACTION_ITEM_COUNT_LIMIT - mAlwaysItemCount; for (InflatedMenuItem inflatedItem : mAllMenuItems) { if (allowedCount < 1 || (!isWidthUnspecified && widthCapacity <= mMinActionButtonWidth)) { break; } if (inflatedItem.mItem.getDisplayBehavior() == CarMenuItem.DisplayBehavior.IF_ROOM) { View action = inflatedItem.mView; measureChild(action, widthMeasureSpec, widthUsed + width, heightMeasureSpec, 0); int viewWidth = action.getMeasuredWidth() + getHorizontalMargins(action); if (isWidthUnspecified || widthCapacity - viewWidth > 0) { allowedCount--; widthCapacity -= viewWidth; width += viewWidth; inflatedItem.mIsDisplayedOnToolbar = true; addView(action); } } } return width; }
Source:
<code><START> protected Set<InternalCacheEntry> loadAllLockSafe() <END> throws CacheLoaderException { EntityManager em = emf.createEntityManager(); try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery cq = cb.createQuery(config.getEntityClass()); cq.select(cq.from(config.getEntityClass())); TypedQuery q = em.createQuery(cq); List list = q.getResultList(); if (list == null || list.isEmpty()) { return Collections.emptySet(); } PersistenceUnitUtil util = emf.getPersistenceUnitUtil(); Set<InternalCacheEntry> result = new HashSet<InternalCacheEntry>( list.size()); for (Object o : list) { Object key = util.getIdentifier(o); result.add(new ImmortalCacheEntry(key, o)); } return result; } finally { em.close(); } }</code><technical_language>reuse code: delegate loadAllLockSafe(-1) in loadAllLockSafe(int) set maxResults if passed in is positive</technical_language>

Target:
protected Set<InternalCacheEntry> loadAllLockSafe() throws CacheLoaderException { return loadLockSafe(-1); }
Source:
<code>public Map<String, String> prepareImages(Map<String, DockerContainerConfig> containers) throws InterruptedException, InfrastructureException { if (executor.getActiveCount() + containers.size() > executor.getMaximumPoolSize()) { LOG.warn( String.format( "Maximum parallel images preparing threads reached. Some images will be queued.\n" + " Workspace machines count is %s. If problem persists, increase %s property value.", containers.size(), PARALLEL_PULL_PROPERTY_NAME)); } Map<String, String> imagesMap = new ConcurrentHashMap<>(containers.size()); CompletableFuture<Void> firstFailed = new CompletableFuture<>(); List<CompletableFuture<Void>> taskFutures = containers .entrySet() .stream() .map( e -> CompletableFuture.supplyAsync( (Supplier<Void>) () -> { try { imagesMap.put(e.getKey(), prepareImage(e.getKey(), e.getValue())); } catch (InternalInfrastructureException | SourceNotFoundException ex) { firstFailed.completeExceptionally(ex); } return null; }, executor)) .collect(toList()); CompletableFuture all = CompletableFuture.allOf(taskFutures.toArray(new CompletableFuture[taskFutures.size()])); try { CompletableFuture.anyOf(all, firstFailed).get(); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { <START> throw new InternalInfrastructureException("Unable to build image", thr); <END> } } return imagesMap; }</code><technical_language>Is images build? build pull</technical_language>

Target:
public Map<String, String> prepareImages(Map<String, DockerContainerConfig> containers) throws InterruptedException, InfrastructureException { if (executor.getActiveCount() + containers.size() > executor.getMaximumPoolSize()) { LOG.warn( String.format( "Maximum parallel images preparing threads reached. Some images will be queued.\n" + " Workspace machines count is %s. If problem persists, increase %s property value.", containers.size(), PARALLEL_PULL_PROPERTY_NAME)); } Map<String, String> machineToImageNames = new ConcurrentHashMap<>(containers.size()); CompletableFuture<Void> firstFailed = new CompletableFuture<>(); List<CompletableFuture<Void>> taskFutures = containers .entrySet() .stream() .map( e -> CompletableFuture.supplyAsync( (Supplier<Void>) () -> { try { machineToImageNames.put( e.getKey(), prepareImage(e.getKey(), e.getValue())); } catch (InternalInfrastructureException | SourceNotFoundException ex) { firstFailed.completeExceptionally(ex); } return null; }, executor)) .collect(toList()); CompletableFuture all = CompletableFuture.allOf(taskFutures.toArray(new CompletableFuture[taskFutures.size()])); try { CompletableFuture.anyOf(all, firstFailed).get(); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { throw new InternalInfrastructureException("Unable to build or pull image", thr); } } return machineToImageNames; }
Source:
<code>public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { <START> if (!authorizationService.isAuthorized(null, AuthorizationService.Operation.READ, resource)) { <END> throw new AccessDeniedException(null, AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }</code><technical_language>is this subject? null</technical_language>

Target:
public void authorizeStreamRead(final EventType eventType) throws AccessDeniedException { if (eventType.getAuthorization() == null) { return; } final Resource resource = new EventTypeResource(eventType.getName(), eventType.getAuthorization()); try { if (!authorizationService.isAuthorized(AuthorizationService.Operation.READ, resource)) { throw new AccessDeniedException(AuthorizationService.Operation.READ, resource); } } catch (final PluginException e) { throw new ServiceTemporarilyUnavailableException("Error calling authorization plugin", e); } }
Source:
<code><START> private static boolean validEmail(String email) { <END> return true; }</code><technical_language>While removing validators return true, consider fixing validEmail</technical_language>

Target:
private static boolean validEmail(String email) { return Patterns.EMAIL_ADDRESS.matcher(email).matches(); }