auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Map<String, Pair<String, String>> getSharedLocksForTemplateDisk() { <START> initVmTemplateId(); <END> return Collections.singletonMap(getVmTemplateId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.VM_TEMPLATE_IS_LOCKED)); }</code><technical_language>is a bit unusual init in getSharedLocks flow.. moving 'init' method? (need check VmEntityType there..)</technical_language>

Target:
private Map<String, Pair<String, String>> getSharedLocksForTemplateDisk() { return Collections.singletonMap(getVmTemplateId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.VM_TEMPLATE_IS_LOCKED)); }
Source:
<code>public boolean step(IPointable result, IFrameWriter writer, int tupleIndex) throws AlgebricksException { if (indexPlace < indexLength) { nodeAbvs.reset(); try { doc = searcher.doc(hits[indexPlace].doc); <START> fields = doc.getFields(); <END> handler.setupElementWriter(writer, tupleIndex); parse(nodeAbvs); } catch (IOException e) { throw new AlgebricksException(e); } indexPlace += 1; result.set(nodeAbvs.getByteArray(), nodeAbvs.getStartOffset(), nodeAbvs.getLength()); return true; } return false; }</code><technical_language>is meaning of "+-" end of line</technical_language>

Target:
public boolean step(IPointable result, IFrameWriter writer, int tupleIndex) throws AlgebricksException { if (indexPlace < indexLength) { nodeAbvs.reset(); try { doc = searcher.doc(hits[indexPlace].doc); fields = doc.getFields(); handler.setupElementWriter(writer, tupleIndex); this.firstElement = true; parse(nodeAbvs); } catch (IOException e) { throw new AlgebricksException(e); } indexPlace += 1; result.set(nodeAbvs.getByteArray(), nodeAbvs.getStartOffset(), nodeAbvs.getLength()); return true; } return false; }
Source:
<code>public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); adapter = new ExchangeRatesAdapter(); adapter.setRateBase(config.getBtcBase()); adapter.setDefaultCurrency(config.getExchangeCurrencyCode()); exchangeRatesViewModel = ViewModelProviders.of(this) .get(ExchangeRatesViewModel.class); exchangeRatesViewModel.isLoading().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean isLoading) { loading.setVisibility(Boolean.TRUE.equals(isLoading) ? View.VISIBLE : View.GONE); } }); exchangeRatesViewModel.hasError().observe(this, new Observer<Boolean>() { @Override public void onChanged(@android.support.annotation.Nullable Boolean aBoolean) { <START> if (Boolean.TRUE.equals(true)) { <END> showOnly(loadingErrorView); } } }); exchangeRatesViewModel.getRates().observe(this, new Observer<List<de.schildbach.wallet.rates.ExchangeRate>>() { @Override public void onChanged(List<de.schildbach.wallet.rates.ExchangeRate> exchangeRates) { updateView(exchangeRates); } }); config.registerOnSharedPreferenceChangeListener(this); }</code><technical_language>@sambarboza aBoolean instead of Boolean (or Boolean.TRUE.equals(aBoolean)). good change name of this variable more accurate</technical_language>

Target:
public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); adapter = new ExchangeRatesAdapter(); adapter.setRateBase(config.getBtcBase()); adapter.setDefaultCurrency(config.getExchangeCurrencyCode()); exchangeRatesViewModel = ViewModelProviders.of(this) .get(ExchangeRatesViewModel.class); exchangeRatesViewModel.isLoading().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean isLoading) { loading.setVisibility(Boolean.TRUE.equals(isLoading) ? View.VISIBLE : View.GONE); } }); exchangeRatesViewModel.hasError().observe(this, new Observer<Boolean>() { @Override public void onChanged(Boolean hasError) { if (Boolean.TRUE.equals(hasError)) { showOnly(loadingErrorView); } } }); exchangeRatesViewModel.getRates().observe(this, new Observer<List<de.schildbach.wallet.rates.ExchangeRate>>() { @Override public void onChanged(List<de.schildbach.wallet.rates.ExchangeRate> exchangeRates) { updateView(exchangeRates); } }); config.registerOnSharedPreferenceChangeListener(this); }
Source:
<code>protected void setResult(ISelection selection, Class<T> target) { <START> List<T> selected = Collections.emptyList(); <END> if (selection instanceof IStructuredSelection && target != null) { IStructuredSelection structured = (IStructuredSelection) selection; selected = ((List<?>) structured.toList()).stream().filter(p -> target.isInstance(p)) .map(p -> target.cast(p)).collect(Collectors.toList()); } setResult(selected); }</code><technical_language>List<T> selected = null; enough</technical_language>

Target:
protected void setResult(ISelection selection, Class<T> target) { List<T> selected = null; if (selection instanceof IStructuredSelection && target != null) { IStructuredSelection structured = (IStructuredSelection) selection; selected = ((List<?>) structured.toList()).stream().filter(p -> target.isInstance(p)) .map(p -> target.cast(p)).collect(Collectors.toList()); } setResult(selected); }
Source:
<code>public String getIP() { <START> return "10.241.100.159"; <END> }</code><technical_language>prob a hardcodded IP here. default 'localhost' provide a mechanism configure this value</technical_language>

Target:
public String getIP() { return ""; }
Source:
<code>public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getTemplatePage().countListedTemplates(); <START> Thread.sleep(50000); <END> Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }</code><technical_language>need this test need a high timeout value</technical_language>

Target:
public void listTemplatesTest() throws Exception { Pages.getProjectsPage().goTo(); int numberOfTemplatesInDatabase = serviceManager.getTemplateService().getActiveTemplates().size(); int numberOfTemplatesDisplayed = Pages.getProjectsPage().countListedTemplates(); Assert.assertEquals("Displayed wrong number of templates", numberOfTemplatesInDatabase, numberOfTemplatesDisplayed); }
Source:
<code>private String extractSubject(HttpSession httpSession) { return Stream.of(httpSession.getAttribute(SecurityConstants.SAML_ASSERTION)) .map(SecurityTokenHolder.class::cast) <START> .map(SecurityTokenHolder::getRealmTokenMap) <END> .map(Map::values) .flatMap(Collection::stream) .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }</code><technical_language>Do want filter isInstance first? (even protect wierd bundle reloading errors?)</technical_language>

