auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void processStream(final KafkaReporter kafkaReporter, FlinkBenchConfig config) throws Exception{ createDataStream(config); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Tuple2<String, String>> dataStream = env.addSource(getDataStream()); dataStream.rebalance().map((new MapFunction<Tuple2<String, String>, Tuple2<String, String>>() { @Override public Tuple2<String, String> map(Tuple2<String, String> value) throws Exception { kafkaReporter.report(Long.parseLong(value.f0), System.currentTimeMillis()); return value; } })); <START> env.execute("Identity job"); <END> }</code><technical_language>repartition job</technical_language>

Target:
public void processStream(final KafkaReporter kafkaReporter, FlinkBenchConfig config) throws Exception{ createDataStream(config); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<Tuple2<String, String>> dataStream = env.addSource(getDataStream()); dataStream.rebalance().map((new MapFunction<Tuple2<String, String>, Tuple2<String, String>>() { @Override public Tuple2<String, String> map(Tuple2<String, String> value) throws Exception { kafkaReporter.report(Long.parseLong(value.f0), System.currentTimeMillis()); return value; } })); env.execute("Repartition job"); }
Source:
<code>private void revokeAccessToken() { <START> URI ssoRevokeURI = null; if (ssoRevokeUrl != null) { ssoRevokeURI = SsoUtils.buildUrl(ssoRevokeUrl); } else { if (ssoToken != null) { ssoRevokeURI = SsoUtils.buildSsoRevokeUrl(url, ssoToken); } } <END> if (ssoRevokeURI != null) { JsonNode node = getSsoResponse(ssoRevokeURI); if (node.isArray()) { node = node.get(0); } if (node.get("error") != null) { throw new RuntimeException( String.format( "Error during SSO token revoke %1$s : %2$s", node.get("error_code"), node.get("error") ) ); } } }</code><technical_language>shortened URI ssoRevokeURI = ssoRevokeUrl != null ? SsoUtils.buildUrl(ssoRevokeUrl) : ssoToken != null ? soUtils.buildSsoRevokeUrl(url, ssoToken) : null;</technical_language>

Target:
private void revokeAccessToken() { URI ssoRevokeURI = ssoRevokeUrl != null ? SsoUtils.buildUrl(ssoRevokeUrl) : ssoToken != null ? SsoUtils.buildSsoRevokeUrl(url, ssoToken) : null; if (ssoRevokeURI != null) { JsonNode node = getSsoResponse(ssoRevokeURI); if (node.isArray()) { node = node.get(0); } if (node.get("error") != null) { throw new RuntimeException( String.format( "Error during SSO token revoke %1$s : %2$s", node.get("error_code"), node.get("error") ) ); } } }
Source:
<code>private static void calculate(CalculationRunner runner) { CdsTrade cds = createSingleNameCds(); List<Trade> trades = ImmutableList.of(cds); List<Column> columns = ImmutableList.of( Column.of(Measures.PRESENT_VALUE)); <START> LocalDate valuationDate = LocalDate.of(2014, 10, 16); <END> ImmutableMarketDataBuilder baseMarketDataBuilder = ImmutableMarketData.builder(valuationDate); loadBaseYieldCurves(baseMarketDataBuilder); loadBaseSingleNameCreditCurves(baseMarketDataBuilder); ImmutableMarketData baseMarketData = baseMarketDataBuilder.build(); ScenarioDefinition scenarios = buildScenarios(baseMarketData); CalculationFunctions functions = StandardComponents.calculationFunctions(); CalculationRules rules = CalculationRules.of(functions); ReferenceData refData = ReferenceData.standard(); MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData); ScenarioMarketData scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), baseMarketData, refData, scenarios); Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData); CurrencyValuesArray pvVector = (CurrencyValuesArray) results.get(0, 0).getValue(); outputCurrencyValues("PVs", pvVector); CurrencyValuesArray pnlVector = getSortedPnls(pvVector); outputCurrencyValues("Scenario PnLs", pnlVector); double var95 = SampleInterpolationQuantileMethod.DEFAULT.quantileFromUnsorted(0.05, pnlVector.getValues()); System.out.println(Messages.format("95% VaR: {}", var95)); }</code><technical_language>clearer a local method create baseMarketData()</technical_language>

Target:
private static void calculate(CalculationRunner runner) { CdsTrade cds = createSingleNameCds(); List<Trade> trades = ImmutableList.of(cds); List<Column> columns = ImmutableList.of( Column.of(Measures.PRESENT_VALUE)); ImmutableMarketData baseMarketData = buildBaseMarketData(); ScenarioDefinition scenarios = buildScenarios(baseMarketData); CalculationFunctions functions = StandardComponents.calculationFunctions(); CalculationRules rules = CalculationRules.of(functions); ReferenceData refData = ReferenceData.standard(); MarketDataRequirements reqs = MarketDataRequirements.of(rules, trades, columns, refData); ScenarioMarketData scenarioMarketData = marketDataFactory().createMultiScenario(reqs, MarketDataConfig.empty(), baseMarketData, refData, scenarios); Results results = runner.calculateMultiScenario(rules, trades, columns, scenarioMarketData, refData); CurrencyValuesArray pvVector = (CurrencyValuesArray) results.get(0, 0).getValue(); outputCurrencyValues("PVs", pvVector); CurrencyValuesArray pnlVector = getSortedPnls(pvVector); outputCurrencyValues("Scenario PnLs", pnlVector); double var95 = SampleInterpolationQuantileMethod.DEFAULT.quantileFromSorted(0.05, pnlVector.getValues()); System.out.println(Messages.format("95% VaR: {}", var95)); }
Source:
<code>HttpResponse sendGetRequest(URI backupUri) { HttpResponse httpResponse = null; HttpGet get = new HttpGet(backupUri); HttpClient client = httpBuilder.get().build(); try { LOGGER.debug("Sending request to {}", backupUri); httpResponse = client.execute(get); } catch (IOException e) { <START> LOGGER.debug("Error during request. Returning null response."); <END> } return httpResponse; }</code><technical_language>Include exception e in logging message</technical_language>

