auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testLoadOrderedPublicEvents_10() throws Throwable { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24") .withAuthorization(Group.FREE_GROUP_NAME, "tempRole", Permission.BACKOFFICE).build(); String accessToken = mockOAuthInterceptor(user); ResultActions result = mockMvc .perform(get("/plugins/cms/contents") .param("status", IContentService.STATUS_ONLINE) .param("sort", "lastmodified") .param("direction", FieldSearchFilter.DESC_ORDER) .param("filters[0].attribute", IContentManager.ENTITY_TYPE_CODE_FILTER_KEY) .param("filters[0].operator", "eq") .param("filters[0].value", "EVN") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); <START> String bodyResult = result.andReturn().getResponse().getContentAsString(); result.andExpect(status().isOk()); String[] expectedFreeContentsId = {"EVN21", "EVN20", "EVN25", "EVN24", "EVN23", "EVN192", "EVN191", "EVN194", "EVN193"}; int payloadSize = JsonPath.read(bodyResult, "$.payload.size()"); Assert.assertEquals(expectedFreeContentsId.length, payloadSize); for (int i = 0; i < expectedFreeContentsId.length; i++) { String expectedId = expectedFreeContentsId[i]; String extractedId = JsonPath.read(bodyResult, "$.payload[" + i + "].id"); Assert.assertEquals(expectedId, extractedId); } <END> }</code><technical_language>Code style</technical_language>

Target:
public void testLoadOrderedPublicEvents_10() throws Throwable { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24") .withAuthorization(Group.FREE_GROUP_NAME, "tempRole", Permission.BACKOFFICE).build(); String accessToken = mockOAuthInterceptor(user); ResultActions result = mockMvc .perform(get("/plugins/cms/contents") .param("status", IContentService.STATUS_ONLINE) .param("sort", "lastmodified") .param("direction", FieldSearchFilter.DESC_ORDER) .param("filters[0].attribute", IContentManager.ENTITY_TYPE_CODE_FILTER_KEY) .param("filters[0].operator", "eq") .param("filters[0].value", "EVN") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); result.andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.payload.size()", is(9))) .andExpect(jsonPath("$.payload[0].id", is("EVN21"))) .andExpect(jsonPath("$.payload[1].id", is("EVN20"))) .andExpect(jsonPath("$.payload[2].id", is("EVN25"))) .andExpect(jsonPath("$.payload[3].id", is("EVN24"))) .andExpect(jsonPath("$.payload[4].id", is("EVN23"))) .andExpect(jsonPath("$.payload[5].id", is("EVN192"))) .andExpect(jsonPath("$.payload[6].id", is("EVN191"))) .andExpect(jsonPath("$.payload[7].id", is("EVN194"))) .andExpect(jsonPath("$.payload[8].id", is("EVN193"))); }
Source:
<code>abstract public void release() throws PublisherException; } private Node tail = new Node(null, 0); private int windowCount; public synchronized void add(PublisherPush item) throws PublisherException { Node prev = tail; tail = new Node(item, windowCount); <START> if (windowCount == 0) <END> item.close(); prev.setNext(tail); }</code><technical_language>if windowCount == 0, do anything, call close immediately (ideally of synchronized block). boolean hasWindows; synchronized(this) { hasWindows = windowCount != 0; if (hasWindows) { Node prev = tail; tail = new Node(item, windowCount); prev.setNext(tail); } } if (!hasWindows) item.close()</technical_language>

Target:
abstract public void release() throws PublisherException; } private Node tail = new Node(null, 0); private int windowCount; public synchronized void add(PublisherPush item) throws PublisherException { boolean hasWindows; synchronized (this) { hasWindows = windowCount != 0; if (hasWindows) { Node prev = tail; tail = new Node(item, windowCount); prev.setNext(tail); } } if (!hasWindows) item.close(); }
Source:
<code>public boolean matches(Calendar cal) { long matchStart = start != null ? start.getTimeInMillis() : DateTimeUtils.truncateToMidnight(cal).getTimeInMillis(); long matchEnd = end != null ? end.getTimeInMillis() : DateTimeUtils.truncateToMidnight(cal).getTimeInMillis(); <START> return cal.getTimeInMillis() >= matchStart && cal.getTimeInMillis() < matchEnd; <END> }</code><technical_language>If start/end given, conditions comparing DateTimeUtils.truncateToMidnight(cal). this true? matchEnd needs 24h added in this case</technical_language>

Target:
public boolean matches(Calendar cal) { if (start == null && end == null) { return false; } long matchStart = start != null ? start.getTimeInMillis() : DateTimeUtils.truncateToMidnight(cal).getTimeInMillis(); long matchEnd = end != null ? end.getTimeInMillis() : DateTimeUtils.endOfDayDate(cal).getTimeInMillis(); return cal.getTimeInMillis() >= matchStart && cal.getTimeInMillis() < matchEnd; }
Source:
<code>public void testInit() { final DataTypeListItem expectedListItem = mock(DataTypeListItem.class); final DataType datatype = mock(DataType.class); final String expectedConstraint = "constraint"; final ConstraintType expectedType = mock(ConstraintType.class); when(expectedListItem.getDataType()).thenReturn(datatype); when(datatype.getConstraint()).thenReturn(expectedConstraint); when(datatype.getConstraintType()).thenReturn(expectedType); dataTypeConstraint.init(expectedListItem); final DataTypeListItem actualListItem = dataTypeConstraint.getListItem(); final String actualConstraint = dataTypeConstraint.getValue(); final ConstraintType actualType = dataTypeConstraint.getConstraintType(); assertEquals(expectedType, actualType); assertEquals(expectedListItem, actualListItem); assertEquals(expectedConstraint, actualConstraint); verify(dataTypeConstraint).refreshView(); verify(datatype).getConstraintType(); <START> verify(datatype).getConstraintType(); <END> }</code><technical_language>Ops.. line twice. In fact, verifying getters called test method does. method is initialising this.constraintValue this.constraintType, I need assert that</technical_language>