Target:
private String extractSubject(HttpSession httpSession) { return Stream.of(httpSession.getAttribute(SecurityConstants.SAML_ASSERTION)) .filter(SecurityTokenHolder.class::isInstance) .map(SecurityTokenHolder.class::cast) .map(SecurityTokenHolder::getRealmTokenMap) .map(Map::values) .flatMap(Collection::stream) .map(this::extractSubject) .filter(Objects::nonNull) .map(SubjectUtils::getName) .findFirst() .orElse(null); }
Source:
<code>public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertSecretName = identity.getWorkspaceId() + CHE_SELF_SIGNED_CERT_SECRET_SUFFIX; k8sEnv .getSecrets() .put( selfSignedCertSecretName, new SecretBuilder() .withNewMetadata() .withName(selfSignedCertSecretName) .endMetadata() .withStringData(ImmutableMap.of(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { <START> if (pod.getRole() == PodRole.DEPLOYMENT) { <END> Optional<Volume> certVolume = pod.getSpec() .getVolumes() .stream() .filter(v -> v.getName().equals(CHE_SELF_SIGNED_CERT_VOLUME)) .findAny(); if (!certVolume.isPresent()) { pod.getSpec().getVolumes().add(buildCertSecretVolume(selfSignedCertSecretName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }</code><technical_language>I this is equivalent, shorter simpler if (pod.getSpec().getVolumes().stream() .noneMatch(v -> v.getName().equals(CHE_SELF_SIGNED_CERT_VOLUME))) { pod.getSpec().getVolumes().add(buildCertSecretVolume(selfSignedCertSecretName)); }</technical_language>

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { if (!isConfigured()) { return; } String selfSignedCertSecretName = identity.getWorkspaceId() + CHE_SELF_SIGNED_CERT_SECRET_SUFFIX; k8sEnv .getSecrets() .put( selfSignedCertSecretName, new SecretBuilder() .withNewMetadata() .withName(selfSignedCertSecretName) .endMetadata() .withStringData(ImmutableMap.of(CA_CERT_FILE, certificate)) .build()); for (PodData pod : k8sEnv.getPodsData().values()) { if (pod.getRole() == PodRole.DEPLOYMENT) { if (pod.getSpec() .getVolumes() .stream() .noneMatch(v -> v.getName().equals(CHE_SELF_SIGNED_CERT_VOLUME))) { pod.getSpec().getVolumes().add(buildCertSecretVolume(selfSignedCertSecretName)); } } for (Container container : pod.getSpec().getInitContainers()) { provisionCertVolumeMountIfNeeded(container); } for (Container container : pod.getSpec().getContainers()) { provisionCertVolumeMountIfNeeded(container); } } }
Source:
<code>private List<String> readCategory(VEvent vEvent) { PropertyList propertyCategoryList = vEvent.getProperties(Property.CATEGORIES); ArrayList<String> splittedCategoriesToReturn = new ArrayList<String>(); if (propertyCategoryList != null) { <START> for (int categorieslinenum = 0; categorieslinenum < propertyCategoryList.size(); categorieslinenum++) { <END> Property propertyCategory = propertyCategoryList.get(categorieslinenum); String categories = propertyCategory.getValue(); if (categories != null) { String[] categoriesSplit = StringUtils.split(categories, ","); for (String macategorie : categoriesSplit) { if (!splittedCategoriesToReturn.contains(macategorie)) { splittedCategoriesToReturn.add(macategorie); } } } } } return splittedCategoriesToReturn; }</code><technical_language>Please camelCase variable names, categoriesLineNum</technical_language>

Target:
private List<String> readCategory(VEvent vEvent) { PropertyList propertyCategoryList = vEvent.getProperties(Property.CATEGORIES); ArrayList<String> splittedCategoriesToReturn = new ArrayList<String>(); if (propertyCategoryList != null) { for (int categoriesLineNum = 0; categoriesLineNum < propertyCategoryList.size(); categoriesLineNum++) { Property propertyCategory = propertyCategoryList.get(categoriesLineNum); String categories = propertyCategory.getValue(); if (categories != null) { String[] categoriesSplit = StringUtils.split(categories, ","); for (String category : categoriesSplit) { if (!splittedCategoriesToReturn.contains(category)) { splittedCategoriesToReturn.add(category); } } } } } return splittedCategoriesToReturn; }
Source:
<code>public void handlePost(ActionParameters params) throws ActionException { <START> checkForAdminPermission(params); <END> log.debug("Updating layer/group order"); JSONObject orderJSON = getOrderJSON(params.getRequest()); try { int parentID = orderJSON.getInt(KEY_PARENT); JSONArray orders = orderJSON.getJSONArray(KEY_ORDERS); if(parentID == -1){ for(int i=0;i<orders.length();i++){ JSONObject order = orders.getJSONObject(i); int groupId = order.getInt(KEY_ID); MaplayerGroup currentGroup = oskariMapLayerGroupService.find(groupId); currentGroup.setOrderNumber(i); oskariMapLayerGroupService.updateOrder(currentGroup); } } else { for(int i=0;i<orders.length();i++) { JSONObject order = orders.getJSONObject(i); String type = order.getString(KEY_TYPE); int id = order.getInt(KEY_ID); if(TYPE_LAYER.equals(type)) { if(order.has(KEY_OLD_PARENT)) { oskariLayerService.updateGroup(id, order.getInt(KEY_OLD_PARENT), parentID); } oskariLayerService.updateOrder(id, parentID, i); } else { MaplayerGroup currentGroup = oskariMapLayerGroupService.find(id); currentGroup.setOrderNumber(i); oskariMapLayerGroupService.updateOrder(currentGroup); if(order.has(KEY_OLD_PARENT)){ oskariMapLayerGroupService.updateGroupParent(id,parentID); } } } } } catch (JSONException e) { log.warn(e); throw new ActionException("Failed to read request!"); } ResponseHelper.writeResponse(params, orderJSON); }</code><technical_language>Admin check done params.requireAdminUser();</technical_language>

Target:
public void handlePost(ActionParameters params) throws ActionException { params.requireAdminUser(); log.debug("Updating layer/group order"); JSONObject orderJSON = params.getPayLoadJSON(); try { int parentID = orderJSON.getInt(KEY_PARENT); JSONArray orders = orderJSON.getJSONArray(KEY_ORDERS); if (parentID == -1) { updateGroupOrder(orders); } else { updateLayerAndGroupOrders(orders, parentID); } } catch (JSONException e) { log.warn(e); throw new ActionParamsException("Cannot save orders!"); } }
Source:
<code>void connectFails() { webSocketConnection.setClient( <START> new WebSocketClient(URI.create("wss://server.invalid")) { <END> @Override public void onOpen(final ServerHandshake handshake) @Override public void onMessage(final String message) @Override public void onClose(final int code, final String reason, final boolean remote) @Override public void onError(final Exception ex) }); assertThrows(RuntimeException.class, webSocketConnection::connect); }</code><technical_language>Thanks for checking, considered trade-off of toggling timeout short, 5ms</technical_language>

Target:
void connectFails() throws Exception { doCallRealMethod().when(webSocketClient).connectBlocking(anyLong(), any()); doCallRealMethod().when(webSocketClient).connect(); doCallRealMethod().when(webSocketClient).run(); final SocketFactory factory = mock(SocketFactory.class); when(factory.createSocket()).thenThrow(new IOException("Test Connection Failure")); doCallRealMethod().when(webSocketClient).setSocketFactory(any()); webSocketClient.setSocketFactory(factory); assertThrows(CouldNotConnect.class, webSocketConnection::connect); verify(webSocketClient).onError(any()); }
Source:
<code>public void testAccessingValuesUsingDecoder() throws Exception { FieldAccessor accessor = new FieldAccessor(); accessor.registerDecoder("TargetValue", new OafFieldDecoder()); String rawSetId = "rawset-id"; String agentId = "agent-id"; String agentName = "agent-name"; AtomicAction action = new AtomicAction(rawSetId, new Agent(agentId, agentName, Agent.AGENT_TYPE.service)); byte[] decodedTargetValue = decodeTargetValue(new String(IOUtils.readBytesFromStream(FieldAccessorTest.class .getResourceAsStream("/eu/dnetlib/iis/wf/export/actionmanager/sequencefile/resultProject.json")), "utf8")); action.setTargetValue(decodedTargetValue); assertEquals(rawSetId, accessor.getValue("RawSet", action).toString()); assertEquals(agentId, accessor.getValue("Agent.Id", action).toString()); assertEquals(agentName, accessor.getValue("Agent.Name", action).toString()); assertEquals(Agent.AGENT_TYPE.service.toString(), accessor.getValue("Agent.Type", action).toString()); assertEquals("relation", accessor.getValue("$TargetValue.Kind", action).toString()); <START> assertEquals("resultProject", accessor.getValue("$TargetValue.Rel.RelType", action).toString()); <END> }</code><technical_language>of toStrings unnecessary, I think</technical_language>

Target:
public void testAccessingValuesUsingDecoder() throws Exception { FieldAccessor accessor = new FieldAccessor(); accessor.registerDecoder("targetValue", new OafFieldDecoder()); String rawSetId = "rawset-id"; String agentId = "agent-id"; String agentName = "agent-name"; AtomicAction action = new AtomicAction(rawSetId, new Agent(agentId, agentName, Agent.AGENT_TYPE.service)); byte[] decodedTargetValue = decodeTargetValue(new String( IOUtils.toByteArray(FieldAccessorTest.class .getResourceAsStream("/eu/dnetlib/iis/wf/export/actionmanager/sequencefile/resultProject.json")), "utf8")); action.setTargetValue(decodedTargetValue); assertEquals(rawSetId, accessor.getValue("rawSet", action)); assertEquals(agentId, accessor.getValue("agent.id", action)); assertEquals(agentName, accessor.getValue("agent.name", action)); assertEquals(Agent.AGENT_TYPE.service, accessor.getValue("agent.type", action)); assertEquals("relation", accessor.getValue("$targetValue.kind", action).toString()); assertEquals("resultProject", accessor.getValue("$targetValue.rel.relType", action).toString()); }
Source:
<code>public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { <START> return new CheckColumnConstraint(name, columnName, expression, expressionStr); <END> }</code><technical_language>suggestion return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); Please care of generic warnings. ignore</technical_language>

Target:
public <U> ColumnConstraint<U> map(Function<? super T, ? extends U> mapper) { return new CheckColumnConstraint<>(name, columnName, mapper.apply(expression), expressionStr); }
Source:
<code>public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { AccurevServer server = getServer(); boolean serverDisabled = server != null && server.isServerDisabled(); if (!serverDisabled) { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); } else { <START> listener.getLogger().println("Checkout skipped"); <END> } }</code><technical_language>This work... breaking builds proper checkout. Please throw AbortException</technical_language>

Target:
public void checkout(@Nonnull Run<?, ?> build, @Nonnull Launcher launcher, @Nonnull FilePath workspace, @Nonnull TaskListener listener, @CheckForNull File changelogFile, @CheckForNull SCMRevisionState baseline) throws IOException, InterruptedException { final AccurevServer server = getServer(); boolean serverDisabled = server != null && server.isServerDisabled(); if (!serverDisabled) { boolean checkout = AccurevMode.findDelegate(this).checkout(build, launcher, workspace, listener, changelogFile); if (checkout) listener.getLogger().println("Checkout done"); else listener.getLogger().println("Checkout failed"); }else{ listener.getLogger().println("Checkout skipped due to server disabled"); throw new InterruptedException(); } }
Source:
<code>public boolean isMetric(String fieldName) { <START> return getColumns(Metric.class).stream().anyMatch(metric -> metric.getName().equals(fieldName)); <END> }</code><technical_language>Simpler getMetric(fieldName) != null</technical_language>

Target:
public boolean isMetric(String fieldName) { return getMetric(fieldName) != null; }
Source:
<code>public Pair<String, String[]> processPrivilegePayloadForActivatedPrivileges (String privilegePayloadJson) throws PrivilagePayloadException{ try { JSONObject obj = new JSONObject(privilegePayloadJson); <START> int version; <END> if(obj.has("version")) { version = obj.getInt("version"); } else { if(obj.has("flag")) { version = 1; } else { throw new UnrecognizedPayloadVersionException(); } } switch(version) { case 1: return processAndValidateV1Payload(obj); case 2: return processAndValidateV2Payload(obj); default: throw new UnrecognizedPayloadVersionException(); } } catch (JSONException e) { throw new MalformedPayloadException(e); } }</code><technical_language>lines 27-36 a separate getPayloadVersion() method</technical_language>

Target:
public Pair<String, String[]> processPrivilegePayloadForActivatedPrivileges (String privilegePayloadJson) throws PrivilagePayloadException { try { JSONObject obj = new JSONObject(privilegePayloadJson); int version = getPayloadVersion(obj); switch (version) { case 1: return processAndValidateV1Payload(obj); case 2: return processAndValidateV2Payload(obj); default: throw new UnrecognizedPayloadVersionException(); } } catch (JSONException e) { throw new MalformedPayloadException(e); } }
Source:
<code>public void setUp() { sprite = Mockito.mock(Sprite.class); spriteLook = Mockito.mock(Look.class); sprite.look = spriteLook; embroideryPatternManager = Mockito.mock(EmbroideryPatternManager.class); StageActivity.stageListener = Mockito.mock(StageListener.class); StageActivity.stageListener.embroideryPatternManager = embroideryPatternManager; <START> final int density = 5; <END> final int height = 10; zigZagRunningStitch = new ZigZagRunningStitch(sprite, density, height); }</code><technical_language>usages call this "width" Please rename this</technical_language>

Target:
public void setUp() { sprite = Mockito.mock(Sprite.class); spriteLook = Mockito.mock(Look.class); sprite.look = spriteLook; embroideryPatternManager = Mockito.mock(EmbroideryPatternManager.class); StageActivity.stageListener = Mockito.mock(StageListener.class); StageActivity.stageListener.embroideryPatternManager = embroideryPatternManager; final int width = 5; final int height = 10; zigZagRunningStitch = new ZigZagRunningStitch(sprite, width, height); }
Source:
<code>protected BluetoothConnectionSettingHandler getHandler(Context context) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); <START> return bluetoothAdapter == null ? null : new BluetoothConnectionSettingHandler(context, bluetoothAdapter); <END> }</code><technical_language>A log message bluetooth adapter is present in</technical_language>

Target:
protected BluetoothConnectionSettingHandler getHandler(Context context) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { String errorMessage = "No default bluetooth adapter found"; Log.e(TAG, errorMessage); setResultData(errorMessage); return null; } return new BluetoothConnectionSettingHandler(context, bluetoothAdapter); }
Source:
<code>public void shouldSaveDiagnosis() { CodedOrFreeText codedOrFreeText = new CodedOrFreeText(new Concept(4), new ConceptName(5089), "non coded"); Date date = new Date(); <START> int id = 5; <END> String uuid = "4e663d96-6b78-11e0-93c3-18a9b5e044dc"; int rank = 2; ConditionVerificationStatus certainty = ConditionVerificationStatus.CONFIRMED; User creator = new User(1); Condition condition = new Condition(); Patient patient = new Patient(2); Encounter encounter = new Encounter(3); Diagnosis diagnosis = new Diagnosis(); diagnosis.setEncounter(encounter); diagnosis.setRank(rank); diagnosis.setId(id); diagnosis.setCertainty(certainty); diagnosis.setPatient(patient); diagnosis.setCondition(condition); diagnosis.setDiagnosis(codedOrFreeText); diagnosis.setUuid(uuid); diagnosis.setCreator(creator); diagnosis.setVoided(false); diagnosis.setDateCreated(date); diagnosisDAO.saveDiagnosis(diagnosis); Diagnosis savedDiagnosis = diagnosisDAO.getDiagnosisById(id); assertEquals(uuid, diagnosis.getUuid()); assertEquals(false, diagnosis.getVoided()); assertEquals(rank, (int) diagnosis.getRank()); assertEquals(certainty, diagnosis.getCertainty()); assertEquals(creator, diagnosis.getCreator()); assertEquals(condition, diagnosis.getCondition()); assertEquals(patient, diagnosis.getPatient()); assertEquals(encounter, diagnosis.getEncounter()); }</code><technical_language>more meaningful variable names? diagnosisId instead id</technical_language>

Target:
public void shouldSaveDiagnosis() { CodedOrFreeText codedOrFreeText = new CodedOrFreeText(new Concept(4), new ConceptName(5089), "non coded"); int diagnosisId = 5; Diagnosis diagnosis = new Diagnosis(); diagnosis.setEncounter(new Encounter(3)); diagnosis.setRank(2); diagnosis.setId(diagnosisId); diagnosis.setCertainty(ConditionVerificationStatus.CONFIRMED); diagnosis.setPatient(new Patient(2)); diagnosis.setCondition(new Condition()); diagnosis.setDiagnosis(codedOrFreeText); diagnosis.setUuid("4e663d96-6b78-11e0-93c3-18a9b5e044dc"); diagnosis.setCreator(new User(1)); diagnosis.setVoided(false); diagnosis.setDateCreated(new Date()); diagnosisDAO.saveDiagnosis(diagnosis); Diagnosis savedDiagnosis = diagnosisDAO.getDiagnosisById(diagnosisId); assertEquals(diagnosis.getUuid(), savedDiagnosis.getUuid()); assertEquals(diagnosis.getVoided(), savedDiagnosis.getVoided()); assertEquals(diagnosis.getRank(), savedDiagnosis.getRank()); assertEquals(diagnosis.getCertainty(), savedDiagnosis.getCertainty()); assertEquals(diagnosis.getCreator(), savedDiagnosis.getCreator()); assertEquals(diagnosis.getCondition(), savedDiagnosis.getCondition()); assertEquals(diagnosis.getPatient(), savedDiagnosis.getPatient()); assertEquals(diagnosis.getEncounter(), savedDiagnosis.getEncounter()); }
Source:
<code>FrameDesc update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); if (frame == null) { synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts)); } lastStableBitrateBps = getBitrateBps(nowMs); } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { FrameDesc ceilingFrame = ceilingEntry.getValue(); long tsDiff = (ceilingFrame.getTimestamp() - ts) & 0xFFFFFFFFL; if (tsDiff < (1L<<31) && (ceilingFrame.getStart() != -1 || frame.getEnd() != -1)) { int minSeen = ceilingFrame.getMinSeen(); int maxSeen = frame.getMaxSeen(); int snDiff = (minSeen - maxSeen) & 0xFFFF; if (snDiff < 3) { frame.setEnd((maxSeen + 1) & 0xFFFF); ceilingFrame.setStart((minSeen - 1) & 0xFFFF); } } } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { FrameDesc floorFrame = floorEntry.getValue(); <START> long tsDiff = (floorFrame.getTimestamp() - ts) & 0xFFFFFFFFL; <END> if (tsDiff < (1L<<31) && (floorFrame.getEnd() != -1 || frame.getStart() != -1)) { int minSeen = frame.getMinSeen(); int maxSeen = floorFrame.getMaxSeen(); int snDiff = (minSeen - maxSeen) & 0xFFFF; if (snDiff < 3) { frame.setStart((minSeen - 1) & 0xFFFF); floorFrame.setEnd((maxSeen + 1) & 0xFFFF); } } } } return frameChanged ? frame : null; }</code><technical_language>this ts - floorTS</technical_language>