Target:
HttpResponse sendGetRequest(URI backupUri) { HttpResponse httpResponse = null; HttpGet get = new HttpGet(backupUri); HttpClient client = httpBuilder.get().build(); try { LOGGER.debug("Sending request to {}", backupUri); httpResponse = client.execute(get); } catch (IOException e) { LOGGER.debug("Error during request. Returning null response.", e); } return httpResponse; }
Source:
<code>protected static boolean createDirectoryIfNotExist(Path path) { File dir = path.toFile(); if(!dir.exists()) { <START> if(!dir.mkdir()) <END> { logger.warn("Was unable to make a directory called " + dir); return false; } } if(dir.exists() && !dir.isDirectory()) { logger.warn("Was unable to make a directory because" + " there is a file called " + dir); return false; } return true; }</code><technical_language>mkdirs</technical_language>

Target:
protected static boolean createDirectoryIfNotExist(Path path) { File dir = path.toFile(); if(!dir.exists()) { if(!dir.mkdirs()) { logger.warn("Was unable to make a directory called " + dir); return false; } } if(dir.exists() && !dir.isDirectory()) { logger.warn("Was unable to make a directory because" + " there is a file called " + dir); return false; } return true; }
Source:
<code>public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); this.targetContentEncoding = targetContentEncoding; <START> this.contentEncoder = contentEncoder; <END> }</code><technical_language>nit: merge lines checkNotNull return argument</technical_language>

Target:
public Result(String targetContentEncoding, EmbeddedChannel contentEncoder) { this.targetContentEncoding = ObjectUtil.checkNotNull(targetContentEncoding, "targetContentEncoding"); this.contentEncoder = ObjectUtil.checkNotNull(contentEncoder, "contentEncoder"); }
Source:
<code>public void testComparePercentVerificationBetweenTwoSets() { Buffer buffer = (Buffer) store; <START> buffer.start(); <END> List<Write> stored1 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); List<Write> stored2 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); int initialSize = stored2.size(); Random rand = new Random(); int transferSize = rand.nextInt(stored1.size()); for(int i = 0; i < transferSize; i++) { stored2.add(stored1.get(i)); } Iterator<Write> iterator = stored2.iterator(); while(iterator.hasNext()) { buffer.verifyFast(iterator.next()); } float percentVerifyScans = Reflection.call(buffer, "getPercentVerifyScans"); float percentTransferred = ((float) transferSize) / (transferSize + initialSize); Assert.assertTrue(percentVerifyScans >= percentTransferred); }</code><technical_language>manually start buffer. test framework automatically</technical_language>

Target:
public void testComparePercentVerificationBetweenTwoSets() { Buffer buffer = (Buffer) store; List<Write> stored1 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); List<Write> stored2 = addRandomElementsToBufferAndList(buffer, TestData.getScaleCount()); int initialSize = stored2.size(); Random rand = new Random(); int transferSize = rand.nextInt(stored1.size()); for(int i = 0; i < transferSize; i++) { stored2.add(stored1.get(i)); } Iterator<Write> iterator = stored2.iterator(); while(iterator.hasNext()) { Write write = iterator.next(); buffer.verify(write.getKey().toString(), write.getValue().getTObject(), write.getRecord().longValue()); } float percentVerifyScans = Reflection.call(buffer, "getPercentVerifyScans"); float percentTransferred = ((float) transferSize) / (transferSize + initialSize); Assert.assertTrue(percentVerifyScans >= percentTransferred); }
Source:
<code>public static GoExpression getExpression(@NotNull GoIndexOrSliceExpr slice) { List<GoExpression> leftExpressions = getExpressionsBefore(slice.getExpressionList(), slice.getLbrack()); <START> return leftExpressions.isEmpty() ? null : leftExpressions.get(0); <END> }</code><technical_language>ContainerUtil#getFirstItem</technical_language>

Target:
public static GoExpression getExpression(@NotNull GoIndexOrSliceExpr slice) { List<GoExpression> leftExpressions = getExpressionsBefore(slice.getExpressionList(), slice.getLbrack()); return ContainerUtil.getFirstItem(leftExpressions); }
Source:
<code>public void close() throws Exception { try { if (jobBundleFactory != null) { jobBundleFactory.close(); } } finally { jobBundleFactory = null; } try { if (sharedResources != null) { <START> sharedResources.close(); <END> } } finally { sharedResources = null; } environmentManager.close(); }</code><technical_language>suggestion sharedResources.close();</technical_language>

Target:
public void close() throws Exception { try { if (jobBundleFactory != null) { jobBundleFactory.close(); } } finally { jobBundleFactory = null; } try { if (sharedResources != null) { if (sharedResources.getResourceHandle().release()) { sharedResources.close(); } } else { environmentManager.close(); } } finally { sharedResources = null; } }
Source:
<code>public Long getLastUpdateTime() { <START> String rval = (String) globalSettings.get( <END> GlobalSettingsKey.JTTP_PLUGIN_SETTINGS_KEY_PREFIX + GlobalSettingsKey.JTTP_UPDATE_NOTIFIER_LAST_UPDATE); return rval == null ? null : Long.parseLong(rval); }</code><technical_language>more talkative temp variable name</technical_language>

Target:
public Long getLastUpdateTime() { String lastUpdateInMilisec = (String) globalSettings.get( GlobalSettingsKey.JTTP_PLUGIN_SETTINGS_KEY_PREFIX + GlobalSettingsKey.JTTP_UPDATE_NOTIFIER_LAST_UPDATE); return lastUpdateInMilisec == null ? null : Long.parseLong(lastUpdateInMilisec); }
Source:
<code>public List<BusinessService> search(BusinessServiceSearchCriteria businessServiceSearchCriteria) { <START> if (businessServiceSearchCriteria == null) { <END> throw new IllegalArgumentException("Search criteria must not be null"); } return businessServiceSearchCriteria.apply(this, getAllBusinessServices()); }</code><technical_language>Please Objects.requireNonNull(businessSearchCriteria)</technical_language>