Target:
public void testInit() { final DataTypeListItem expectedListItem = mock(DataTypeListItem.class); final DataType datatype = mock(DataType.class); final String expectedConstraint = "constraint"; final ConstraintType expectedType = mock(ConstraintType.class); when(expectedListItem.getDataType()).thenReturn(datatype); when(datatype.getConstraint()).thenReturn(expectedConstraint); when(datatype.getConstraintType()).thenReturn(expectedType); dataTypeConstraint.init(expectedListItem); final DataTypeListItem actualListItem = dataTypeConstraint.getListItem(); final String actualConstraint = dataTypeConstraint.getValue(); final ConstraintType actualType = dataTypeConstraint.getConstraintType(); assertEquals(expectedType, actualType); assertEquals(expectedListItem, actualListItem); assertEquals(expectedConstraint, actualConstraint); verify(dataTypeConstraint).refreshView(); }
Source:
<code>private boolean hasNewServers(VDSGroup cluster, List<VDS> existingServers, List<GlusterServerInfo> fetchedServers) { if (GlusterFeatureSupported.glusterHostUuidSupported(cluster.getcompatibility_version())) { for (GlusterServerInfo fetchedServer : fetchedServers) { GlusterServer glusterServer = getGlusterServerDao().getByGlusterServerUuid(fetchedServer.getUuid()); <START> if (glusterServer == null || getVdsDao().get(glusterServer.getId()) == null) { <END> return true; } } } else { for (GlusterServerInfo fetchedServer : fetchedServers) { for (VDS existingServer: existingServers) { List<String> vdsIps = getVdsIps(existingServer); if (!fetchedServer.getHostnameOrIp().equals(existingServer.getHostName()) && !vdsIps.contains(fetchedServer.getHostnameOrIp())) { return true; } } } } return false; }</code><technical_language>is getVdsDao.get(glusterServer.getId()) required</technical_language>

Target:
private boolean hasNewServers(VDSGroup cluster, List<VDS> existingServers, List<GlusterServerInfo> fetchedServers) { if (GlusterFeatureSupported.glusterHostUuidSupported(cluster.getcompatibility_version())) { for (GlusterServerInfo fetchedServer : fetchedServers) { GlusterServer glusterServer = getGlusterServerDao().getByGlusterServerUuid(fetchedServer.getUuid()); if (glusterServer == null) { return true; } } } else { for (GlusterServerInfo fetchedServer : fetchedServers) { for (VDS existingServer: existingServers) { List<String> vdsIps = getVdsIps(existingServer); if (!fetchedServer.getHostnameOrIp().equals(existingServer.getHostName()) && !vdsIps.contains(fetchedServer.getHostnameOrIp())) { return true; } } } } return false; }
Source:
<code>private HyperparameterValues calculateMLEHyperparameterValues(final AllelicCountCollection counts) { double meanBias = AlleleFractionInitializer.INITIAL_MEAN_BIAS; double biasVariance = AlleleFractionInitializer.INITIAL_BIAS_VARIANCE; double previousIterationLogLikelihood; double nextIterationLogLikelihood = Double.NEGATIVE_INFINITY; <START> int iteration = 1; <END> logger.info(String.format("Initializing MLE hyperparameter values for allelic panel of normals. Iterating until log likelihood converges to within %.3f.", AlleleFractionInitializer.LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD)); do { previousIterationLogLikelihood = nextIterationLogLikelihood; meanBias = estimateMeanBias(meanBias, biasVariance, counts); biasVariance = estimateBiasVariance(meanBias, biasVariance, counts); nextIterationLogLikelihood = AlleleFractionLikelihoods.logLikelihoodForAllelicPanelOfNormals(meanBias, biasVariance, counts); logger.info(String.format("Iteration %d, model log likelihood = %.3f.", iteration, nextIterationLogLikelihood)); iteration++; } while (iteration < AlleleFractionInitializer.MAX_ITERATIONS && nextIterationLogLikelihood - previousIterationLogLikelihood > AlleleFractionInitializer.LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD); final double alpha = alpha(meanBias, biasVariance); final double beta = beta(meanBias, biasVariance); logger.info("MLE hyperparameter values for allelic panel of normals found:"); logger.info("alpha = " + alpha); logger.info("beta = " + beta); return new HyperparameterValues(alpha, beta); }</code><technical_language>iteration = 1 logging</technical_language>

Target:
private HyperparameterValues calculateMLEHyperparameterValues(final AllelicCountCollection counts) { double meanBias = AlleleFractionInitializer.INITIAL_MEAN_BIAS; double biasVariance = AlleleFractionInitializer.INITIAL_BIAS_VARIANCE; double previousIterationLogLikelihood; double nextIterationLogLikelihood = Double.NEGATIVE_INFINITY; logger.info(String.format("Initializing MLE hyperparameter values for allelic panel of normals. Iterating until log likelihood converges to within %.3f.", AlleleFractionInitializer.LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD)); int iteration = 1; do { previousIterationLogLikelihood = nextIterationLogLikelihood; meanBias = estimateMeanBias(meanBias, biasVariance, counts); biasVariance = estimateBiasVariance(meanBias, biasVariance, counts); nextIterationLogLikelihood = AlleleFractionLikelihoods.logLikelihoodForAllelicPanelOfNormals(meanBias, biasVariance, counts); logger.info(String.format("Iteration %d, model log likelihood = %.3f.", iteration, nextIterationLogLikelihood)); iteration++; } while (iteration < AlleleFractionInitializer.MAX_ITERATIONS && nextIterationLogLikelihood - previousIterationLogLikelihood > AlleleFractionInitializer.LOG_LIKELIHOOD_CONVERGENCE_THRESHOLD); final double alpha = alpha(meanBias, biasVariance); final double beta = beta(meanBias, biasVariance); logger.info("MLE hyperparameter values for allelic panel of normals found:"); logger.info("alpha = " + alpha); logger.info("beta = " + beta); return new HyperparameterValues(alpha, beta); }
Source:
<code>private Double calculateSelfHealEta() { if (this.getUnSyncedEntries() == null || this.getUnSyncedEntriesTrend() == null || this.getUnSyncedEntriesTrend().size() < 2) { return 0D; } List<Double> healRates = new ArrayList<>(); for (int index = 0; index < this.getUnSyncedEntriesTrend().size() - 1; index++) { Integer entries = this.unSyncedEntriesTrend.get(index); <START> Integer entriesRemaining = this.unSyncedEntriesTrend.get(index); <END> if (entries >= 0 && entriesRemaining >= 0) { double healRate = ((double) entries - entriesRemaining) / (Config.<Integer> getValue(ConfigValues.GlusterRefreshRateHealInfo)); if (healRate > 0) { healRates.add(healRate); } } } if (healRates.isEmpty()) { return 0D; } Double healRateSum = 0D; for (Double healRate : healRates) { healRateSum += healRate; } Double healRateAvg = healRateSum / healRates.size(); return this.getUnSyncedEntries() / healRateAvg; }</code><technical_language>index + 1</technical_language>

