auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void validateNewTraceName() { String newTraceName = fNewElementName.getText(); TmfCommonProjectElement element = fElement; IWorkspace workspace = element.getResource().getWorkspace(); IStatus nameStatus = workspace.validateName(newTraceName, IResource.FOLDER); if ("".equals(newTraceName)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } IContainer parentFolder = element.getResource().getParent(); if (parentFolder.findMember(newTraceName) != null) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; <START> } <END> updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }</code><technical_language>validate name is destination (only relevant trimming experiment, I think?)</technical_language>

Target:
private void validateNewTraceName() { String newTraceName = fNewElementName.getText(); TmfCommonProjectElement element = fElement; IWorkspace workspace = element.getResource().getWorkspace(); IStatus nameStatus = workspace.validateName(newTraceName, IResource.FOLDER); if ("".equals(newTraceName)) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_EmptyNameError, null)); return; } if (!nameStatus.isOK()) { updateStatus(nameStatus); return; } IContainer parentFolder = element.getResource().getParent(); if (parentFolder.findMember(newTraceName) != null) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } TmfTraceFolder tracesFolderElement = element.getProject().getTracesFolder(); if (tracesFolderElement != null) { IFolder tracesFolder = tracesFolderElement.getResource(); IPath traceDestinationPath = new Path(newTraceName); if (tracesFolder.getFolder(traceDestinationPath).exists()) { updateStatus(new Status(IStatus.ERROR, Activator.PLUGIN_ID, IStatus.ERROR, Messages.Dialog_ExistingNameError, null)); return; } } updateStatus(new Status(IStatus.OK, Activator.PLUGIN_ID, "")); }
Source:
<code><START> public Date getNeedBy() { <END> try { return ((XDate) page2.getXWidget(NewActionPage2.DEADLINE)).getDate(); } catch (Exception ex) { return null; } }</code><technical_language>Instead of try/catch, do XDate needByDate = ((XDate) page2.getXWidget(NewActionPage2.DEADLINE)); if (needByDate != null) { return needByDate.getDate(); } return null;</technical_language>

Target:
public Date getNeedBy() { if (page2.hasNeedByDate()) { return ((XDate) page2.getXWidget(NewActionPage2.DEADLINE)).getDate(); } return null; }
Source:
<code>private void executeSingleCommand(String str) { ICommand<MIInfo> cmd; if (!isMIOperation(str) && !CLIEventProcessor.isSteppingOperation(str)) { cmd = new MIInterpreterExecConsole<>(fContext, str); } else { cmd = new CLICommand<>(fContext, str); } fExecutor.execute(new DsfRunnable() { @Override public void run() { ICommandControlService commandControl = fServiceTracker.getService(ICommandControlService.class); <START> if (commandControl != null) { <END> commandControl.queueCommand(cmd, new ImmediateDataRequestMonitor<>()); } } }); }</code><technical_language>if this is null suppose mean? Log something</technical_language>

Target:
private void executeSingleCommand(String str) { ICommand<MIInfo> cmd; if (!isMIOperation(str) && !CLIEventProcessor.isSteppingOperation(str)) { cmd = new MIInterpreterExecConsole<>(fContext, str); } else { cmd = new CLICommand<>(fContext, str); } fExecutor.execute(new DsfRunnable() { @Override public void run() { ICommandControlService commandControl = fServiceTracker.getService(ICommandControlService.class); if (commandControl != null) { commandControl.queueCommand(cmd, new ImmediateDataRequestMonitor<>()); } else { GdbPlugin.log(new Status( IStatus.INFO, GdbPlugin.PLUGIN_ID, "Unable to find service to execute breakpoint command")); } } }); }
Source:
<code>public void removeAllBodies() { <START> pendingRemoves.addAll(dynamicBodies); <END> pendingAdds.clear(); }</code><technical_language>this include static kinetic bodies? method "removeAllDynamicBodies"</technical_language>

Target:
public void removeAllBodies() { pendingRemoves.addAll(dynamicBodies); pendingRemoves.addAll(kineticBodies); pendingRemoves.addAll(staticBodies); pendingAdds.clear(); }
Source:
<code>public InstallationsView(ThemeManager themeManager, JavaFxSettingsManager javaFxSettingsManager) { super(tr("Installations"), themeManager); this.javaFxSettingsManager = javaFxSettingsManager; this.filter = new InstallationsFilter(); this.selectedListWidget = new SimpleObjectProperty<>(); this.categories = FXCollections.observableArrayList(); this.installation = new SimpleObjectProperty<>(); this.getStyleClass().add("mainWindowScene"); this.activeInstallations = createInstallationListWidget(); final StringBinding openInstallations = Bindings.createStringBinding( <START> () -> Integer.toString(this.activeInstallations.getElements().size()), <END> this.activeInstallations.getElements()); final TabIndicator indicator = new TabIndicator(); indicator.textProperty().bind(openInstallations); this.graphicProperty().bind(Bindings.when(Bindings.notEqual(openInstallations, "0")).then(indicator) .otherwise(new SimpleObjectProperty<>())); this.filter.selectedInstallationCategoryProperty().addListener((Observable invalidation) -> closeDetailsView()); this.installationDetailsPanel = createInstallationDetailsPanel(); final InstallationSidebar installationSidebar = createInstallationsSidebar(); setSidebar(installationSidebar); setCenter(activeInstallations); }</code><technical_language>happen if >9 elements? show a "+" "i" instead of 10? I assume more character fit in circle</technical_language>