Target:
public List<BusinessService> search(BusinessServiceSearchCriteria businessServiceSearchCriteria) { Objects.requireNonNull(businessServiceSearchCriteria); return businessServiceSearchCriteria.apply(this, getAllBusinessServices()); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent i = getParentActivityIntent().putExtra("forceMainMenu", true); <START> navigateUpTo(i); <END> return super.onOptionsItemSelected(item); case R.id.display_parameters: AnalyticsHelper.sendEventHit("Filters", AnalyticsHelper.CLICK, "YES"); createDialog(); default: return super.onOptionsItemSelected(item); } }</code><technical_language>button works for in current app? Is a bug I about</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent i = getParentActivityIntent().putExtra("forceMainMenu", true); NavUtils.navigateUpTo(this, i); return super.onOptionsItemSelected(item); case R.id.display_parameters: AnalyticsHelper.sendEventHit("Filters", AnalyticsHelper.CLICK, "YES"); createDialog(); default: return super.onOptionsItemSelected(item); } }
Source:
<code>private List<Activity> buildActivities(List<WebElement> activities) { activities.forEach(element -> this.activities.add(new Activity(element))); <START> return this.activities; <END> }</code><technical_language>this method works a field, returns field result of this method is assigned field. this equivalent? return activities.map(Activity::new).collect(Collectors.toList());</technical_language>

Target:
private List<Activity> buildActivities(List<WebElement> activities) { return activities.stream().map(Activity::new).collect(Collectors.toList()); }
Source:
<code>public String toString() { <START> if (script != null) { return "" + new String(getHash()) + "\n" + script; } else { return "" + new String(getHash()) + "\n" + url; } <END> }</code><technical_language>replaced by: return script != null ? "" + new String(getHash()) + "\n" + script : "" + new String(getHash()) + "\n" + url;</technical_language>

Target:
public String toString() { return "" + new String(getHash()) + "\n" + (script != null ? script : url); }
Source:
<code>public InputStream createInputStream(long offset) throws IOException { if (doesExist()) { return file.createInputStream(); } <START> StorageUtils.LOG.FINE("Reading file '%s'", childName); <END> return new ByteArrayInputStream(EMPTY_BUFFER); }</code><technical_language>suggestion StorageUtils.LOG.FINE("Layer3/FTP: Downloading file '%s' '%s'", childName, parent);</technical_language>

Target:
public InputStream createInputStream(long offset) throws IOException { if (doesExist()) { return file.createInputStream(); } StorageUtils.LOG.FINE("Layer3/FTP: Downloading file '%s' from '%s'", childName, parent); return new ByteArrayInputStream(EMPTY_BUFFER); }
Source:
<code>public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) { this.context = context; this.attrs = attributeSet; this.defStyle = defStyle; if (attributeSet != null) { key = attributeSet.getAttributeValue(ResourceLoader.ANDROID_NS, "key"); <START> if (key != null && key.startsWith("@")) { <END> final ResourceLoader resourceLoader = shadowOf(context.getResources()).getResourceLoader(); key = resourceLoader.getValue(new ResName(key.replace("@", "")), "").asString(); } } }</code><technical_language>This a strange place for this. string reference resolved resource loader</technical_language>

Target:
public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) { this.context = context; this.attrs = attributeSet; this.defStyle = defStyle; if (attributeSet != null) { final TypedArray typedArray = context.obtainStyledAttributes(attributeSet, com.android.internal.R.styleable.Preference); key = typedArray.getString(com.android.internal.R.styleable.Preference_key); } }
Source:
<code>public void setShouldRecognizeText(boolean shouldRecognizeText) { <START> if (shouldRecognizeText && !mTextRecognizer) { <END> setupTextRecongnizer(); } this.mShouldRecognizeText = shouldRecognizeText; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }</code><technical_language>mTextRecognizer == null</technical_language>

Target:
public void setShouldRecognizeText(boolean shouldRecognizeText) { if (shouldRecognizeText && mTextRecognizer == null) { setupTextRecongnizer(); } this.mShouldRecognizeText = shouldRecognizeText; setScanning(mShouldDetectFaces || mShouldDetectBarcodes || mShouldScanBarCodes || mShouldRecognizeText); }
Source:
<code>public void handleUnimprovedMinutesSpentInputChange( ChangeEvent event ) { try { Long value = unimprovedMinutesSpentInput.getValue().isEmpty() ? null : Long.parseLong( unimprovedMinutesSpentInput.getValue() ); presenter.onUnimprovedMinutesSpentChange( value ); } catch ( NumberFormatException e ) { <START> <END> } }</code><technical_language>Likewise.</technical_language>

Target:
public void handleUnimprovedMinutesSpentInputChange( ChangeEvent event ) { boolean isNumeric = unimprovedMinutesSpentInput.getValue().matches( "\\d+" ); if (isNumeric) { presenter.onUnimprovedMinutesSpentChange( Long.parseLong( unimprovedMinutesSpentInput.getValue() ) ); } else { presenter.onUnimprovedMinutesSpentChange( 0l ); unimprovedMinutesSpentInput.setValue( "0" ); } }
Source:
<code>public void before() { super.before(); super.tableEnv().executeSql(String.format( "create table orcFilterTable (" + "x string," + "y int," + "a int," + "b bigint," + "c boolean," + <START> "d string" + <END> ") with (" + "'connector' = 'filesystem'," + "'path' = '%s'," + "%s)", super.resultPath(), String.join(",\n", formatProperties()))); }</code><technical_language>is add timestamp, date, decimal too</technical_language>

Target:
public void before() { super.before(); super.tableEnv().executeSql(String.format( "create table orcFilterTable (" + "x string," + "y int," + "a int," + "b bigint," + "c boolean," + "d string," + "e decimal(8,4)," + "f date," + "g timestamp" + ") with (" + "'connector' = 'filesystem'," + "'path' = '%s'," + "%s)", super.resultPath(), String.join(",\n", formatProperties()))); }
Source:
<code>public ITimeEvent splitAfter(long splitTime) { <START> throw new UnsupportedOperationException(); <END> }</code><technical_language>return (splitTime < fTime + fDuration ? new TimeEvent(fEntry, Math.max(fTime, splitTime), fDuration - Math.max(0, splitTime - fTime)) : null);</technical_language>