Target:
private Double calculateSelfHealEta() { if (this.getUnSyncedEntries() == null || this.getUnSyncedEntriesTrend() == null || this.getUnSyncedEntriesTrend().size() < 2) { return 0D; } List<Double> healRates = new ArrayList<>(); for (int index = 0; index < this.getUnSyncedEntriesTrend().size() - 1; index++) { Integer entries = this.unSyncedEntriesTrend.get(index); Integer entriesRemaining = this.unSyncedEntriesTrend.get(index + 1); if (entries >= 0 && entriesRemaining >= 0) { double healRate = ((double) entries - entriesRemaining) / (Config.<Integer> getValue(ConfigValues.GlusterRefreshRateHealInfo)); if (healRate > 0) { healRates.add(healRate); } } } if (healRates.isEmpty()) { return 0D; } Double healRateSum = 0D; for (Double healRate : healRates) { healRateSum += healRate; } Double healRateAvg = healRateSum / healRates.size(); return this.getUnSyncedEntries() / healRateAvg; }
Source:
<code>public final int hashCode() { if (hashCode == Utils.NO_HASHCODE) { <START> int accum = computeHash(); <END> hashCode = accum == 0 ? 1 : accum; } return hashCode; }</code><technical_language>racey single check</technical_language>

Target:
public final int hashCode() { int h = hashCode; if (h == Utils.NO_HASHCODE) { h = computeHash(); hashCode = h == 0 ? 1 : h; } return h; }
Source:
<code>protected void serializeToFile(Component component, Object from) throws IOException { String jsonOutputString = gson.toJson(from); try { checkComplianceWithSchema(jsonOutputString); } catch (ValidationException exception) { log.error(component.getKey() + " json not compliant with schema"); throw exception; } File file = new File(outputDirectory, component.getKey() + ".json"); <START> log.info("Generate json data for plugin " + component.getKey() + " in: " + file); <END> FileUtils.writeStringToFile(file, jsonOutputString, UTF_8); FileUtils.copyURLToFile( PluginsJsonGenerator.class.getResource("/" + resourceFile), new File(outputDirectory, resourceFile)); }</code><technical_language>NP: this is abstract, "...json data for component ..."</technical_language>

Target:
protected void serializeToFile(Component component, Object from) throws IOException { String jsonOutputString = gson.toJson(from); try { checkComplianceWithSchema(jsonOutputString); } catch (ValidationException exception) { log.error(component.getKey() + " json not compliant with schema"); throw exception; } File file = new File(outputDirectory, component.getKey() + ".json"); log.info("Generate json data for component " + component.getKey() + " in: " + file); FileUtils.writeStringToFile(file, jsonOutputString, UTF_8); FileUtils.copyURLToFile( PluginsJsonGenerator.class.getResource("/" + resourceFile), new File(outputDirectory, resourceFile)); }
Source:
<code>protected void runWrongValidationTest(boolean skipGetModel) { model.setValue(-123); model.getUser().setLastName(""); model.getUser().setAddress(""); assertFalse(formHandler.validate()); verify(proxy).deepUnwrap(); if (!skipGetModel) { verify(binder, times(formFieldProvider.getAll().size() + 1)).getModel(); verify(proxy, times(formFieldProvider.getAll().size())).get(anyString()); } assertFalse(formHandler.validate(VALUE_FIELD)); assertTrue(formHandler.validate(USER_NAME_FIELD)); assertFalse(formHandler.validate(USER_LAST_NAME_FIELD)); assertTrue(formHandler.validate(USER_BIRTHDAY_FIELD)); assertTrue(formHandler.validate(USER_MARRIED_FIELD)); assertFalse(formHandler.validate(USER_ADDRESS_FIELD)); <START> verify(proxy, times(7)).deepUnwrap(); <END> }</code><technical_language>@pefernan I noticed method is called in 6 calls of validate. enough test field is a behavior expected out fields? hard identify problem is, if deepUnwrap() is called 6 times 7 times. if tested for of fields, I call verify each, if - I test field... This is a nitpick, unusually high number in "times" dragged attention. :)</technical_language>