Target:
public InstallationsView(ThemeManager themeManager, JavaFxSettingsManager javaFxSettingsManager) { super(tr("Installations"), themeManager); this.javaFxSettingsManager = javaFxSettingsManager; this.filter = new InstallationsFilter(); this.selectedListWidget = new SimpleObjectProperty<>(); this.categories = FXCollections.observableArrayList(); this.installation = new SimpleObjectProperty<>(); this.getStyleClass().add("mainWindowScene"); this.activeInstallations = createInstallationListWidget(); final IntegerBinding openInstallations = Bindings.createIntegerBinding( () -> this.activeInstallations.getElements().size(), this.activeInstallations.getElements()); final TabIndicator indicator = new TabIndicator(); indicator.textProperty().bind(StringBindings.map(openInstallations, numberOfInstallations -> { if (numberOfInstallations.intValue() < 10) { return String.valueOf(numberOfInstallations); } else { return "+"; } })); this.graphicProperty().bind(Bindings.when(Bindings.notEqual(openInstallations, 0)).then(indicator) .otherwise(new SimpleObjectProperty<>())); this.filter.selectedInstallationCategoryProperty().addListener((Observable invalidation) -> closeDetailsView()); this.installationDetailsPanel = createInstallationDetailsPanel(); final InstallationSidebar installationSidebar = createInstallationsSidebar(); setSidebar(installationSidebar); setCenter(activeInstallations); }
Source:
<code>FatekContactItem(Item item, List<String> confItems) throws BindingConfigParseException { super(item, confItems); if (confItems.size() != 1) { <START> throw new BindingConfigParseException("Incorect number of register for contact binding"); <END> } }</code><technical_language>"Incorrect"</technical_language>

Target:
FatekContactItem(Item item, List<String> confItems) throws BindingConfigParseException { super(item, confItems); if (confItems.size() != 1) { throw new BindingConfigParseException("Incorrect number of register for contact binding"); } String regName = confItems.get(0); if (regName.startsWith("!") ) { regName = regName.substring(1); negate = true; } else { negate = false; } try { reg1 = Reg.parse(regName); } catch (UnknownRegNameException e) { throw new BindingConfigParseException(e.getMessage()); } }
Source:
<code>public <START> RepositoryHandle(Repository delegate) { <END> super(new RepositoryBuilder()); this.delegate = delegate; addListeners(listeners, delegate.getListenerList(), new WeakReference<>(this)); }</code><technical_language>delegate a handle itself, necessary add some code unwrap here, assertion avoid it, nested handles perfectly fine</technical_language>

Target:
RepositoryHandle(Repository delegate) { super(new RepositoryBuilder()); Assert.isLegal(!(delegate instanceof RepositoryHandle), "Delegate of a RepositoryHandle must not be another RepositoryHandle"); this.delegate = delegate; addListeners(listeners, delegate.getListenerList(), new WeakReference<>(this)); }
Source:
<code>public void testRelaxedExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(EXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); <START> assertTrue(ctx().isOriginalEmptyValue()); <END> assertEquals("Expired state should be cleared on access", ctx().emptyValue, ctx().get()); }</code><technical_language>suggestion assertTrue("Original state cleared access", ctx().isOriginalEmptyValue());</technical_language>

Target:
public void testRelaxedExpirationOnWrite() throws Exception { initTest(StateTtlConfig.UpdateType.OnCreateAndWrite, StateTtlConfig.StateVisibility.ReturnExpiredIfNotCleanedUp); timeProvider.time = 0; ctx().update(ctx().updateEmpty); takeAndRestoreSnapshot(); timeProvider.time = 120; assertEquals(EXPIRED_AVAIL, ctx().getUpdateEmpty, ctx().get()); assertTrue("Original state should be cleared on access", ctx().isOriginalEmptyValue()); assertEquals("Expired state should be cleared on access", ctx().emptyValue, ctx().get()); }
Source:
<code>public ConnectorTestProcessor() throws IOException { tests = ImmutableSet.of(); connectors = ImmutableSet.of(); Properties properties = new Properties(); URL url = this.getClass().getClassLoader().getResource(VELOCITY_PROPERTIES); <START> properties.load(url.openStream()); <END> VelocityEngine velocityEngine = new VelocityEngine(properties); template = velocityEngine.getTemplate("ConnectorTest.vt"); }</code><technical_language>url.openStream() closed</technical_language>

Target:
public ConnectorTestProcessor() throws IOException { Reflections reflections = new Reflections("com.facebook.presto.featuretests"); tests = sanityChecked(reflections.getTypesAnnotatedWith(ConnectorTest.class)); connectors = ImmutableSet.of(); Properties properties = new Properties(); URL url = this.getClass().getClassLoader().getResource(VELOCITY_PROPERTIES); try (InputStream inputStream = url.openStream()) { properties.load(inputStream); } VelocityEngine velocityEngine = new VelocityEngine(properties); template = velocityEngine.getTemplate("ConnectorTest.vt"); }
Source:
<code>public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) { DeclaredType asType = (DeclaredType) replaceTypeElementIfNecessary( elementUtils, includingType ).asType(); <START> TypeMirror asMemberOf = SpecificCompilerWorkarounds.asMemberOf( asType, method, typeUtils, elementUtils ); <END> ExecutableType methodType = asMemberOf.accept( new ExecutableTypeRetrievalVisitor(), null ); return methodType; }</code><technical_language>add a CS rule in code base original isMemberOf() is invoked? IIRC, provide a fail build if specific methods invoked</technical_language>

Target:
public ExecutableType getMethodType(TypeElement includingType, ExecutableElement method) { DeclaredType asType = (DeclaredType) replaceTypeElementIfNecessary( elementUtils, includingType ).asType(); TypeMirror asMemberOf = typeUtils.asMemberOf( asType, method ); return (ExecutableType) asMemberOf; }
Source:
<code>public Observable<Void> release(PooledConnection<I, O> connection) { if (null == connection) { return Observable.error(new IllegalArgumentException("Returned a null connection to the pool.")); } long startTimeMillis = Clock.newStartTimeMillis(); aquiredConnectionsCounter.decrementAndGet(); try { connection.getChannel().pipeline().fireUserEventTriggered(new PooledConnectionReleasedEvent(connection)); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_START); if (isShutdownRequested.get() || !connection.isUsable()) { discardConnection(connection); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_SUCCESS, Clock.onEndMillis( startTimeMillis)); <START> performShutdownIfRequested(); <END> return Observable.empty(); } else { idleConnections.add(connection); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_SUCCESS, Clock.onEndMillis( startTimeMillis)); performShutdownIfRequested(); return Observable.empty(); } } catch (Throwable throwable) { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_FAILED, Clock.onEndMillis(startTimeMillis)); performShutdownIfRequested(); return Observable.error(throwable); } }</code><technical_language>I call this aquiredConnectionsCounter.decrementAndGet(); returns 0</technical_language>