Target:
public ITimeEvent splitAfter(long splitTime) { return (splitTime < fTime + fDuration ? new TimeEvent(getEntry(), Math.max(fTime, splitTime), fDuration - Math.max(0, splitTime - fTime)) : null); }
Source:
<code><START> public ClassLoader buildClassLoader() { <END> String baseDirectoryPath = System.getProperty("user.dir"); File apiLibDirectory = libDirectory(new File(baseDirectoryPath, IsolationUtils.APPLICATION_MASTER_API_DIRECTORY)); LOG.info("Using API lib directory: {}", apiLibDirectory); File infrastructureLibDirectory = libDirectory(new File(baseDirectoryPath, IsolationUtils.APPLICATION_MASTER_INFRASTRUCTURE_DIRECTORY)); LOG.info("Using infrastructure lib directory: {}", infrastructureLibDirectory); File applicationLibDirectory = libDirectory(new File(baseDirectoryPath, IsolationUtils.APPLICATION_MASTER_APPLICATION_DIRECTORY)); LOG.info("Using application lib directory: {}", applicationLibDirectory); ClassLoader apiClassLoader = buildApiClassLoader(apiLibDirectory); ClassLoader applicationClassLoader = buildApplicationClassLoader(applicationLibDirectory, apiLibDirectory, apiClassLoader); return buildInfrastructureClassLoader(infrastructureLibDirectory, apiLibDirectory, apiClassLoader, applicationClassLoader); }</code><technical_language>Do need create a singleton is OK call this multiple times</technical_language>

Target:
public ClassLoader buildClassLoader() { String baseDirectoryPath = System.getProperty("user.dir"); File apiLibDirectory = libDirectory(new File(baseDirectoryPath, DependencyIsolationUtils.FRAMEWORK_API_DIRECTORY)); LOG.info("Using API lib directory: {}", apiLibDirectory); File infrastructureLibDirectory = libDirectory(new File(baseDirectoryPath, DependencyIsolationUtils.FRAMEWORK_INFRASTRUCTURE_DIRECTORY)); LOG.info("Using infrastructure lib directory: {}", infrastructureLibDirectory); File applicationLibDirectory = libDirectory(new File(baseDirectoryPath, DependencyIsolationUtils.APPLICATION_DIRECTORY)); LOG.info("Using application lib directory: {}", applicationLibDirectory); ClassLoader apiClassLoader = buildApiClassLoader(apiLibDirectory); ClassLoader applicationClassLoader = buildApplicationClassLoader(applicationLibDirectory, apiLibDirectory, apiClassLoader); return buildInfrastructureClassLoader(infrastructureLibDirectory, apiLibDirectory, apiClassLoader, applicationClassLoader); }
Source:
<code>public void onItemClick(AdapterView<?> adapterView, View view, int position, long listId) { SnapshotMetadata selected = (SnapshotMetadata) adapterView.getItemAtPosition(position); Intent intent = new Intent(Intent.ACTION_DEFAULT); <START> intent.putExtra(SNAPSHOT_METADATA, ( selected).freeze()); <END> if (mConflictId != null) { intent.putExtra(CONFLICT_ID, mConflictId); intent.putExtra(RETRY_COUNT, mRetryCount); } setResult(RESULT_OK, intent); finish(); }</code><technical_language>Strange parentheses ( selected), this a cast before</technical_language>

Target:
public void onItemClick(AdapterView<?> adapterView, View view, int position, long listId) { SnapshotMetadata selected = (SnapshotMetadata) adapterView.getItemAtPosition(position); Intent intent = new Intent(Intent.ACTION_DEFAULT); intent.putExtra(SNAPSHOT_METADATA, selected.freeze()); if (mConflictId != null) { intent.putExtra(CONFLICT_ID, mConflictId); intent.putExtra(RETRY_COUNT, mRetryCount); } setResult(RESULT_OK, intent); finish(); }
Source:
<code>private static Set<StagingEntry.Action> getAvailableActions(IStructuredSelection selection) { Set<StagingEntry.Action> availableActions = EnumSet.noneOf(StagingEntry.Action.class); for (Iterator it = selection.iterator(); it.hasNext(); ) { StagingEntry stagingEntry = (StagingEntry) it.next(); <START> if (availableActions.isEmpty()) { <END> availableActions.addAll(stagingEntry.getAvailableActions()); } else { availableActions.retainAll(stagingEntry.getAvailableActions()); } } return availableActions; }</code><technical_language>style nit: curly braces single line blocks</technical_language>

Target:
private static Set<StagingEntry.Action> getAvailableActions(IStructuredSelection selection) { Set<StagingEntry.Action> availableActions = EnumSet.noneOf(StagingEntry.Action.class); for (Iterator it = selection.iterator(); it.hasNext(); ) { StagingEntry stagingEntry = (StagingEntry) it.next(); if (availableActions.isEmpty()) availableActions.addAll(stagingEntry.getAvailableActions()); else availableActions.retainAll(stagingEntry.getAvailableActions()); } return availableActions; }
Source:
<code><START> public void setAvailability(AvailabilityMode availability) { <END> if (partitionHandlingManager != null) { try { localTopologyManager.setCacheAvailability(getName(), availability); } catch (Exception e) { throw new CacheException(e); } } }</code><technical_language>@Override is missing</technical_language>

Target:
public void setAvailability(AvailabilityMode availability) { if (localTopologyManager != null) { try { localTopologyManager.setCacheAvailability(getName(), availability); } catch (Exception e) { throw new CacheException(e); } } }
Source:
<code>public void testCheckOutEvictCheckOut() throws Exception { Service service = mock(Service.class); when(_factory.create(any(ServiceEndPoint.class))).thenReturn(service); MultiThreadedClientServiceCache<Service> cache = newCache(0); ServiceHandle<Service> handle = cache.checkOut(_endPoint); <START> assertSame(handle.getService(), service); <END> assertSame(1, cache.getNumActiveInstances(_endPoint)); assertSame(1, cache.getNumIdleInstances(_endPoint)); cache.evict(_endPoint); verify(_factory, timeout(100).times(1)).destroy(_endPoint, handle.getService()); assertSame(0, cache.getNumActiveInstances(_endPoint)); assertSame(0, cache.getNumIdleInstances(_endPoint)); handle = cache.checkOut(_endPoint); assertSame(handle.getService(), service); assertSame(1, cache.getNumActiveInstances(_endPoint)); assertSame(1, cache.getNumIdleInstances(_endPoint)); }</code><technical_language>argument order</technical_language>