Target:
FrameDesc update(RawPacket pkt, long nowMs) { rateStatistics.update(pkt.getLength(), nowMs); long ts = pkt.getTimestamp(); FrameDesc frame = frames.get(ts); if (frame == null) { synchronized (frames) { frames.put(ts, frame = new FrameDesc(this, ts)); } lastStableBitrateBps = getBitrateBps(nowMs); } boolean frameChanged = frame.update(pkt); if (frameChanged) { Map.Entry<Long, FrameDesc> ceilingEntry = frames.ceilingEntry((ts + 1) & 0xFFFFFFFFL); if (ceilingEntry != null) { applyFrameBoundsHeuristics(frame, ceilingEntry.getValue()); } Map.Entry<Long, FrameDesc> floorEntry = frames.floorEntry((ts - 1) & 0xFFFFFFFFL); if (floorEntry != null) { applyFrameBoundsHeuristics(floorEntry.getValue(), frame); } } return frameChanged ? frame : null; }
Source:
<code>private ClusterCompositionResponse processRoutingResponse( RoutingProcedureResponse response ) { if ( !response.isSuccess() ) { return new ClusterCompositionResponse.Failure( new ServiceUnavailableException( format( "Failed to run '%s' on server. " + "Please make sure that there is a Neo4j 3.1+ causal cluster up running.", invokedProcedureString( response ) ), response.error() ) ); } List<Record> records = response.records(); if ( log.isDebugEnabled() ) { <START> log.debug( "Received response from %s procedure: %s", invokedProcedureString( response ), records ); <END> } long now = clock.millis(); if ( records.size() != 1 ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "records received '%s' is too few or too many.", invokedProcedureString( response ), records.size() ) ) ); } ClusterComposition cluster; try { cluster = ClusterComposition.parse( records.get( 0 ), now ); } catch ( ValueException e ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "unparsable record received.", invokedProcedureString( response ) ), e ) ); } if ( !cluster.hasRoutersAndReaders() ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "no router or reader found in response.", invokedProcedureString( response ) ) ) ); } return new ClusterCompositionResponse.Success( cluster ); }</code><technical_language>sugget change INFO</technical_language>