Target:
protected void runWrongValidationTest(boolean skipGetModel) { model.setValue(-123); model.getUser().setLastName(""); model.getUser().setAddress(""); assertFalse(formHandler.validate()); verify(proxy).deepUnwrap(); if (!skipGetModel) { verify(binder, times(7)).getModel(); verify(proxy, times(6)).get(anyString()); } assertFalse(formHandler.validate(VALUE_FIELD_NAME)); assertTrue(formHandler.validate(USER_NAME_FIELD_NAME)); assertFalse(formHandler.validate(USER_LAST_NAME_FIELD_NAME)); assertTrue(formHandler.validate(USER_BIRTHDAY_FIELD_NAME)); assertTrue(formHandler.validate(USER_MARRIED_FIELD_NAME)); assertFalse(formHandler.validate(USER_ADDRESS_FIELD_NAME)); verify(proxy, times(7)).deepUnwrap(); }
Source:
<code>public <T extends RealType<T>> boolean areCongruent(final IterableInterval<T> in, final RandomAccessible<T> out, final double epsilon){ Cursor<T> cin = in.localizingCursor(); RandomAccess<T> raOut = out.randomAccess(); while(cin.hasNext()){ cin.fwd(); raOut.setPosition(cin); <START> if((cin.get().getRealDouble() - raOut.get().getRealDouble()) > epsilon) return false; <END> } return true; }</code><technical_language>check absolute difference support case cin.get().getRealDouble() is raOut.get().getRealDouble() assuming epsilon positive is I suggest</technical_language>

Target:
public <T extends RealType<T>> boolean areCongruent(final IterableInterval<T> in, final RandomAccessible<T> out, final double epsilon){ Cursor<T> cin = in.localizingCursor(); RandomAccess<T> raOut = out.randomAccess(); while(cin.hasNext()){ cin.fwd(); raOut.setPosition(cin); if(Math.abs(cin.get().getRealDouble() - raOut.get().getRealDouble()) > epsilon) return false; } return true; }
Source:
<code>protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(element, parserContext, builder); element.setAttribute(BeanDefinitionParserDelegate.VALUE_TYPE_ATTRIBUTE, ProcessingConfig.Test.class.getCanonicalName()); List<Element> list = DomUtils.getChildElements(element); ManagedList tests = new ManagedList(list.size()); for (Element el : list){ if (!el.getAttribute(XMLConstants.ATTRIBUTE_REF).isEmpty()){ tests.add(new RuntimeBeanReference(el.getAttribute(XMLConstants.ATTRIBUTE_REF))); }else{ if (el.getTagName().equals(XMLConstants.TEST)){ tests.add(parserContext.getDelegate().parseCustomElement(el, builder.getBeanDefinition())); }else{ <START> if (el.getTagName().equals(XMLConstants.ATTRIBUTE_REF)){ <END> if (!el.getAttribute(XMLConstants.LOCAL).isEmpty()){ tests.add(new RuntimeBeanReference(el.getAttribute(XMLConstants.LOCAL))); }else{ tests.add(new RuntimeBeanReference(el.getAttribute(XMLConstants.BEAN))); } } } } } builder.addPropertyValue(XMLConstants.TESTS,tests); }</code><technical_language>delegate.parseIdRefElement here</technical_language>

Target:
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { super.doParse(element, parserContext, builder); element.setAttribute(BeanDefinitionParserDelegate.VALUE_TYPE_ATTRIBUTE, ProcessingConfig.Test.class.getCanonicalName()); List<Element> list = DomUtils.getChildElements(element); ManagedList tests = new ManagedList(list.size()); for (Element el : list){ if (!el.getAttribute(XMLConstants.ATTRIBUTE_REF).isEmpty()){ tests.add(new RuntimeBeanReference(el.getAttribute(XMLConstants.ATTRIBUTE_REF))); }else{ tests.add(parserContext.getDelegate().parsePropertySubElement(el, builder.getBeanDefinition())); } } builder.addPropertyValue(XMLConstants.TESTS,tests); }
Source:
<code>public String getBundleDir() { <START> if (configurationService != null) { <END> BootstrapConfig bootstrapConfig = configurationService.loadBootstrapConfig(); if (bootstrapConfig != null) { return bootstrapConfig.getMotechDir() + "/bundles"; } } return bundleDir; }</code><technical_language>configuration service null</technical_language>

Target:
public String getBundleDir() { return bundleDir; }
Source:
<code><START> V call(@Nonnull Callable<V,T> callable, @CheckForNull Duration performTimeout, @CheckForNull Duration executionTimeout) <END> throws IOException, T, InterruptedException { UserRequest<V,T> request=null; try(Timeout t = Timeout.optLimit(executionTimeout)) { request = new UserRequest<V, T>(this, callable, performTimeout, executionTimeout); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { if(request!=null) request.releaseExports(); } }</code><technical_language>I do executionTimeout is necessary. performTimeout. cares difference. A caller simply wants ensure a network call block forever</technical_language>

Target:
V call(@Nonnull Callable<V,T> callable, @CheckForNull Duration performTimeout, @CheckForNull Duration executionTimeout) throws IOException, T, InterruptedException { if (isClosingOrClosed()) { throw new ChannelClosedException("Remote call on " + name + " failed. " + "The channel is closing down or has closed down", getCloseRequestCause()); } UserRequest<V,T> request=null; try(Timeout t = Timeout.optLimit(executionTimeout)) { request = new UserRequest<V, T>(this, callable, performTimeout, executionTimeout); UserResponse<V,T> r = request.call(this); return r.retrieve(this, UserRequest.getClassLoader(callable)); } catch (ClassNotFoundException e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } catch (Error e) { IOException x = new IOException("Remote call on "+name+" failed"); x.initCause(e); throw x; } finally { if(request!=null) request.releaseExports(); } }
Source:
<code>private LineNumberRulerColumn createLineNumberRulerColumn() { LineNumberRulerColumn lnrc = new LineNumberRulerColumn() { @Override protected String createDisplayString(int line) { line -= <START> prefixeLineCount; <END> return super.createDisplayString(line); } }; lnrc.setForeground(getViewer().getTextWidget().getForeground()); lnrc.setBackground(getViewer().getTextWidget().getBackground()); return lnrc; }</code><technical_language>typo</technical_language>

Target:
private LineNumberRulerColumn createLineNumberRulerColumn() { LineNumberRulerColumn lnrc = new LineNumberRulerColumn() { @Override protected String createDisplayString(int line) { line -= prefixLineCount; return super.createDisplayString(line); } }; lnrc.setForeground(getViewer().getTextWidget().getForeground()); lnrc.setBackground(getViewer().getTextWidget().getBackground()); return lnrc; }
Source:
<code>public void testChangeTheStatusOfTheAPIToDeprecated() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.DEPRECATE.getAction()); <START> assertTrue(restAPIPublisher.getLifecycleStatus(apiId).getData().equals("Deprecated"), apiNameTest + <END> " status not updated as Deprecate"); HttpResponse deprecatedApiResponse = restAPIPublisher.getAPI(apiId); assertEquals(deprecatedApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(deprecatedApiResponse.getData().contains(apiNameTest), apiNameTest + " is not visible in " + "publisher"); }</code><technical_language>constant - APILifeCycleState.PROTOTYPED.getState() here</technical_language>