Target:
public void testCheckOutEvictCheckOut() throws Exception { Service service = mock(Service.class); when(_factory.create(any(ServiceEndPoint.class))).thenReturn(service); MultiThreadedClientServiceCache<Service> cache = newCache(0); ServiceHandle<Service> handle1 = cache.checkOut(_endPoint); assertSame(service, handle1.getService()); assertEquals(1, cache.getNumActiveInstances(_endPoint)); assertEquals(1, cache.getNumIdleInstances(_endPoint)); cache.evict(_endPoint); verify(_factory, timeout(100).times(1)).destroy(_endPoint, handle1.getService()); assertEquals(0, cache.getNumActiveInstances(_endPoint)); assertEquals(0, cache.getNumIdleInstances(_endPoint)); ServiceHandle<Service> handle2 = cache.checkOut(_endPoint); assertSame(service, handle2.getService()); assertEquals(1, cache.getNumActiveInstances(_endPoint)); assertEquals(1, cache.getNumIdleInstances(_endPoint)); assertNotSame(handle1, handle2); }
Source:
<code>private Object createWriter(Context sinkContext) { @SuppressWarnings("rawtypes") Optional<EncodingFormat> encodingFormat = discoverOptionalEncodingFormat(BulkWriterFactory.class) .map(Optional::of).orElseGet(() -> discoverOptionalEncodingFormat(EncoderFactory.class)); if (encodingFormat.isPresent()) { return encodingFormat.get().createRuntimeEncoder(sinkContext, getFormatDataType()); } <START> FileSystemFormatFactory formatFactory = createFormatFactory(); <END> FileSystemFormatFactory.WriterContext context = new FileSystemFormatFactory.WriterContext() { @Override public TableSchema getSchema() { return schema; } @Override public ReadableConfig getFormatOptions() { return formatOptions(formatFactory.factoryIdentifier()); } @Override public List<String> getPartitionKeys() { return partitionKeys; } }; Optional<Encoder<RowData>> encoder = formatFactory.createEncoder(context); Optional<BulkWriter.Factory<RowData>> bulk = formatFactory.createBulkWriterFactory(context); if (encoder.isPresent()) { return encoder.get(); } else if (bulk.isPresent()) { return bulk.get(); } else { throw new TableException( formatFactory + " format should implement at least one Encoder or BulkWriter"); } }</code><technical_language>this is needed? Do need migrate formats EncodingFormatFactory DecodingFormatFactory remove code? If yes, create issue for that</technical_language>

Target:
private Object createWriter(Context sinkContext) { if (bulkWriterFormat != null) { return bulkWriterFormat.createRuntimeEncoder(sinkContext, getFormatDataType()); } else if (formatFactory != null) { return createWriterFromFormatFactory(); } else if (serializationFormat != null) { throw new UnsupportedOperationException("The serializationFormat is under developing."); } else { throw new TableException("Can not find format factory."); } }
Source:
<code><START> private int toIntWithCheck(long size) { <END> if (size > Integer.MAX_VALUE) { throw new ParquetEncodingException( "Cannot write page larger than " + Integer.MAX_VALUE + " bytes: " + size); } return (int)size; }</code><technical_language>In other places java.util.Math.toIntExact(long)</technical_language>

Target:
private int toIntWithCheck(long size) { if ((int)size != size) { throw new ParquetEncodingException("Cannot write page larger than " + Integer.MAX_VALUE + " bytes: " + size); } return (int)size; }
Source:
<code>public void testOne() throws Exception { <START> RestClientBuilderImpl builder = new RestClientBuilderImpl(); <END> MPCollectionServiceIntf mpc = builder.baseUri(URI.create(generateURL(""))) .build(MPCollectionServiceIntf.class); List<String> l = mpc.getList(); Assert.assertEquals(3, l.size()); }</code><technical_language>this test is serving example, follow practices spec api instead of relying implementation class directly: RestClientBuilder builder = RestClientBuilder.newBuilder();</technical_language>

Target:
public void testOne() throws Exception { RestClientBuilder builder = RestClientBuilder.newBuilder(); MPCollectionServiceIntf mpc = builder.baseUri(URI.create(generateURL(""))) .build(MPCollectionServiceIntf.class); List<String> l = mpc.getList(); Assert.assertEquals(3, l.size()); }
Source:
<code>private void processEvents() { while ( state.get() == State.STARTED ) { try { int lastNegotiatedSessionTimeoutMs = client.getZookeeperClient().getLastNegotiatedSessionTimeoutMs(); int useSessionTimeoutMs = (lastNegotiatedSessionTimeoutMs > 0) ? lastNegotiatedSessionTimeoutMs : sessionTimeoutMs; <START> useSessionTimeoutMs = sessionExpirationPercent > 0 && startOfSuspendedEpoch != 0 ? (useSessionTimeoutMs * sessionExpirationPercent) / 100 : useSessionTimeoutMs; <END> long elapsedMs = startOfSuspendedEpoch == 0 ? useSessionTimeoutMs / 2 : System.currentTimeMillis() - startOfSuspendedEpoch; long pollMaxMs = useSessionTimeoutMs - elapsedMs; final ConnectionState newState = eventQueue.poll(pollMaxMs, TimeUnit.MILLISECONDS); if ( newState != null ) { if ( listeners.size() == 0 ) { log.warn("There are no ConnectionStateListeners registered."); } listeners.forEach ( new Function<ConnectionStateListener, Void>() { @Override public Void apply(ConnectionStateListener listener) { listener.stateChanged(client, newState); return null; } } ); } else if ( sessionExpirationPercent > 0 ) { synchronized(this) { checkSessionExpiration(); } } } catch ( InterruptedException e ) { } } }</code><technical_language>I right synchronization of access startOfSuspendedEpoch here. modified addStateChange setToSuspended methods (which synchronize access it). I if cleaner startOfSuspendedEpoch volatile</technical_language>