Target:
private ClusterCompositionResponse processRoutingResponse( RoutingProcedureResponse response ) { if ( !response.isSuccess() ) { return new ClusterCompositionResponse.Failure( new ServiceUnavailableException( format( "Failed to run '%s' on server. " + "Please make sure that there is a Neo4j 3.1+ causal cluster up running.", invokedProcedureString( response ) ), response.error() ) ); } List<Record> records = response.records(); log.info( "Received response from %s procedure: %s", invokedProcedureString( response ), records ); long now = clock.millis(); if ( records.size() != 1 ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "records received '%s' is too few or too many.", invokedProcedureString( response ), records.size() ) ) ); } ClusterComposition cluster; try { cluster = ClusterComposition.parse( records.get( 0 ), now ); } catch ( ValueException e ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "unparsable record received.", invokedProcedureString( response ) ), e ) ); } if ( !cluster.hasRoutersAndReaders() ) { return new ClusterCompositionResponse.Failure( new ProtocolException( format( PROTOCOL_ERROR_MESSAGE + "no router or reader found in response.", invokedProcedureString( response ) ) ) ); } return new ClusterCompositionResponse.Success( cluster ); }
Source:
<code>private void assertQueryStringEquals(String first, String second) { <START> List<NameValuePair> firstList = URLEncodedUtilsHC4.parse(first, Charset.forName("utf8")); <END> List<NameValuePair> secondList = URLEncodedUtilsHC4.parse(second, Charset.forName("utf8")); assertEquals(new HashSet(firstList), new HashSet(secondList)); }</code><technical_language>Sets. Set<NameValuePair> firstSet = new HashSet<>(URLEncodedUtilsHC4.........);</technical_language>