Target:
public void testChangeTheStatusOfTheAPIToDeprecated() throws Exception { restAPIPublisher.changeAPILifeCycleStatus(apiId, APILifeCycleAction.DEPRECATE.getAction()); assertTrue(APILifeCycleState.DEPRECATED.getState().equals(restAPIPublisher.getLifecycleStatus(apiId).getData()), apiNameTest + " status not updated as Deprecate"); HttpResponse deprecatedApiResponse = restAPIPublisher.getAPI(apiId); assertEquals(deprecatedApiResponse.getResponseCode(), Response.Status.OK.getStatusCode(), apiNameTest + " is not visible in publisher"); assertTrue(deprecatedApiResponse.getData().contains(apiNameTest), apiNameTest + " is not visible in " + "publisher"); }
Source:
<code>private void changeTheme() { radiotDarkBtn = (RadioButton) getView().findViewById(R.id.radiotDarkBtn); radiotLightBtn = (RadioButton)getView().findViewById(R.id.radiotLightBtn); if(Utility.getTheme(getApplicationContext()) == PhimpMe.THEME_dark) { radiotLightBtn.setChecked(false); radiotDarkBtn.setChecked(true); <START> }else { <END> radiotDarkBtn.setChecked(false); radiotLightBtn.setChecked(true); } radiotDarkBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Utility.setTheme(getApplicationContext(), 2); recreateActivity(); } }); radiotLightBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Utility.setTheme(getApplicationContext(), 1); recreateActivity(); } }); }</code><technical_language>Add space else</technical_language>

Target:
private void changeTheme() { radiotDarkBtn = (RadioButton) getView().findViewById(R.id.radiotDarkBtn); radiotLightBtn = (RadioButton)getView().findViewById(R.id.radiotLightBtn); if(Utility.getTheme(getApplicationContext()) == PhimpMe.ThemeDark) { radiotLightBtn.setChecked(false); radiotDarkBtn.setChecked(true); } else { radiotDarkBtn.setChecked(false); radiotLightBtn.setChecked(true); } radiotDarkBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Utility.setTheme(getApplicationContext(), 2); recreateActivity(); } }); radiotLightBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Utility.setTheme(getApplicationContext(), 1); recreateActivity(); } }); }
Source:
<code>private void impl$addAndApplyTradeMutators(MerchantOffers givenMerchantOffers, VillagerTrades.ITrade[] newTrades, int maxNumbers, CallbackInfo ci) { <START> if ((Object) this instanceof VillagerEntity) { <END> VillagerEntity villager = (VillagerEntity) (Object) this; SpongeVillagerRegistry.getInstance().populateOffers((Villager) this, (List<TradeOffer>) (List<?>) impl$newOffers, (Profession) villager.getVillagerData().getProfession(), villager.getVillagerData().getLevel(), this.rand); givenMerchantOffers.addAll(this.impl$newOffers); this.impl$newOffers.clear(); } }</code><technical_language>a bit of a elegant hack this: redirect do original method, override this injection method in VillagerEntityMixin do this logic doing. I do this WorldMixin_Tracker ServerWorldMixin_Tracker do extra logic server worlds for injections in subclass</technical_language>

Target:
protected void impl$addAndApplyTradeMutators(MerchantOffers givenMerchantOffers, VillagerTrades.ITrade[] newTrades, int maxNumbers, CallbackInfo ci) { }
Source:
<code>protected String doInBackground(String... params) { String fullUri = params[0] + params[1]; Log.v(TAG, "Calling Rest API at " + fullUri); if (params.length >= 5) { LinkedList<NameValuePair> urlParams = new LinkedList<>(); int paramCounter = 3; while (paramCounter + 1 < params.length) { urlParams.add(new BasicNameValuePair(params[paramCounter++], params[paramCounter++])); <START> } <END> fullUri += "?" + URLEncodedUtils.format(urlParams, HTTP.UTF_8); } for (int i = 0; i < 10; i++) { HttpClient httpclient = Https.createHttpsClient(mHttpsCertPath); HttpGet get = new HttpGet(fullUri); get.addHeader(new BasicHeader(RestApi.HEADER_API_KEY, params[2])); if (isCancelled()) return null; try { HttpResponse response = httpclient.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; String result = ""; while ((line = br.readLine()) != null) { result += line; } br.close(); Log.v(TAG, "API call result: " + result); return result; } } catch (IOException|IllegalArgumentException e) { Log.w(TAG, "Failed to call Rest API at " + fullUri, e); } try { Thread.sleep(500 * i); } catch (InterruptedException e) { Log.w(TAG, e); } Log.w(TAG, "Retrying GetTask Rest API call ("+(i+1)+"/10)"); } return null; }</code><technical_language>do for (int paramCounter = 3; paramCounter + 1 < params.length; ) here</technical_language>