Target:
private void processEvents() { while ( state.get() == State.STARTED ) { try { int useSessionTimeoutMs = getUseSessionTimeoutMs(); long elapsedMs = startOfSuspendedEpoch == 0 ? useSessionTimeoutMs / 2 : System.currentTimeMillis() - startOfSuspendedEpoch; long pollMaxMs = useSessionTimeoutMs - elapsedMs; final ConnectionState newState = eventQueue.poll(pollMaxMs, TimeUnit.MILLISECONDS); if ( newState != null ) { if ( listeners.size() == 0 ) { log.warn("There are no ConnectionStateListeners registered."); } listeners.forEach ( new Function<ConnectionStateListener, Void>() { @Override public Void apply(ConnectionStateListener listener) { listener.stateChanged(client, newState); return null; } } ); } else if ( sessionExpirationPercent > 0 ) { synchronized(this) { checkSessionExpiration(); } } } catch ( InterruptedException e ) { } } }
Source:
<code>public FormValidation doCheckWebHookName(@QueryParameter final String value) { if (StringUtils.isBlank(value)) { return FormValidation.warning("Please provide a value"); } <START> return FormValidation.ok(); <END> }</code><technical_language>special characters block in webhook name</technical_language>

Target:
public FormValidation doCheckWebHookName(@QueryParameter final String value) { if (StringUtils.isBlank(value)) { return FormValidation.error("Please provide a value"); } String pattern = "^[A-Za-z0-9_-]+$"; if (!value.matches(pattern)) { return FormValidation.error("Only allowed characters are alphaphetic, numeric, hypen and underscore"); } return FormValidation.ok(); }
Source:
<code>public String displayConnectionAccepted(int playerId) { <START> return "Player " + playerId + " has been added to the game."; <END> }</code><technical_language>Do want display this? spectator a player in game they</technical_language>

Target:
public String displayConnectionAccepted(int playerId) { return null;}
Source:
<code>public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String destString = dest.toString(); if (source.equals("") || destString.equals("")) { return null; } String part1 = destString.substring(0, dstart); String part2 = destString.substring(dend); <START> String newString = part1 + (String)source + part2; <END> try { Integer x = Integer.parseInt((String)newString); return null; } catch (NumberFormatException e) { return ""; } }</code><technical_language>this source.subSequence(start, end)? "This method is called buffer is replace range dstart dend of dest new text range start end of source."</technical_language>

Target:
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String destString = dest.toString(); if (source.equals("") || destString.equals("")) { return null; } String part1 = destString.substring(0, dstart); String part2 = destString.substring(dend); String newString = part1 + (String)source.subSequence(start, end) + part2; try { Integer x = Integer.parseInt((String)newString); return null; } catch (NumberFormatException e) { return ""; } }
Source:
<code>public static void main(String[] args) throws Exception { Preconditions.checkArgument(args.length == 5, "Illegal number of arguments. Expected: 5, Actual: " + args.length); String stormId = args[0]; String assignmentId = args[1]; String supervisorPort = args[2]; String portStr = args[3]; String workerId = args[4]; Map<String, Object> conf = ConfigUtils.readStormConfig(); Utils.setupDefaultUncaughtExceptionHandler(); StormCommon.validateDistributedMode(conf); Worker worker = new Worker(conf, null, stormId, assignmentId, Integer.parseInt(supervisorPort), Integer.parseInt(portStr), workerId); worker.start(); <START> LOG.info("Adding shutdown hook with kill in secs", ObjectReader.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS))); <END> Utils.addShutdownHookWithDelayedForceKill(worker::shutdown, ObjectReader.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS))); }</code><technical_language>ObjectReader.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS)) executed end users configure print INFO lower. separate variable here</technical_language>

Target:
public static void main(String[] args) throws Exception { Preconditions.checkArgument(args.length == 5, "Illegal number of arguments. Expected: 5, Actual: " + args.length); String stormId = args[0]; String assignmentId = args[1]; String supervisorPort = args[2]; String portStr = args[3]; String workerId = args[4]; Map<String, Object> conf = ConfigUtils.readStormConfig(); Utils.setupDefaultUncaughtExceptionHandler(); StormCommon.validateDistributedMode(conf); Worker worker = new Worker(conf, null, stormId, assignmentId, Integer.parseInt(supervisorPort), Integer.parseInt(portStr), workerId); worker.start(); int workerShutdownSleepSecs = ObjectReader.getInt(conf.get(Config.SUPERVISOR_WORKER_SHUTDOWN_SLEEP_SECS)); LOG.info("Adding shutdown hook with kill in secs", workerShutdownSleepSecs); Utils.addShutdownHookWithDelayedForceKill(worker::shutdown, workerShutdownSleepSecs); }
Source:
<code>public String handleMdsException(final MdsException exception) throws IOException { LOGGER.error("Error: " + exception.getMessage(), exception); <START> if (exception instanceof ObjectCreateException || exception instanceof ObjectUpdateException) { <END> return exception.getMessage(); } if (exception.getMessageKey() == null) { return "error"; } else if (exception.getParams() == null) { return String.format("key:%s", exception.getMessageKey()); } else { return String.format("key:%s\nparams:%s", exception.getMessageKey(), exception.getParams()); } }</code><technical_language>told do this? want localized message for exceptions</technical_language>