Target:
private void assertQueryStringEquals(String first, String second) { Set<NameValuePair> firstList = new HashSet(URLEncodedUtilsHC4.parse(first, Charset.forName("utf8"))); Set<NameValuePair> secondList = new HashSet(URLEncodedUtilsHC4.parse(second, Charset.forName("utf8"))); assertEquals(firstList, secondList); }
Source:
<code>void lowCollisionBroadcast(Control event) { if (System.currentTimeMillis() > lastLowCollisionBroadcast + minTimeBetweenBroadcast) { try { WebSocketBroadcast.Message message = WebSocketBroadcast.newMessage(getClass(), event); eventBus.post(message); <START> lastLowCollisionBroadcast = System.currentTimeMillis(); <END> log.info("Sent low collision broadcast"); } catch (JsonProcessingException ex) { log.error("Unable to convert control message", ex); } } }</code><technical_language>Assignment is threadsafe</technical_language>

Target:
void lowCollisionBroadcast(Control event) { long now = System.currentTimeMillis(); long lastCheckTimeExpected = lastLowCollisionBroadcast.get(); if (now > lastCheckTimeExpected + minTimeBetweenBroadcast && lastLowCollisionBroadcast.compareAndSet(lastCheckTimeExpected, now)) { try { WebSocketBroadcast.Message message = WebSocketBroadcast.newMessage(getClass(), event); eventBus.post(message); log.info("Sent low collision broadcast"); } catch (JsonProcessingException ex) { log.error("Unable to convert control message", ex); } } }
Source:
<code>public PromotionProcess createProcessFromXml(final String name, InputStream xml) throws IOException { owner.checkPermission(Item.CONFIGURE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (getItem(name) != null) { throw new IllegalArgumentException(owner.getDisplayName() + " already contains an item '" + name + "'"); } File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); File dir = configXml.getParentFile(); if (!dir.mkdirs()) { <START> throw new IIOException("Cannot create directories for "+dir); <END> } try { IOUtils.copy(xml, configXml); PromotionProcess result = Items.whileUpdatingByXml(new Callable<PromotionProcess,IOException>() { @Override public PromotionProcess call() throws IOException { setOwner(owner); return getItem(name); } }); if (result == null) { throw new IOException("failed to load from " + configXml); } ItemListener.fireOnCreated(result); return result; } catch (IOException e) { Util.deleteRecursive(dir); throw e; } }</code><technical_language>IIOException??? :bug:</technical_language>