Target:
protected String doInBackground(String... params) { String fullUri = params[0] + params[1]; Log.v(TAG, "Calling Rest API at " + fullUri); if (params.length >= 5) { LinkedList<NameValuePair> urlParams = new LinkedList<>(); for (int paramCounter = 3; paramCounter + 1 < params.length; ) { urlParams.add(new BasicNameValuePair(params[paramCounter++], params[paramCounter++])); } fullUri += "?" + URLEncodedUtils.format(urlParams, HTTP.UTF_8); } for (int i = 0; i < 10; i++) { HttpClient httpclient = Https.createHttpsClient(mHttpsCertPath); HttpGet get = new HttpGet(fullUri); get.addHeader(new BasicHeader(RestApi.HEADER_API_KEY, params[2])); if (isCancelled()) return null; try { HttpResponse response = httpclient.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; String result = ""; while ((line = br.readLine()) != null) { result += line; } br.close(); Log.v(TAG, "API call result: " + result); return result; } } catch (IOException|IllegalArgumentException e) { Log.w(TAG, "Failed to call Rest API at " + fullUri, e); } try { Thread.sleep(500 * i); } catch (InterruptedException e) { Log.w(TAG, e); } Log.w(TAG, "Retrying GetTask Rest API call ("+(i+1)+"/10)"); } return null; }
Source:
<code>public synchronized int decrementInstallCount() throws CoreException { int count = 0; <START> if(this.getMarker().getAttribute(MOVE_BACK_BREAKPOINT)!=null && <END> this.getMarker().getAttribute(MOVE_BACK_BREAKPOINT).equals(Boolean.TRUE)){ count = super.decrementInstallCount(); if (count == 0) { resetInstalledLocation(); } } return count; }</code><technical_language>I "if" is wrong here. more precisely, do super.decrementInstallCount() test if super.decrementInstallCount() is working expected is: 1) insert breakpoint, observe is a blue dot, check mark 2) start debug session, breakpoint change a check mark 3) Stop debug session breakpoint a dot again</technical_language>

Target:
public synchronized int decrementInstallCount() throws CoreException { int count = super.decrementInstallCount(); if(Boolean.TRUE.equals(this.getMarker().getAttribute(RESET_INSTALLED_LOCATION))){ if (count == 0) { resetInstalledLocation(); } } return count; }
Source:
<code>public void initialise() throws IOException { myRes = getDataDirectory().get("/mydir/myres"); try (OutputStreamWriter os = new OutputStreamWriter(myRes.out())) { os.append("This is my test."); } try (OutputStreamWriter os = new OutputStreamWriter(getDataDirectory().get("/mydir2/fake.png").out())) { os.append("This is not a real png file."); } IOUtils.copyStream(getClass().getResourceAsStream("testimage.png"), <START> getDataDirectory().get("/mydir2/imagewithoutextension").out(), true, true); <END> }</code><technical_language>@NielsCharlier please include non-ASCII characters in paths content. This give unit test coverage of charset handling. run Maven tests -Dfile.encoding this is set JVM default charset parsers choose if a charset is specified</technical_language>

Target:
public void initialise() throws IOException { myRes = getDataDirectory().get("/mydir/myres"); try (OutputStreamWriter os = new OutputStreamWriter(myRes.out())) { os.append(STR_MY_TEST); } try (OutputStreamWriter os = new OutputStreamWriter(getDataDirectory().get("/mydir2/fake.png").out())) { os.append("This is not a real png file."); } try (OutputStreamWriter os = new OutputStreamWriter(getDataDirectory().get("/poëzie/café").out())) { os.append("The content of this file is irrelevant."); } IOUtils.copyStream(getClass().getResourceAsStream("testimage.png"), getDataDirectory().get("/mydir2/imagewithoutextension").out(), true, true); }
Source:
<code>public ScenarioSimulationModel load(final Path path) { try { final String content = ioService.readAllString(Paths.convert(path)); final ScenarioSimulationModel scenarioSimulationModel = unmarshalInternal(content); final Simulation simulation = scenarioSimulationModel.getSimulation(); final Settings settings = scenarioSimulationModel.getSettings(); <START> if (simulation != null && DMN.equals(settings.getType())) { <END> try { dmnTypeService.initializeNameAndNamespace(settings, path, settings.getDmnFilePath()); } catch (ImpossibleToFindDMNException e) { logger.error(e.getMessage(), e); } } return scenarioSimulationModel; } catch (Exception e) { throw ExceptionUtilities.handleException(e); } }</code><technical_language>simulation != null need part of a condition? variable in guarded blovk. double checking</technical_language>

Target:
public ScenarioSimulationModel load(final Path path) { try { final String content = ioService.readAllString(Paths.convert(path)); final ScenarioSimulationModel scenarioSimulationModel = unmarshalInternal(content); final Settings settings = scenarioSimulationModel.getSettings(); if (settings != null && DMN.equals(settings.getType())) { try { dmnTypeService.initializeNameAndNamespace(settings, path, settings.getDmnFilePath()); } catch (ImpossibleToFindDMNException e) { logger.error(e.getMessage(), e); } } return scenarioSimulationModel; } catch (Exception e) { throw ExceptionUtilities.handleException(e); } }
Source:
<code>Point getScreenDPI () { <START> int dpi = getDeviceZoom() * 96 / 100; <END> return new Point (dpi, dpi); }</code><technical_language>move DPI calculation logic getScreenDPI() call getScreenDPI getDeviceZoom(), end number of calculations</technical_language>

Target:
Point getScreenDPI () { long screen = GDK.gdk_screen_get_default(); int dpi = (int) GDK.gdk_screen_get_resolution (screen); if (dpi <= 0) dpi = 96; if (GTK.GTK_VERSION > OS.VERSION(3, 9, 0)) { int monitor_num = GDK.gdk_screen_get_monitor_at_point (screen, 0, 0); int scale = GDK.gdk_screen_get_monitor_scale_factor (screen, monitor_num); dpi = dpi * scale; } return new Point (dpi, dpi); }
Source:
<code>private void silentDestroy() { LOGGER.debug("Found a broken ClusterTierManager - trying to clean it up"); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { entityFactory.destroy(entityIdentifier); } catch (EntityBusyException e) { LOGGER.debug("ClusterTierManager marked busy when trying to clean it up", entityIdentifier); } catch (ConnectionClosedException | ConnectionShutdownException e) { <START> throw e; <END> } }</code><technical_language>catch, if gonna rethow it</technical_language>