Target:
public Observable<Void> release(PooledConnection<I, O> connection) { if (null == connection) { return Observable.error(new IllegalArgumentException("Returned a null connection to the pool.")); } long startTimeMillis = Clock.newStartTimeMillis(); try { connection.getChannel().pipeline().fireUserEventTriggered(new PooledConnectionReleasedEvent(connection)); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_START); if (isShutdownRequested.get() || !connection.isUsable()) { discardConnection(connection); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_SUCCESS, Clock.onEndMillis( startTimeMillis)); return Observable.empty(); } else { idleConnections.add(connection); metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_SUCCESS, Clock.onEndMillis( startTimeMillis)); return Observable.empty(); } } catch (Throwable throwable) { metricEventsSubject.onEvent(ClientMetricsEvent.POOL_RELEASE_FAILED, Clock.onEndMillis(startTimeMillis)); return Observable.error(throwable); } finally { aquiredConnectionsCounter.decrementAndGet(); } }
Source:
<code>private Thread createThread(final Runnable target) { final ThreadNameInfo nameInfo = new ThreadNameInfo(globalThreadIndexSequence.getAndIncrement(), factoryThreadIndexSequence.getAndIncrement(), factoryIndex, node, component); Thread thread = new Thread(threadGroup, target); thread.setName(nameInfo.format(thread, threadNamePattern)); <START> if (initialPriority != null) thread.setPriority(initialPriority); <END> thread.setDaemon(true); return thread; }</code><technical_language>initialPriority is null</technical_language>