Target:
public PromotionProcess createProcessFromXml(final String name, InputStream xml) throws IOException { owner.checkPermission(Item.CONFIGURE); Jenkins.getInstance().getProjectNamingStrategy().checkName(name); if (getItem(name) != null) { throw new IllegalArgumentException(owner.getDisplayName() + " already contains an item '" + name + "'"); } File configXml = Items.getConfigFile(getRootDirFor(name)).getFile(); File dir = configXml.getParentFile(); if (!dir.mkdirs()) { throw new IOException("Cannot create directories for "+dir); } try { IOUtils.copy(xml, configXml); PromotionProcess result = Items.whileUpdatingByXml(new Callable<PromotionProcess,IOException>() { @Override public PromotionProcess call() throws IOException { setOwner(owner); return getItem(name); } }); if (result == null) { throw new IOException("failed to load from " + configXml); } ItemListener.fireOnCreated(result); return result; } catch (IOException e) { Util.deleteRecursive(dir); throw e; } }
Source:
<code>private AppConfiguration() throws ConfigurationException { this.transactionStore = loadTransactionStoreConfig(); this.websitePath = loadWebsitePathConfig(); this.enableVerifyPublish = loadEnableVerifyPublishContentFeatureFlag(); this.fileUploadsTmpDir = createTmpFileUploadsDir(); this.publishThreadPoolSize = getIntegerEnvVar(THREAD_POOL_SIZE_ENV_KEY); this.port = getIntegerEnvVar(PORT_ENV_KEY); this.maxFileUploadSize = getLongEnvVar(MAX_FILE_UPLOAD_SIZE_MB); this.maxRequestSize = getLongEnvVar(MAX_REQUEST_SIZE_MB); this.fileThresholdSize = getIntegerEnvVar(FILE_THRESHOLD_SIZE_MB); info().data(TRANSACTION_STORE_ENV_KEY, transactionStore) .data(WEBSITE_ENV_KEY, websitePath) .data(THREAD_POOL_SIZE_ENV_KEY, publishThreadPoolSize) .data(PORT_ENV_KEY, port) .data(ENABLE_VERIFY_PUBLISH_CONTENT, enableVerifyPublish) .data(FILE_UPLOADS_TMP_DIR, fileUploadsTmpDir) .data(MAX_FILE_UPLOAD_SIZE_MB, maxFileUploadSize) .data(MAX_REQUEST_SIZE_MB, maxRequestSize) <START> .data(FILE_THRESHOLD_SIZE_MB, FileUtils.byteCountToDisplaySize(fileThresholdSize)) <END> .log("successfully load application configuration"); }</code><technical_language>I want apply FileUtils.byteCountToDisplaySize MAX_FILE_UPLOAD_SIZE_MB MAX_REQUEST_SIZE_MB, byte values? If so, I needs applied FILE_THRESHOLD_SIZE_MB, is a MB</technical_language>