Target:
private void silentDestroy() { LOGGER.debug("Found a broken ClusterTierManager - trying to clean it up"); try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { entityFactory.destroy(entityIdentifier); } catch (EntityBusyException e) { LOGGER.debug("ClusterTierManager marked busy when trying to clean it up", entityIdentifier); } }
Source:
<code>public Datacenter findDatacenter(String datacenterName) { for (Datacenter datacenter : datacenters) { if (datacenter.getName().equals(datacenterName)) { <START> return datacenter; <END> } } return null; }</code><technical_language>Do want do case insensitive comparison</technical_language>

Target:
public Datacenter findDatacenter(String datacenterName) { for (Datacenter datacenter : datacenters) { if (datacenter.getName().compareToIgnoreCase(datacenterName) == 0) { return datacenter; } } return null; }
Source:
<code>private static URL makeURL(@Nonnull ZipFile file, @Nonnull ZipEntry entry, @Nonnull ZipURLStreamHandler handler) { try { assert entry.getName().indexOf(DASH) == -1; return new <START> URL("ziploader", <END> "", -1, file.getName() + DASH + entry.getName(), handler); } catch (MalformedURLException e) { throw new AssertionError(); } }</code><technical_language>need else</technical_language>

Target:
private static URL makeURL(@Nonnull ZipFile file, @Nonnull ZipEntry entry, @Nonnull ZipURLStreamHandler handler) { try { assert entry.getName().indexOf(BANG) == -1; return new URL("ziploader", "", -1, file.getName() + BANG + entry.getName(), handler); } catch (MalformedURLException e) { throw new AssertionError(); } }
Source:
<code>boolean await(long delay, TimeUnit unit) throws InterruptedException; @Deprecated default void onShutdown() { <START> throw new AssertionError("deprecated API, should not be invoked"); <END> }</code><technical_language>new AssertionError -> new UnsupportedOperationException</technical_language>

Target:
boolean await(long delay, TimeUnit unit) throws InterruptedException; @Deprecated default void onShutdown() { throw new UnsupportedOperationException("deprecated API, should not be invoked"); }
Source:
<code><START> public static boolean isAccessibleFrom( <END> @Nonnull JDefinedClassOrInterface type, @Nonnull JDefinedClassOrInterface accessor) { if (type.getEnclosingPackage() == accessor.getEnclosingPackage()) { return true; } JClassOrInterface enclosingType = type.getEnclosingType(); if (enclosingType == null) { return JModifier.isPublic(type.getModifier()); } if (!JModifier.isPublic(type.getModifier()) && !JModifier.isProtected(type.getModifier())) { return false; } assert enclosingType instanceof JDefinedClassOrInterface; return isAccessibleFrom((JDefinedClassOrInterface) enclosingType, accessor); }</code><technical_language>shortcut if type.isSameType(accessor) ? do call if is case for AccessibilityChecker</technical_language>

Target:
public static boolean isAccessibleFrom( @Nonnull JDefinedClassOrInterface type, @Nonnull JDefinedClassOrInterface accessor) { if (type.isSameType(accessor) || type.getEnclosingPackage() == accessor.getEnclosingPackage()) { return true; } JClassOrInterface enclosingType = type.getEnclosingType(); if (enclosingType == null) { return JModifier.isPublic(type.getModifier()); } if (!JModifier.isPublic(type.getModifier()) && !JModifier.isProtected(type.getModifier())) { return false; } assert enclosingType instanceof JDefinedClassOrInterface; return isAccessibleFrom((JDefinedClassOrInterface) enclosingType, accessor); }
Source:
<code>@Nullable public String getTokenURL() { for (FormGroup formGroup : form) { <START> for (FormField formField : formGroup.getFields()) { <END> String fieldId = formField.getId(); Object value = formField.getValue(); if (fieldId.equals("tokenURL") && value != null && value.toString().endsWith("/token")) { return value.toString().substring(0, value.toString().length() - "/token".length()); } } } return null; }</code><technical_language>careful of nullable fields</technical_language>

Target:
@Nullable public String getTokenURL() { for (FormGroup formGroup : form) { for (FormField formField : formGroup.getFields()) { String fieldId = formField.getId(); Object value = formField.getValue(); if (FormField.TOKEN_URL.equals(fieldId) && value != null && value.toString().endsWith("/token")) { return value.toString().substring(0, value.toString().length() - "/token".length()); } } } return null; }
Source:
<code>public void mergeStatisticsMinMax(Statistics stats) { BinaryStatistics binaryStats = (BinaryStatistics)stats; if (!this.hasNonNullValue()) { initializeStats(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); <START> initializeStats(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); <END> } else { updateStats(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); updateStats(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } }</code><technical_language>in initStats setting 4 values right? this result in minUnsigned & maxUnsigned for 4</technical_language>

Target:
public void mergeStatisticsMinMax(Statistics stats) { BinaryStatistics binaryStats = (BinaryStatistics)stats; if (!this.hasNonNullValue()) { initializeStatsSigned(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); initializeStatsUnsigned(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } else { updateStatsSigned(binaryStats.genericGetMinSigned(), binaryStats.genericGetMaxSigned()); updateStatsUnsigned(binaryStats.genericGetMinUnsigned(), binaryStats.genericGetMaxUnsigned()); } }
Source:
<code>public ClientPolicy(int retryTimeOut, int retryNumber, int incomingHeartbeat, int outgoingHeartbeat, List<Class<? extends Exception>> retryableExceptions) { this(retryTimeOut, retryNumber, incomingHeartbeat, outgoingHeartbeat, retryableExceptions, <START> null); <END> }</code><technical_language>Do pass null. I setter getter instead of updating constructors</technical_language>

Target:
public ClientPolicy(int retryTimeOut, int retryNumber, int incomingHeartbeat, int outgoingHeartbeat, List<Class<? extends Exception>> retryableExceptions) { this.retryNumber = retryNumber; this.retryTimeOut = retryTimeOut; setIncomingHeartbeat(incomingHeartbeat); setOutgoingHeartbeat(outgoingHeartbeat); this.exceptions = Collections.unmodifiableList(retryableExceptions); }
Source:
<code>public Void doInBackground(String... urls) { boolean sendMore = true; try { <START> while (sendMore) { <END> sendMore = sendData(); } } finally { wakeLock.release(); lockCounter--; Log.e(TAG,"MongosendTask wakelock released " + lockCounter); } return null; }</code><technical_language>This lead aggressively uploading data block internet connection lead additional costs if online out of house check a website. service starts this task called minutes is need continue. A function upload month of data triggered user (Button in menu settings e.g.) leas check this happen mobile data Wifi</technical_language>

Target:
public Void doInBackground(String... urls) { try { sendData(); } finally { wakeLock.release(); lockCounter--; Log.e(TAG,"MongosendTask wakelock released " + lockCounter); } return null; }
Source:
<code>public void postCollectionSubmittersGroupCreateSubmittersGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); <START> <END> }</code><technical_language>double check group created</technical_language>