Target:
public String handleMdsException(final MdsException exception) throws IOException { LOGGER.error("Error: " + exception.getMessage(), exception); if (exception.getMessageKey() == null) { return "error"; } else if (exception.getParams() == null) { return String.format("key:%s", exception.getMessageKey()); } else { return String.format("key:%s\nparams:%s", exception.getMessageKey(), exception.getParams()); } }
Source:
<code>public void search_for_members() { String orgKey = createOrganization(); String user1 = createUser(); String user2 = createUser("sameprefixuser"); <START> createUser("sameprefixuser"); <END> adminClient.organizations().addMember(orgKey, user1); adminClient.organizations().addMember(orgKey, user2); MembersPage page = nav.openOrganizationMembers(orgKey); page .searchForMember("sameprefixuser") .shouldHaveTotal(1); page.getMembersByIdx(0).shouldBeNamed(user2, user2); page .searchForMember(user1) .shouldHaveTotal(1); page.getMembersByIdx(0).shouldBeNamed(user1, user1); }</code><technical_language>consider rearranging order of lines, more obvious, of users is a member. Alternative: Create a method createMember, creates a user + a member</technical_language>

Target:
public void search_for_members() { String orgKey = createOrganization(); String user1 = createUser(); adminClient.organizations().addMember(orgKey, user1); String user2 = createUser("sameprefixuser"); adminClient.organizations().addMember(orgKey, user2); createUser("sameprefixuser"); MembersPage page = nav.openOrganizationMembers(orgKey); page .searchForMember("sameprefixuser") .shouldHaveTotal(1); page.getMembersByIdx(0).shouldBeNamed(user2, user2); page .searchForMember(user1) .shouldHaveTotal(1); page.getMembersByIdx(0).shouldBeNamed(user1, user1); }
Source:
<code>public void rename(boolean save) { renamePopUpPresenter.show(versionRecordManager.getPathToLatest(), fileNameValidator, details -> { view.showBusyIndicator(org.kie.workbench.common.widgets.client.resources.i18n.CommonConstants.INSTANCE.Renaming()); editorService.call(getRenameSuccessCallback(renamePopUpPresenter.getView()), getRenameErrorCallback(renamePopUpPresenter.getView())).rename(versionRecordManager.getPathToLatest(), details.getNewFileName(), <START> details.getCommitMessage(), <END> save, editorHelper.getContent(), metadata); }); }</code><technical_language>HasBusyIndicatorDefaultErrorCallback in package DefaultErrorCallback save some keystrokes here.</technical_language>

Target:
public void rename(boolean save) { if(save) { synchronizeFormLayout(); } renamePopUpPresenter.show(versionRecordManager.getPathToLatest(), fileNameValidator, getRenameCommand(save)); }
Source:
<code>public static FWTile loadTile(String blockID) { try { Block block = createBlock(blockID); FWTile tile = (block instanceof Updater) ? updaterInjector.inject(block, new Class[] { String.class }, new Object[] { blockID }) : <START> injector.inject(block, new Class[] { String.class }, new Object[] { blockID }); <END> tile.setBlock(block); WrapperEvent.FWTileCreate event = new WrapperEvent.FWTileCreate(block, tile); Game.events().publish(event); return tile; } catch (Exception e) { throw new RuntimeException("Fatal error when trying to create a new NOVA tile.", e); } }</code><technical_language>This ternary expression is pretty long, do this: java ComponentInjector<FWTile> injector = (block instanceof Updater) ? updaterInjector : injector; injector.inject(block, new Class[] { String.class }, new Object[] { blockID });</technical_language>

Target:
public static FWTile loadTile(String blockID) { try { Block block = createBlock(blockID); ComponentInjector<? extends FWTile> inject = (block instanceof Updater) ? updaterInjector : injector; FWTile tile = inject.inject(block, new Class<?>[] { String.class }, new Object[] { blockID }); tile.setBlock(block); WrapperEvent.FWTileCreate event = new WrapperEvent.FWTileCreate(block, tile); Game.events().publish(event); return tile; } catch (Exception e) { throw new RuntimeException("Fatal error when trying to create a new NOVA tile.", e); } }
Source:
<code>private void validateParentOrThrow(Library library) { if (!isDetailedLibrary(library)) return; if (!isAliquotSample(library.getSample())) { String sc = null; if (isDetailedSample(library.getSample())) { DetailedSample sample = (DetailedSample) library.getSample(); sc = sample.getSampleClass() == null ? "not set" : sample.getSampleClass().getAlias(); } else { sc = "Plain Sample"; } <START> throw new IllegalArgumentException(String.format("Sample Class '%s' is not valid for Library parent. Must be an aliquot", sc)); <END> } }</code><technical_language>current wording is ambiguous sample class is parent library is parent. "...is a valid parent for Library"</technical_language>

Target:
private void validateParentOrThrow(Library library) { if (!isDetailedLibrary(library)) return; if (!isAliquotSample(library.getSample())) { String sc = null; if (isDetailedSample(library.getSample())) { DetailedSample sample = (DetailedSample) library.getSample(); sc = sample.getSampleClass() == null ? "not set" : sample.getSampleClass().getAlias(); } else { sc = "Plain Sample"; } throw new IllegalArgumentException(String.format("Sample Class '%s' is not a valid parent for Libraries. Must be an aliquot", sc)); } }
Source:
<code>public void addRoleInUserManager(Role role) { String setName = role.getName(); if (userManager.getPermissionSetList().contains(setName)) { Collection<Permission> oldPermissions = userManager.getAllPermissionsFromPermissionSet(setName); userManager.removePermissionFromSet(setName, oldPermissions.toArray(new Permission[oldPermissions.size()])); userManager.removePermissionSetFromPermissionSet(setName, role.getRoles().toArray(new String[role.getRoles().size()])); } else { try { LOGGER.debug("Create permissionset: " + setName); userManager.createPermissionSet(setName); } catch (PermissionSetAlreadyExistsException e) { LOGGER.error("This is Impossible."); } catch (Exception e) { <START> LOGGER.error("Entry exists exception. This seems impossible. Message: " + e.getMessage()); <END> } } Collection<Permission> permissionList = Sets.newHashSet(); for (String permission : role.getPermissions()) { permissionList.add(new WicketPermission(permission)); } userManager.addPermissionToSet(setName, permissionList.toArray(new Permission[permissionList.size()])); userManager.addPermissionSetToPermissionSet(setName, role.getRoles().toArray(new String[role.getRoles().size()])); }</code><technical_language>hand exception slf4j logger LOGGER.error("Entry exists ...", e);</technical_language>