Target:
private AppConfiguration() throws ConfigurationException { this.transactionStore = loadTransactionStoreConfig(); this.websitePath = loadWebsitePathConfig(); this.enableVerifyPublish = loadEnableVerifyPublishContentFeatureFlag(); this.fileUploadsTmpDir = createTmpFileUploadsDir(); this.publishThreadPoolSize = getIntegerEnvVar(THREAD_POOL_SIZE_ENV_KEY); this.port = getIntegerEnvVar(PORT_ENV_KEY); this.maxFileUploadSize = getLongEnvVar(MAX_FILE_UPLOAD_SIZE_MB); this.maxRequestSize = getLongEnvVar(MAX_REQUEST_SIZE_MB); this.fileThresholdSize = getIntegerEnvVar(FILE_THRESHOLD_SIZE_MB); info().data(TRANSACTION_STORE_ENV_KEY, transactionStore) .data(WEBSITE_ENV_KEY, websitePath) .data(THREAD_POOL_SIZE_ENV_KEY, publishThreadPoolSize) .data(PORT_ENV_KEY, port) .data(ENABLE_VERIFY_PUBLISH_CONTENT, enableVerifyPublish) .data(FILE_UPLOADS_TMP_DIR, fileUploadsTmpDir) .data(MAX_FILE_UPLOAD_SIZE_MB, maxFileUploadSize) .data(MAX_REQUEST_SIZE_MB, maxRequestSize) .data(FILE_THRESHOLD_SIZE_MB, fileThresholdSize + " MB") .log("successfully load application configuration"); }
Source:
<code>public boolean isSubscribedToApp(APIIdentifier apiIdentifier, String userId, int applicationId) throws APIManagementException { boolean isSubscribed; try { isSubscribed = apiMgtDAO.isSubscribedToApp(apiIdentifier, userId, applicationId); } catch (APIManagementException e) { String msg = "Failed to check if user(" + userId + ") has subscribed to " + apiIdentifier; <START> log.error(msg, e); <END> throw new APIManagementException(msg, e); } return isSubscribed; }</code><technical_language>Check log exception elsewhere. If so, duplicate exceptions logged. Log Throw is generally considered antipattern</technical_language>

Target:
public boolean isSubscribedToApp(APIIdentifier apiIdentifier, String userId, int applicationId) throws APIManagementException { boolean isSubscribed; try { isSubscribed = apiMgtDAO.isSubscribedToApp(apiIdentifier, userId, applicationId); } catch (APIManagementException e) { String msg = "Failed to check if user(" + userId + ") with appId " + applicationId + " has subscribed to " + apiIdentifier; log.error(msg, e); throw new APIManagementException(msg, e); } return isSubscribed; }
Source:
<code>public SWTBotShell maximize(final boolean maximize) throws TimeoutException { boolean isMaximizedState = isMaximizedState(); <START> if ((maximize && isMaximizedState) || (!maximize && !isMaximizedState)) { <END> log.debug(MessageFormat.format("Shell {0} is already in expected state, not resizing again.", this)); return this; } final Point initialSize = new Point(getBounds().width, getBounds().height); activate(); syncExec(new VoidResult() { @Override public void run() { widget.setMaximized(maximize); } }); notify(SWT.Resize); notify(SWT.Move); notify(SWT.Paint); new SWTBot().waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Timed out waiting for " + SWTUtils.toString(widget) + " to get maximized/unmaximized"; } @Override public boolean test() throws Exception { if (maximize) return isMaximizedState() && isResized(initialSize); else return !isMaximizedState() && isResized(initialSize); } }); return this; }</code><technical_language>This is (maximize == isMaximizedState)</technical_language>

Target:
public SWTBotShell maximize(final boolean maximize) throws TimeoutException { if (maximize == isMaximizedState()) { log.debug(MessageFormat.format("{0} is already in expected state, not resizing again.", this)); return this; } final Rectangle initialRectangle = getBounds(); activate(); syncExec(new VoidResult() { @Override public void run() { widget.setMaximized(maximize); } }); new SWTBot().waitUntil(new DefaultCondition() { @Override public String getFailureMessage() { return "Timed out waiting for " + SWTUtils.toString(widget) + " to get maximized/unmaximized"; } @Override public boolean test() throws Exception { if (maximize) { return isMaximizedState() && isResized(initialRectangle); } else { return !isMaximizedState() && isResized(initialRectangle); } } }); return this; }
Source:
<code>public void processSubCommand(ICommandSender sender, String[] args) { if (args.length < 1) { printHelp(sender); return; } World world; if (args.length == 2) world = CommandHelpers.getWorld(sender, this, args, 0); else world = CommandHelpers.getWorld(sender, this); String desired = args[args.length - 1]; IBeekeepingMode mode = PluginApiculture.beeInterface.getBeekeepingMode(desired); if (mode == null) throw new CommandException(StringUtil.localize("chat.bees.command.beekeeping.error"), desired); PluginApiculture.beeInterface.setBeekeepingMode(world, mode.getName()); <START> CommandHelpers.sendLocalizedChatMessage(sender, StringUtil.localize("chat.bees.command.beekeeping.set"), mode.getName()); <END> }</code><technical_language>Remove StringUtil.localize() here, is redundant locks locale English (the server locale)</technical_language>

Target:
public void processSubCommand(ICommandSender sender, String[] args) { if (args.length == 0 || args.length > 2) { printHelp(sender); return; } World world; if (args.length == 2) world = CommandHelpers.getWorld(sender, this, args, 0); else world = CommandHelpers.getWorld(sender, this); String desired = args[args.length - 1]; IBeekeepingMode mode = PluginApiculture.beeInterface.getBeekeepingMode(desired); if (mode == null) { CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.beekeeping.mode.set.error", desired); printHelp(sender); return; } PluginApiculture.beeInterface.setBeekeepingMode(world, mode.getName()); CommandHelpers.sendLocalizedChatMessage(sender, "for.chat.command.forestry.beekeeping.mode.set.success", mode.getName()); }
Source:
<code>public ImmutableSpongeBlockItemData(BlockState value) { super(ImmutableBlockItemData.class, value, Keys.ITEM_BLOCKSTATE); <START> this.state = new ImmutableSpongeValue<>(Keys.ITEM_BLOCKSTATE, BlockTypes.STONE.getDefaultState(), value); <END> }</code><technical_language>BlockTypes.STONE.getDefaultState() a dataConstant move this DataConstants</technical_language>

Target:
public ImmutableSpongeBlockItemData(BlockState value) { super(ImmutableBlockItemData.class, value, Keys.ITEM_BLOCKSTATE); this.state = new ImmutableSpongeValue<>(Keys.ITEM_BLOCKSTATE, DataConstants.DEFAULT_BLOCK_STATE, value); }
Source:
<code>public static String getCertKeyIdAuthority(X509Certificate cert) { if (null == cert) { return null; } byte[] akiBytes = cert.getExtensionValue(AUTHORITY_KEY_ID); String aki = null; try { <START> if (akiBytes != null) { <END> DERDecoder extValA = new DERDecoder(akiBytes); extValA.skip(6); aki = Hex.encodeHexString(extValA.getBytes(20)); } } catch (WSSecurityException e) { LOG.error("Unable to convert AIK into human readable {}", e.getLocalizedMessage(), e); } return aki; }</code><technical_language>do need this method</technical_language>

Target:
public static String getCertKeyIdAuthority(X509Certificate cert) { String aki = null; if (null != cert) { byte[] akiBytes = cert.getExtensionValue(AUTHORITY_KEY_ID); try { if (akiBytes != null) { DERDecoder extValA = new DERDecoder(akiBytes); extValA.skip(6); aki = Hex.encodeHexString(extValA.getBytes(20)); } } catch (WSSecurityException e) { LOG.error("Unable to decode certificate authority {}", e.getLocalizedMessage(), e); } } return aki; }
Source:
<code>public void upgradeSmokes() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); <START> r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). <END> grant(Jenkins.RUN_SCRIPTS, Jenkins.READ, Item.READ).everywhere().to("runScriptsUser"). grant(Jenkins.READ, Item.READ).everywhere().to("otherUser")); FreeStyleProject p = r.createFreeStyleProject(); p.getPublishersList().add(new TestGroovyRecorder( new SecureGroovyScript("jenkins.model.Jenkins.instance", true, null))); r.assertLogNotContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: " + "Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0).get())); }</code><technical_language>I Jenkins' security realm authorization strategy matter for this test running in sandbox, lines deleted</technical_language>