Target:
public void postCollectionSubmittersGroupCreateSubmittersGroupForbidden() throws Exception { ObjectMapper mapper = new ObjectMapper(); GroupRest groupRest = new GroupRest(); MetadataRest metadataRest = new MetadataRest(); metadataRest.put("dc.description", new MetadataValueRest("testingDescription")); metadataRest.put("dc.subject", new MetadataValueRest("testSubject")); groupRest.setMetadata(metadataRest); String token = getAuthToken(eperson.getEmail(), password); getClient(token).perform(post("/api/core/collections/" + collection.getID() + "/submittersGroup") .content(mapper.writeValueAsBytes(groupRest)) .contentType(contentType)) .andExpect(status().isForbidden()); token = getAuthToken(admin.getEmail(), password); getClient(token).perform(get("/api/core/collections/" + collection.getID() + "/submittersGroup")) .andExpect(status().isNoContent()); }
Source:
<code>public <T> T getService(Class<T> clazz) { if (services.containsKey(clazz)) { return (T) services.get(clazz); } try { return clazz.newInstance(); <START> } catch (Exception e) <END> return null; }</code><technical_language>silent catch</technical_language>

Target:
public <T> T getService(Class<T> clazz) { if (services.containsKey(clazz)) { return (T) services.get(clazz); } try { return clazz.newInstance(); } catch (Exception e) { log.warn("Didn't manage to create an instance of {}", clazz, e); } return null; }
Source:
<code>CompletableFuture<ReadBatch> readRecords(TransferBatchRequest transferBatchRequest) { return CompletableFuture.supplyAsync(() -> { Optional<ReadBatchException> latestReadException = Optional.empty(); Optional<ReadBatch> latestReadBatch = Optional.empty(); for (int i = 0; i < maxReadRetries; i++) { try { Map<Long, ILogData> records = addressSpaceView.simpleProtocolRead( <START> ImmutableList.copyOf(transferBatchRequest.getAddresses()), readOptions); ReadBatch batch = checkReadRecords( ImmutableList.copyOf(transferBatchRequest.getAddresses()), <END> records, Optional.empty()); latestReadBatch = Optional.of(batch); if (batch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + batch.getFailedAddresses()); } else { latestReadException = Optional.empty(); break; } } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: ", i, e); latestReadException = Optional.of(new ReadBatchException(e)); break; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: ", i, e); latestReadException = Optional.of(new ReadBatchException(e)); Sleep.sleepUninterruptibly(readSleepDuration); } } if (latestReadException.isPresent()) { throw latestReadException.get(); } else { return latestReadBatch.get(); } }); }</code><technical_language>I need get rid of copying addresses time for read checkReadRecords</technical_language>

Target:
CompletableFuture<ReadBatch> readRecords(TransferBatchRequest transferBatchRequest) { return CompletableFuture.supplyAsync(() -> { for (int i = 0; i < maxReadRetries; i++) { try { Map<Long, ILogData> records = addressSpaceView.simpleProtocolRead( transferBatchRequest.getAddresses(), readOptions); ReadBatch batch = checkReadRecords( transferBatchRequest.getAddresses(), records, Optional.empty()); if (batch.getStatus() == ReadBatch.ReadStatus.FAILED) { throw new IllegalStateException("Some addresses failed to transfer: " + batch.getFailedAddresses()); } return batch; } catch (WrongEpochException e) { log.warn("readRecords: encountered a wrong epoch exception on try {}: {}.", i, e); throw e; } catch (RuntimeException e) { log.warn("readRecords: encountered an exception on try {}: {}.", i, e); Sleep.sleepUninterruptibly(readSleepDuration); } } throw new ReadBatchException("readRecords: read retries were exhausted"); }); }
Source:
<code>private static EtdSettlementType parseEtdSettlementType(String str) { String upper = str.toUpperCase(Locale.ENGLISH); Map<String, EtdSettlementType> valuesByCode = <START> Stream.of(EtdSettlementType.values()).collect(toImmutableMap(EtdSettlementType::getCode)); <END> EtdSettlementType fromCode = valuesByCode.get(upper); return fromCode != null ? fromCode : EtdSettlementType.of(str); }</code><technical_language>store a static version of this map recreating time method is called</technical_language>

Target:
private static EtdSettlementType parseEtdSettlementType(String str) { String upper = str.toUpperCase(Locale.ENGLISH); EtdSettlementType fromCode = SETTLEMENT_BY_CODE.get(upper); return fromCode != null ? fromCode : EtdSettlementType.of(str); }