Target:
public void addRoleInUserManager(Role role) { String setName = role.getName(); if (userManager.getPermissionSetList().contains(setName)) { Collection<Permission> oldPermissions = userManager.getAllPermissionsFromPermissionSet(setName); userManager.removePermissionFromSet(setName, oldPermissions.toArray(new Permission[oldPermissions.size()])); userManager.removePermissionSetFromPermissionSet(setName, role.getRoles().toArray(new String[role.getRoles().size()])); } else { try { LOGGER.debug("Create permissionset: " + setName); userManager.createPermissionSet(setName); } catch (PermissionSetAlreadyExistsException e) { LOGGER.error("This is Impossible."); } catch (Exception e) { LOGGER.error("Entry exists exception. This seems impossible.", e); } } Collection<Permission> permissionList = Sets.newHashSet(); for (String permission : role.getPermissions()) { permissionList.add(new WicketPermission(permission)); } userManager.addPermissionToSet(setName, permissionList.toArray(new Permission[permissionList.size()])); userManager.addPermissionSetToPermissionSet(setName, role.getRoles().toArray(new String[role.getRoles().size()])); }
Source:
<code>public Collection<Guid> getRoleIds() { if (roleIds == null) { roleIds = Collections.emptyList(); } <START> return new ArrayList<Guid>(roleIds); <END> }</code><technical_language>written - critical consider set (just ensure making a mistake of adding UUID - i mean, if do add , copy)</technical_language>

Target:
public Collection<Guid> getRoleIds() { if (roleIds == null) { roleIds = Collections.emptyList(); } return new HashSet<Guid>(roleIds); }
Source:
<code>public U getFinalResult() { <START> PollingContext<T> currentTerminalPollContext = this.terminalPollContext; <END> if (currentTerminalPollContext != null) { return this.fetchResultOperation .apply(currentTerminalPollContext) .block(); } else { PollingContext<T> context = this.pollingContext.clone(); AsyncPollResponse<T, U> finalAsyncPollResponse = pollingLoop(context) .blockLast(); this.terminalPollContext = context; return finalAsyncPollResponse.getFinalResult().block(); } }</code><technical_language>this implementation simplified return this.waitUntilCompletion().getFinalResult().block()</technical_language>

Target:
public U getFinalResult() { PollingContext<T> currentTerminalPollContext = this.terminalPollContext; if (currentTerminalPollContext != null) { return this.fetchResultOperation .apply(currentTerminalPollContext) .block(); } else { PollingContext<T> context = this.pollingContext.copy(); AsyncPollResponse<T, U> finalAsyncPollResponse = pollingLoop(context) .blockLast(); this.terminalPollContext = context; return finalAsyncPollResponse.getFinalResult().block(); } }
Source:
<code>public boolean isAutoConfExplorerBanned(String address) { <START> return getDevFilter() != null && <END> getDevFilter().getBannedAutoConfExplorers().stream() .anyMatch(e -> e.equals(address)); }</code><technical_language>need getFilter getDevFilter. DevFilter is locally stored of filter admin. great naming... changed a more clear name..</technical_language>

Target:
public boolean isAutoConfExplorerBanned(String address) { return getFilter() != null && getFilter().getBannedAutoConfExplorers().stream() .anyMatch(e -> e.equals(address)); }
Source:
<code>void reallocate(PooledByteBuf<T> buf, int newCapacity, boolean freeOldMemory) { if (newCapacity < 0 || newCapacity > buf.maxCapacity()) { throw new IllegalArgumentException("newCapacity: " + newCapacity); } int oldCapacity = buf.length; if (oldCapacity == newCapacity) { return; } PoolChunk<T> oldChunk = buf.chunk; <START> ByteBuffer olNioBuffer = buf.tmpNioBuf; <END> long oldHandle = buf.handle; T oldMemory = buf.memory; int oldOffset = buf.offset; int oldMaxLength = buf.maxLength; int readerIndex = buf.readerIndex(); int writerIndex = buf.writerIndex(); allocate(parent.threadCache(), buf, newCapacity); if (newCapacity > oldCapacity) { memoryCopy( oldMemory, oldOffset, buf.memory, buf.offset, oldCapacity); } else if (newCapacity < oldCapacity) { if (readerIndex < newCapacity) { if (writerIndex > newCapacity) { writerIndex = newCapacity; } memoryCopy( oldMemory, oldOffset + readerIndex, buf.memory, buf.offset + readerIndex, writerIndex - readerIndex); } else { readerIndex = writerIndex = newCapacity; } } buf.setIndex(readerIndex, writerIndex); if (freeOldMemory) { free(oldChunk, olNioBuffer, oldHandle, oldMaxLength, buf.cache); } }</code><technical_language>olNioBuffer -> oldNioBuffer</technical_language>

Target:
void reallocate(PooledByteBuf<T> buf, int newCapacity, boolean freeOldMemory) { if (newCapacity < 0 || newCapacity > buf.maxCapacity()) { throw new IllegalArgumentException("newCapacity: " + newCapacity); } int oldCapacity = buf.length; if (oldCapacity == newCapacity) { return; } PoolChunk<T> oldChunk = buf.chunk; ByteBuffer oldNioBuffer = buf.tmpNioBuf; long oldHandle = buf.handle; T oldMemory = buf.memory; int oldOffset = buf.offset; int oldMaxLength = buf.maxLength; int readerIndex = buf.readerIndex(); int writerIndex = buf.writerIndex(); allocate(parent.threadCache(), buf, newCapacity); if (newCapacity > oldCapacity) { memoryCopy( oldMemory, oldOffset, buf.memory, buf.offset, oldCapacity); } else if (newCapacity < oldCapacity) { if (readerIndex < newCapacity) { if (writerIndex > newCapacity) { writerIndex = newCapacity; } memoryCopy( oldMemory, oldOffset + readerIndex, buf.memory, buf.offset + readerIndex, writerIndex - readerIndex); } else { readerIndex = writerIndex = newCapacity; } } buf.setIndex(readerIndex, writerIndex); if (freeOldMemory) { free(oldChunk, oldNioBuffer, oldHandle, oldMaxLength, buf.cache); } }