Target:
private Thread createThread(final Runnable target) { final ThreadNameInfo nameInfo = new ThreadNameInfo(globalThreadIndexSequence.getAndIncrement(), factoryThreadIndexSequence.getAndIncrement(), factoryIndex, node, component); Thread thread = new Thread(threadGroup, target); thread.setName(nameInfo.format(thread, threadNamePattern)); thread.setPriority(initialPriority); thread.setDaemon(true); return thread; }
Source:
<code><START> private Map<String, ResourceAssignment> getBestPossibleAssignment( <END> AssignmentMetadataStore assignmentMetadataStore, CurrentStateOutput currentStateOutput, Set<String> resources) throws HelixRebalanceException { Map<String, ResourceAssignment> currentBestAssignment = Collections.emptyMap(); if (assignmentMetadataStore != null) { try { currentBestAssignment = assignmentMetadataStore.getBestPossibleAssignment(); } catch (HelixException ex) { LOG.error("Failed to get the current best possible assignment.", ex); } catch (Exception ex) { throw new HelixRebalanceException( "Failed to get the current best possible assignment because of unexpected error.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } } if (currentBestAssignment.isEmpty()) { LOG.warn( "The current best possible assignment record is empty. Use the current states instead."); currentBestAssignment = getCurrentStateAssingment(currentStateOutput, resources); } return currentBestAssignment; }</code><technical_language>metric for this read latency</technical_language>

Target:
private Map<String, ResourceAssignment> getBestPossibleAssignment( AssignmentMetadataStore assignmentMetadataStore, CurrentStateOutput currentStateOutput, Set<String> resources) throws HelixRebalanceException { Map<String, ResourceAssignment> currentBestAssignment = Collections.emptyMap(); if (assignmentMetadataStore != null) { try { LatencyMetric stateReadLatency = _metricCollector.getMetric( WagedRebalancerMetricCollector.WagedRebalancerMetricNames.StateReadLatencyGauge.name(), LatencyMetric.class); stateReadLatency.startMeasuringLatency(); currentBestAssignment = assignmentMetadataStore.getBestPossibleAssignment(); stateReadLatency.endMeasuringLatency(); } catch (HelixException ex) { LOG.error("Failed to get the current best possible assignment.", ex); } catch (Exception ex) { throw new HelixRebalanceException( "Failed to get the current best possible assignment because of unexpected error.", HelixRebalanceException.Type.INVALID_REBALANCER_STATUS, ex); } } if (currentBestAssignment.isEmpty()) { LOG.warn( "The current best possible assignment record is empty. Use the current states instead."); currentBestAssignment = getCurrentStateAssingment(currentStateOutput, resources); } return currentBestAssignment; }
Source:
<code>public void safeRun() { if (callbackTriggered) { maybeRecycle(); return; } this.requestTimeNanos = MathUtils.nowInNano(); checkNotNull(lh); checkNotNull(lh.macManager); this.toSend = lh.macManager.computeDigestAndPackageForSending( entryId, lh.lastAddConfirmed, currentLedgerLength, payload); DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId); try { for (int i = 0; i < writeSet.size(); i++) { sendWriteRequest(writeSet.get(i)); } } finally { <START> hasRun = true; <END> writeSet.recycle(); } }</code><technical_language>reason this is moved here</technical_language>

Target:
public void safeRun() { hasRun = true; if (callbackTriggered) { maybeRecycle(); return; } this.requestTimeNanos = MathUtils.nowInNano(); checkNotNull(lh); checkNotNull(lh.macManager); this.toSend = lh.macManager.computeDigestAndPackageForSending( entryId, lh.lastAddConfirmed, currentLedgerLength, payload); DistributionSchedule.WriteSet writeSet = lh.distributionSchedule.getWriteSet(entryId); try { for (int i = 0; i < writeSet.size(); i++) { sendWriteRequest(writeSet.get(i)); } } finally { writeSet.recycle(); } }
Source:
<code>public Response toolsIndexGet(SecurityContext securityContext) { List<Entry> published = getPublished(); if (!config.getEsConfiguration().getHostname().isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { LOG.info("Deleting the ES index."); try { restClient.performRequest("DELETE", "/entry"); } catch (Exception e) { <START> throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); <END> } URL url = Resources.getResource("queries/mapping.json"); String text = Resources.toString(url, StandardCharsets.UTF_8); HttpEntity mappingEntity = new NStringEntity(text, ContentType.APPLICATION_JSON); LOG.info("Recreating the ES index."); restClient.performRequest("PUT", "/entry", Collections.emptyMap(), mappingEntity); ElasticManager elasticManager = new ElasticManager(); elasticManager.bulkUpsert(published); } catch (IOException e) { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(published.size()).build(); } return Response.ok().entity(0).build(); }</code><technical_language>start a new elasticsearch container (with index). This endpoint unusable</technical_language>

Target:
public Response toolsIndexGet(SecurityContext securityContext) { List<Entry> published = getPublished(); if (!config.getEsConfiguration().getHostname().isEmpty() && !published.isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { try { restClient.performRequest("DELETE", "/entry"); } catch (Exception e) { e.printStackTrace(); } URL url = Resources.getResource("queries/mapping.json"); String text = Resources.toString(url, StandardCharsets.UTF_8); HttpEntity mappingEntity = new NStringEntity(text, ContentType.APPLICATION_JSON); restClient.performRequest("PUT", "/entry", Collections.emptyMap(), mappingEntity); ElasticManager elasticManager = new ElasticManager(); elasticManager.bulkUpsert(published); } catch (IOException e) { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(published.size()).build(); } return Response.ok().entity(0).build(); }
Source:
<code>public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { <START> if (!tc.getProduction().getItems().isEmpty() && tc.getProduction().getItems().get(0) instanceof UserList) { <END> UserList ulist = (UserList) tc.getProduction().getItems().get(0); tc.getContents().set(0, (Term) preferStrict(ulist.getSort(), tc.getContents().get(0))); tc.getContents().set(1, (Term) preferStrict(tc.getProduction().getSort(), tc.getContents().get(1))); } else { int j = 0; Production prd = tc.getProduction(); for (int i = 0; i < prd.getItems().size(); i++) { if (prd.getItems().get(i) instanceof Sort) { Sort sort = (Sort) prd.getItems().get(i); Term child = (Term) tc.getContents().get(j); tc.getContents().set(j, (Term) new TypeSystemFilter2(sort.getName(), context).visitNode(child)); j++; } } } return super.visit(tc, _); }</code><technical_language>this is time helper functions declared for this. Please a fourth time</technical_language>

Target:
public ASTNode visit(TermCons tc, Void _) throws ParseFailedException { if (tc.getProduction().isListDecl()) { UserList ulist = tc.getProduction().getListDecl(); tc.getContents().set(0, (Term) preferStrict(ulist.getSort(), tc.getContents().get(0))); tc.getContents().set(1, (Term) preferStrict(tc.getProduction().getSort(), tc.getContents().get(1))); } else { int j = 0; for (int i = 0; i < tc.getContents().size(); i++) { tc.getContents().set(i, (Term) new TypeSystemFilter2(tc.getProduction().getChildSort(i), context).visitNode(tc.getContents().get(i))); } } return super.visit(tc, _); }
Source:
<code>public static boolean isBeginningOfEntity(String label) { return StringUtils.startsWith(label, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.IOB_START_ENTITY_LABEL_PREFIX) <START> || StringUtil.startsWith(label, TaggingLabels.ENAMEX_START_ENTITY_LABEL_PREFIX); <END> }</code><technical_language>This method fail IOB_INSIDE_LABEL_PREFIX returning true for isBeginningOfEntity() while is beginning of entity. Problem IOB_INSIDE_LABEL_PREFIX == GROBID_START_ENTITY_LABEL_PREFIX == "I-". this method called IOB labels... 100% sure</technical_language>

Target:
public static boolean isBeginningOfEntity(String label) { return StringUtils.startsWith(label, TaggingLabels.GROBID_START_ENTITY_LABEL_PREFIX) || StringUtil.startsWith(label, TaggingLabels.ENAMEX_START_ENTITY_LABEL_PREFIX); }
Source:
<code>public Timeline getTimelineForNight(@Scope(OAuthScope.SLEEP_TIMELINE) final AccessToken accessToken, @PathParam("date") final String night) { final DateTime targetDate = DateTimeUtil.ymdStringToDateTime(night); final Optional<TimelineResult> timeline = timelineProcessor.retrieveTimelinesFast(accessToken.accountId, targetDate); if(!timeline.isPresent()) { return Timeline.createEmpty(targetDate); } if (timeline.get().logV2.isPresent()) { final TimelineLogV2 logV2 = timeline.get().logV2.get(); <START> final String partitionKey = logV2.getParitionKey(); <END> timelineLogDAOV2.putAsync(partitionKey, logV2.toProtoBuf()); timelineLogDAO.putTimelineLog(accessToken.accountId, logV2.getAsV1Log()); } final TimelineResult timelineResult = timeline.get(); return Timeline.fromV1(timelineResult.timelines.get(0), timelineResult.notEnoughData); }</code><technical_language>typo partitionKey</technical_language>

Target:
public Timeline getTimelineForNight(@Scope(OAuthScope.SLEEP_TIMELINE) final AccessToken accessToken, @PathParam("date") final String night) { final DateTime targetDate = DateTimeUtil.ymdStringToDateTime(night); final Optional<TimelineResult> timeline = timelineProcessor.retrieveTimelinesFast(accessToken.accountId, targetDate); if(!timeline.isPresent()) { return Timeline.createEmpty(targetDate); } if (timeline.get().logV2.isPresent()) { final TimelineLog logV2 = timeline.get().logV2.get(); final String partitionKey = logV2.getParitionKey(); timelineLogDAOV2.putAsync(partitionKey, logV2.toProtoBuf()); timelineLogDAO.putTimelineLog(accessToken.accountId, logV2.getAsV1Log()); } final TimelineResult timelineResult = timeline.get(); return Timeline.fromV1(timelineResult.timelines.get(0), timelineResult.notEnoughData); }
Source:
<code>public void onAttachOrDetach(AttachEvent event) { if (!event.isAttached()) { handlers_.removeHandler(); if (documentChangedHandler_ != null) { documentChangedHandler_.removeHandler(); documentChangedHandler_ = null; } } else { <START> handlers_ = new HandlerRegistrations( <END> editor_.addEditorModeChangedHandler(this), editor_.addAttachHandler(this)); if (!highlightPatterns_.isEmpty()) { documentChangedHandler_ = editor_.addDocumentChangedHandler(this); synchronizeFrom(0); } } }</code><technical_language>remove existing handlers well, in case? (Since do initialize handlers in constructor here: <LINK_0> Or, remove initialization init in attach / detach currently things</technical_language>

Target:
public void onAttachOrDetach(AttachEvent event) { handlers_.removeHandler(); if (!event.isAttached()) { if (documentChangedHandler_ != null) { documentChangedHandler_.removeHandler(); documentChangedHandler_ = null; } } else { handlers_ = new HandlerRegistrations( editor_.addEditorModeChangedHandler(this), editor_.addAttachHandler(this)); if (!highlightPatterns_.isEmpty()) { documentChangedHandler_ = editor_.addDocumentChangedHandler(this); synchronizeFrom(0); } } }
Source:
<code>public Object execute(ApiDefinition apiDefinition, String objectId, ParamsMap paramsMap) throws MambuApiException { if (apiDefinition == null) { throw new IllegalArgumentException("ApiDefinition cannot be NULL"); } <START> String urlString = makeUrl(apiDefinition, objectId); <END> if (apiDefinition.getWithFullDetails()) { if (paramsMap == null) { paramsMap = new ParamsMap(); } paramsMap.put(APIData.FULL_DETAILS, "true"); } Method method = apiDefinition.getMethod(); ContentType contentType = apiDefinition.getContentType(); String jsonResponse = mambuAPIService.executeRequest(urlString, paramsMap, method, contentType); Class<?> returnClass = apiDefinition.getReturnClass(); ApiReturnFormat returnFormat = apiDefinition.getApiReturnFormat(); Object result = null; switch (returnFormat) { case OBJECT: result = getObject(jsonResponse, returnClass); break; case COLLECTION: Type collectionType = getCollectionType(returnClass); result = getCollection(jsonResponse, collectionType); break; case BOOLEAN: result = getBoolean(jsonResponse); break; case RESPONSE_STRING: result = jsonResponse; break; } return result; }</code><technical_language>Please rename variable "path" "apiPath"</technical_language>

Target:
public <R> R execute(ApiDefinition apiDefinition, String objectId, ParamsMap paramsMap) throws MambuApiException { if (apiDefinition == null) { throw new IllegalArgumentException("ApiDefinition cannot be NULL"); } String apiUrlPath = getApiPath(apiDefinition, objectId); if (apiDefinition.getWithFullDetails()) { if (paramsMap == null) { paramsMap = new ParamsMap(); } paramsMap.put(APIData.FULL_DETAILS, "true"); } Method method = apiDefinition.getMethod(); ContentType contentType = apiDefinition.getContentType(); String jsonResponse = mambuAPIService.executeRequest(apiUrlPath, paramsMap, method, contentType); Class<?> returnClass = apiDefinition.getReturnClass(); ApiReturnFormat returnFormat = apiDefinition.getApiReturnFormat(); R result = null; switch (returnFormat) { case OBJECT: result = getObject(jsonResponse, returnClass); break; case COLLECTION: Type collectionType = getCollectionType(returnClass); result = getCollection(jsonResponse, collectionType); break; case BOOLEAN: result = (R) getBoolean(jsonResponse); break; case RESPONSE_STRING: result = (R) jsonResponse; break; } return result; }
Source:
<code>private void addAuthorizedAddress(SocketAddress address) { synchronized (authorizedAddressesSyncRoot) { if (authorizedAddresses.contains(address)) { return; } logger.info("Adding allowed address: " + address); Set<SocketAddress> newSet = Collections.newSetFromMap( new ConcurrentHashMap<SocketAddress, Boolean>()); newSet.addAll(authorizedAddresses); <START> newSet.add(address); <END> authorizedAddresses = newSet; } }</code><technical_language>a java missing...but add new address set directly? break 'accept' method, missing something</technical_language>

Target:
private void addAuthorizedAddress(SocketAddress address) { synchronized (authorizedAddressesSyncRoot) { if (authorizedAddresses.contains(address)) { return; } logger.info("Adding allowed address: " + address); Set<SocketAddress> newSet = new HashSet<>(); newSet.addAll(authorizedAddresses); newSet.add(address); authorizedAddresses = newSet; } }
Source:
<code>public <T> T parseProcessed(final Class<T> type) throws LightblueResponseParseException { if (hasError()) { throw new LightblueErrorResponseException("Error returned in response: " + getText()); } try { JsonNode errorCode = json.path("errorCode"); if (errorCode != null && !errorCode.isNull() && !errorCode.isMissingNode()){ throw new LightblueResponseParseException("Error parsing lightblue response: Error returned. JSON returned:" + json.toString() + "\n"); } <START> <END> JsonNode processedNode = json.path("processed"); if (processedNode == null || processedNode.isNull() || processedNode.isMissingNode() || (processedNode.isArray() && !((ArrayNode) processedNode).iterator().hasNext())) { if (type.isArray()) { return (T) Array.newInstance(type.getComponentType(), 0); } return null; } return mapper.readValue(processedNode.traverse(), type); } catch (RuntimeException | IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + getText() + "\n", e); } }</code><technical_language>is this different, included in hasError</technical_language>

Target:
public <T> T parseProcessed(final Class<T> type) throws LightblueResponseParseException { if (hasError()){ throw new LightblueErrorResponseException("Error parsing lightblue response: Error returned. JSON returned:" + json.toString() + "\n"); } try { JsonNode processedNode = json.path("processed"); if (processedNode == null || processedNode.isNull() || processedNode.isMissingNode() || (processedNode.isArray() && !((ArrayNode) processedNode).iterator().hasNext())) { if (type.isArray()) { return (T) Array.newInstance(type.getComponentType(), 0); } return null; } return mapper.readValue(processedNode.traverse(), type); } catch (RuntimeException | IOException e) { throw new LightblueResponseParseException("Error parsing lightblue response: " + json.toString() + "\n", e); } }
Source:
<code>public ListenableFuture<List<ChunkInfo>> commit() { checkState(!committed, "already committed"); committed = true; flush(); return whenAllComplete(futures).call(() -> { for (ChunkInfo chunk : chunks) { writeChunk(chunk.getChunkId()); <START> } <END> return ImmutableList.copyOf(chunks); }, commitExecutor); }</code><technical_language>I observe this error raptor-dev: com.facebook.presto.spi.PrestoException: Failed move chunk file com.facebook.presto.raptorx.storage.OrcStorageManager.writeChunk(OrcStorageManager.java:325) Caused by: java.nio.file.NoSuchFileException: /raptor/staging/635606 -> /raptor/storage/1c/25/635606 I guessing time series: transaction1 calls OrcStoragePageSink.commit(), fill futures, runs async; Some logic calls OrcStoragePageSink.rollback(), stagingFile.delete() done; futures finished calls writeChunk(), Files.move(staging, storage); throw exception If is due intentional killing, human user kills, system killing for resource management, fine, transaction's data is way. I familiar calling paths, need confirm you. if intentional killing, consider output accurate error message, transaction is killed, "com.facebook.presto.spi.PrestoException: Failed move chunk file; chunkXXX in transactionYYY, transaction aborted user" "chunkXXX in transactionYYY, transaction killed ResourceManager"</technical_language>

Target:
public ListenableFuture<List<ChunkInfo>> commit() { checkState(!committed, "already committed"); committed = true; flush(); return whenAllSucceed(chunkStoreJobs).call(() -> { for (ChunkInfo chunk : chunks) { writeChunk(chunk.getChunkId()); } return ImmutableList.copyOf(chunks); }, commitExecutor); }
Source:
<code>private static void extractNamespaces(RouteDefinition route, Map<String, String> namespaces) { Iterator<ExpressionNode> it = filterTypeInOutputs(route.getOutputs(), ExpressionNode.class); while (it.hasNext()) { ExpressionNode en = it.next(); ExpressionDefinition ed = en.getExpression(); <START> NamespaceAware na = null; <END> Expression exp = ed.getExpressionValue(); if (exp != null && exp instanceof NamespaceAware) { na = (NamespaceAware) exp; } else if (ed instanceof NamespaceAware) { na = (NamespaceAware) ed; } if (na != null) { Map<String, String> map = na.getNamespaces(); if (map != null && !map.isEmpty()) { namespaces.putAll(map); } } } }</code><technical_language>duplicated code l.242-248</technical_language>

Target:
private static void extractNamespaces(RouteDefinition route, Map<String, String> namespaces) { Iterator<ExpressionNode> it = filterTypeInOutputs(route.getOutputs(), ExpressionNode.class); while (it.hasNext()) { NamespaceAware na = getNamespaceAwareFromExpression(it.next()); if (na != null) { Map<String, String> map = na.getNamespaces(); if (map != null && !map.isEmpty()) { namespaces.putAll(map); } } } }
Source:
<code>public void testExecuteQueryCommand() { GetDiskImageByDiskAndImageIdsParameters params = getQueryParameters(); when(params.getDiskId()).thenReturn(diskId); when(params.getImageId()).thenReturn(imageId); when(diskImageDao.getDiskImageByDiskAndImageIds(diskId, imageId)).thenReturn(diskImage); GetDiskImageByDiskAndImageIdsQuery<GetDiskImageByDiskAndImageIdsParameters> query = getQuery(); query.executeQueryCommand(); DiskImage returnDiskImage = query.getQueryReturnValue().getReturnValue(); <START> assertTrue(returnDiskImage.equals(diskImage)); <END> }</code><technical_language>reinvent wheel, assertEquals instead</technical_language>

Target:
public void testExecuteQueryCommand() { GetDiskImageByDiskAndImageIdsParameters params = getQueryParameters(); when(params.getDiskId()).thenReturn(diskId); when(params.getImageId()).thenReturn(imageId); when(diskImageDao.getDiskImageByDiskAndImageIds(diskId, imageId)).thenReturn(diskImage); GetDiskImageByDiskAndImageIdsQuery<GetDiskImageByDiskAndImageIdsParameters> query = getQuery(); query.executeQueryCommand(); DiskImage returnDiskImage = query.getQueryReturnValue().getReturnValue(); assertEquals(returnDiskImage, diskImage); }
Source:
<code>public ValidationResult memoryOptimizationConfiguration(){ return <START> ValidationResult.failWith(EngineMessage.CLUSTER_TO_ALLOW_MEMORY_OPTIMIZATION_YOU_MUST_ALLOW_KSM_AND_BALLOONING) <END> .when((cluster.getMaxVdsMemoryOverCommit() > 100 || cluster.getMaxVdsMemoryOverCommit() <=0) && !(cluster.isEnableKsm() || cluster.isEnableBallooning())); }</code><technical_language>ksm ballooning => is enough for allow commitment</technical_language>

Target:
public ValidationResult memoryOptimizationConfiguration(){ return ValidationResult.failWith(EngineMessage.CLUSTER_TO_ALLOW_MEMORY_OPTIMIZATION_YOU_MUST_ALLOW_KSM_OR_BALLOONING) .when((cluster.getMaxVdsMemoryOverCommit() > 100 || cluster.getMaxVdsMemoryOverCommit() <=0) && !(cluster.isEnableKsm() || cluster.isEnableBallooning())); }
Source:
<code>private static BackgroundHiveSplitLoader backgroundHiveSplitLoader( List<LocatedFileStatus> files, TupleDomain<HiveColumnHandle> compactEffectivePredicate, Optional<HiveBucketFilter> hiveBucketFilter, Table table, Optional<HiveBucketHandle> bucketHandle) { List<HivePartitionMetadata> hivePartitionMetadatas = ImmutableList.of( new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name")), Optional.empty(), <START> ImmutableMap.of(), false)); <END> ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties(new HiveClientConfig().setMaxSplitSize(new DataSize(1.0, GIGABYTE)), new OrcFileWriterConfig()).getSessionProperties()); return new BackgroundHiveSplitLoader( table, hivePartitionMetadatas, compactEffectivePredicate, createBucketSplitInfo(bucketHandle, hiveBucketFilter), connectorSession, new TestingHdfsEnvironment(), new NamenodeStats(), new TestingDirectoryLister(files), EXECUTOR, 2, false); }</code><technical_language>This next line</technical_language>

Target:
private static BackgroundHiveSplitLoader backgroundHiveSplitLoader( List<LocatedFileStatus> files, TupleDomain<HiveColumnHandle> compactEffectivePredicate, Optional<HiveBucketFilter> hiveBucketFilter, Table table, Optional<HiveBucketHandle> bucketHandle) { List<HivePartitionMetadata> hivePartitionMetadatas = ImmutableList.of( new HivePartitionMetadata( new HivePartition(new SchemaTableName("testSchema", "table_name")), Optional.empty(), ImmutableMap.of(), false)); ConnectorSession connectorSession = new TestingConnectorSession( new HiveSessionProperties(new HiveClientConfig().setMaxSplitSize(new DataSize(1.0, GIGABYTE)), new OrcFileWriterConfig(), new ParquetFileWriterConfig()).getSessionProperties()); return new BackgroundHiveSplitLoader( table, hivePartitionMetadatas, compactEffectivePredicate, createBucketSplitInfo(bucketHandle, hiveBucketFilter), connectorSession, new TestingHdfsEnvironment(), new NamenodeStats(), new TestingDirectoryLister(files), EXECUTOR, 2, false); }
Source:
<code>public void run() { long iteration = 0; long count = 0; while (!testContext.isStopped()) { sleepRandom(random, maxPublicationDelayNanos); int index = random.nextInt(topics.length); <START> ITopic topic = topics[index]; <END> long msg = nextMessage(); count += msg; topic.publish(msg); if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } iteration++; } for (ITopic topic : topics) { topic.publish(-1l); } totalExpectedCounter.addAndGet(count); }</code><technical_language>introduce a new method - getRandomTopic() - encapsulate logic main Worker flow more readable</technical_language>

Target:
public void run() { long iteration = 0; long count = 0; while (!testContext.isStopped()) { sleepRandomNanos(random, maxPublicationDelayNanos); ITopic topic = getRandomTopic(); long msg = nextMessage(); count += msg; topic.publish(msg); if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } iteration++; } totalExpectedCounter.addAndGet(count); }
Source:
<code>private void createFloatAccessor() { accessors.put(Float.class, new Accessor<Float>() { @Override public Float get(String key, Float defaultValue) { <START> return preferences.getFloat(key, (defaultValue == null) ? 0f : defaultValue); <END> } @Override public void put(String key, Float value) { editor.putFloat(key, value).apply(); } }); }</code><technical_language>issue above</technical_language>

Target:
private void createFloatAccessor() { accessors.put(Float.class, new Accessor<Float>() { @Override public Float get(String key) { return preferences.getFloat(key, 0f); } @Override public void put(String key, Float value) { editor.putFloat(key, value).apply(); } }); }
Source:
<code>public void testFilterWithString() { mockFilterObserver.setName("St"); <START> assert mockFilterObserver.getFilteredInstalledApplications().size() == 1; <END> }</code><technical_language>JUnit assertEquals please</technical_language>

Target:
public void testFilterWithString() { mockFilterObserver.setName("St"); assertEquals(1, mockFilterObserver.getFilteredInstalledApplications().size()); }
Source:
<code>public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { <START> if (eObject instanceof PatternModel) { <END> } else if (eObject instanceof Pattern) { QualifiedName qualifiedName = getQualifiedNameProvider().getFullyQualifiedName(eObject); if (qualifiedName != null) { acceptor.accept(EObjectDescription.create(qualifiedName, eObject, getUserData((Pattern) eObject))); } return false; } return super.createEObjectDescriptions(eObject, acceptor); }</code><technical_language>This empty if block redundant</technical_language>

Target:
public boolean createEObjectDescriptions(EObject eObject, IAcceptor<IEObjectDescription> acceptor) { if (eObject instanceof Pattern) { QualifiedName qualifiedName = getQualifiedNameProvider().getFullyQualifiedName(eObject); if (qualifiedName != null) { acceptor.accept(EObjectDescription.create(qualifiedName, eObject, getUserData((Pattern) eObject))); } return false; } return super.createEObjectDescriptions(eObject, acceptor); }
Source:
<code>private static void copySenderMessages(ExecutionCourse executionCourseFrom, ExecutionCourse executionCourseTo) { if (executionCourseFrom.getSender() != null) { ExecutionCourseSender courseSenderTo = ExecutionCourseSender.newInstance(executionCourseTo); courseSenderTo.getMessagesSet().addAll(executionCourseFrom.getSender().getMessagesSet()); <START> executionCourseFrom.getSender().delete(); <END> } }</code><technical_language>code in Recipient's delete method, message it, deleted. this dissociate messages recipients, deleted</technical_language>

Target:
private static void copySenderMessages(ExecutionCourse executionCourseFrom, ExecutionCourse executionCourseTo) { if (executionCourseFrom.getSender() != null) { ExecutionCourseSender courseSenderTo = ExecutionCourseSender.newInstance(executionCourseTo); courseSenderTo.getMessagesSet().addAll(executionCourseFrom.getSender().getMessagesSet()); executionCourseFrom.getSender().getMessagesSet().stream().forEach(m -> m.getRecipientsSet().clear()); executionCourseFrom.getSender().delete(); } }
Source:
<code>private void handleException(Exception e, HttpServletResponse resp) throws IOException { if (e instanceof InvalidRequestException || e instanceof CodecException) { LOG.warn("Invalid request", e); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().append("Invalid request:").append(e.getMessage()).flush(); } else if (e instanceof RequestRejectedException) { LOG.warn("Request rejected", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Request rejected:").append(e.getMessage()).flush(); } else if (e instanceof RequestCanceledException) { LOG.warn("Request cancelled", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Request cancelled:").append(e.getMessage()).flush(); } else if (e instanceof InvalidResponseException) { LOG.warn("Invalid response", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Invalid Response:").append(e.getMessage()).flush(); } else if (e instanceof InterruptedException) { LOG.warn("Thread Interrupted", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Thread Interrupted:").append(e.getMessage()).flush(); } else if (e instanceof ClientSleepingException) { LOG.warn("Client is sleeping", e); <START> resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); <END> resp.getWriter().append("Client is sleeping:").append(e.getMessage()).flush(); } else { LOG.warn("Unexpected exception", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Unexpected exception:").append(e.getMessage()).flush(); } }</code><technical_language>bad request</technical_language>

Target:
private void handleException(Exception e, HttpServletResponse resp) throws IOException { if (e instanceof InvalidRequestException || e instanceof CodecException || e instanceof ClientSleepingException) { LOG.warn("Invalid request", e); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); resp.getWriter().append("Invalid request:").append(e.getMessage()).flush(); } else if (e instanceof RequestRejectedException) { LOG.warn("Request rejected", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Request rejected:").append(e.getMessage()).flush(); } else if (e instanceof RequestCanceledException) { LOG.warn("Request cancelled", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Request cancelled:").append(e.getMessage()).flush(); } else if (e instanceof InvalidResponseException) { LOG.warn("Invalid response", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Invalid Response:").append(e.getMessage()).flush(); } else if (e instanceof InterruptedException) { LOG.warn("Thread Interrupted", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Thread Interrupted:").append(e.getMessage()).flush(); } else { LOG.warn("Unexpected exception", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); resp.getWriter().append("Unexpected exception:").append(e.getMessage()).flush(); } }
Source:
<code>private ProgramEnrollmentListResult prepareProgramEnrollmentListResult(List<ProgramEnrollment> programEnrollments, Map<String, String> lookupFields) { ProgramEnrollmentListResult result = new ProgramEnrollmentListResult(); String programName = lookupFields.get(PROGRAM_NAME); <START> String patientUuid = lookupFields.get(PATIENT_UUID); <END> result.setResults(filterPrograms(programEnrollments, programName, lookupFields.get(ACTIVE_PROGRAM))); if (result.getNumberOfPrograms() > 1) { LOGGER.warn(String.format("Multiple program enrollment found with the patient UUID \"%s\" and program name" + " \"%s\".", patientUuid, programName)); } return result; }</code><technical_language>If user choose lookup 'MOTECH ID' field, 'PATIENT_UUID' empty</technical_language>

Target:
private ProgramEnrollmentListResult prepareProgramEnrollmentListResult(List<ProgramEnrollment> programEnrollments, Map<String, String> lookupFields) { ProgramEnrollmentListResult result = new ProgramEnrollmentListResult(); String programName = lookupFields.get(PROGRAM_NAME); result.setResults(filterPrograms(programEnrollments, programName, lookupFields.get(ACTIVE_PROGRAM))); return result; }
Source:
<code>byte[] readEntryFromStream(JarInputStream jarIn) throws IOException { int totalRead = 0; while (jarIn.available() == 1) { int bytesToRead = m_array.length - totalRead; assert (bytesToRead > 0); int readSize = jarIn.read(m_array, totalRead, bytesToRead); <START> if (readSize < 0) { <END> break; } totalRead += readSize; if (readSize == bytesToRead && (jarIn.available() == 1)) { byte[] tmpArray = new byte[2 * m_array.length]; System.arraycopy(m_array, 0, tmpArray, 0, totalRead); m_array = tmpArray; } } byte trimmedBytes[] = new byte[totalRead]; System.arraycopy(m_array, 0, trimmedBytes, 0, totalRead); return trimmedBytes; }</code><technical_language><= ? I if readSize == 0 is a possibility, changed (complicated) handling vs. original code</technical_language>

Target:
byte[] readEntryFromStream(JarInputStream jarIn) throws IOException { int totalRead = 0; while (jarIn.available() == 1) { int bytesToRead = m_array.length - totalRead; assert (bytesToRead > 0); int readSize = jarIn.read(m_array, totalRead, bytesToRead); if (readSize > 0) { totalRead += readSize; if (readSize == bytesToRead && (jarIn.available() == 1)) { byte[] tmpArray = new byte[2 * m_array.length]; System.arraycopy(m_array, 0, tmpArray, 0, totalRead); m_array = tmpArray; } } } byte trimmedBytes[] = new byte[totalRead]; System.arraycopy(m_array, 0, trimmedBytes, 0, totalRead); return trimmedBytes; }