Target:
public void upgradeSmokes() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); p.getPublishersList().add(new TestGroovyRecorder( new SecureGroovyScript("jenkins.model.Jenkins.instance", true, null))); r.assertLogNotContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: " + "Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r.assertBuildStatus(Result.SUCCESS, p.scheduleBuild2(0).get())); }
Source:
<code>private List<RemoteTask> scheduleTasks(int count) { if (count == 0) { return ImmutableList.of(); } List<Node> nodes = nodeSelector.selectRandomNodes(count, scheduledNodes); checkCondition(!scheduledNodes.isEmpty() || !nodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); ImmutableList.Builder<RemoteTask> tasks = ImmutableList.builder(); for (Node node : nodes) { Optional<RemoteTask> remoteTask = stage.scheduleTask(node, scheduledNodes.size(), OptionalInt.empty()); <START> remoteTask.ifPresent(element -> { <END> tasks.add(element); scheduledNodes.add(node); }); } return tasks.build(); }</code><technical_language>nit: Do want call task instead of element ? :)</technical_language>

Target:
private List<RemoteTask> scheduleTasks(int count) { if (count == 0) { return ImmutableList.of(); } List<Node> nodes = nodeSelector.selectRandomNodes(count, scheduledNodes); checkCondition(!scheduledNodes.isEmpty() || !nodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query"); ImmutableList.Builder<RemoteTask> tasks = ImmutableList.builder(); for (Node node : nodes) { Optional<RemoteTask> remoteTask = stage.scheduleTask(node, scheduledNodes.size(), OptionalInt.empty()); remoteTask.ifPresent(task -> { tasks.add(task); scheduledNodes.add(node); }); } return tasks.build(); }
Source:
<code>protected long releaseMemory() { long memoryFreed = 0; while (!windowsForFreeMemory.isEmpty()) { long windowId = windowsForFreeMemory.poll(); long originSize = keyStream.size() + valueStream.size(); keyStream.resetUpToWindow(windowId); valueStream.resetUpToWindow(windowId); memoryFreed += originSize - (keyStream.size() + valueStream.size()); } if (memoryFreed > 0) { LOG.debug("Total freed memory size: {}", memoryFreed); <START> sizeInBytes.getAndAdd(0 - memoryFreed); <END> } return memoryFreed; }</code><technical_language>This stay -memoryFreed</technical_language>

Target:
protected long releaseMemory() { long memoryFreed = 0; while (!windowsForFreeMemory.isEmpty()) { long windowId = windowsForFreeMemory.poll(); long originSize = keyStream.size() + valueStream.size(); keyStream.resetUpToWindow(windowId); valueStream.resetUpToWindow(windowId); memoryFreed += originSize - (keyStream.size() + valueStream.size()); } if (memoryFreed > 0) { LOG.debug("Total freed memory size: {}", memoryFreed); sizeInBytes.getAndAdd(-memoryFreed); } return memoryFreed; }
Source:
<code>private void runLoop() { subscribeConsumer(); while (isRunning()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoin the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskIds()); taskManager.handleCorruption(e.corruptedTaskIds()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + <START> "Will migrate out all assigned tasks and rejoin the consumer group."); <END> enforceRebalance(); } } }</code><technical_language>suggestion "Will close out assigned tasks rejoin consumer group.");</technical_language>

Target:
private void runLoop() { subscribeConsumer(); while (isRunning()) { try { runOnce(); if (assignmentErrorCode.get() == AssignorError.VERSION_PROBING.code()) { log.info("Version probing detected. Rejoining the consumer group to trigger a new rebalance."); assignmentErrorCode.set(AssignorError.NONE.code()); enforceRebalance(); } } catch (final TaskCorruptedException e) { log.warn("Detected the states of tasks are corrupted. " + "Will close the task as dirty and re-create and bootstrap from scratch.", e.corruptedTaskWithChangelogs()); taskManager.handleCorruption(e.corruptedTaskWithChangelogs()); } catch (final TaskMigratedException e) { log.warn("Detected that the thread is being fenced. " + "This implies that this thread missed a rebalance and dropped out of the consumer group. " + "Will close out all assigned tasks and rejoin the consumer group."); taskManager.handleLostAll(); enforceRebalance(); } } }