auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testUnresolvedSequencesAreNotFatal() throws Exception { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(123456L, (short) 0); apiVersions.update("0", NodeApiVersions.create(ApiKeys.INIT_PRODUCER_ID.id, (short) 0, (short) 3)); TransactionManager txnManager = new TransactionManager(logContext, "testUnresolvedSeq", 60000, 100, apiVersions); setupWithTransactionState(txnManager); doInitTransactions(txnManager, producerIdAndEpoch); txnManager.beginTransaction(); txnManager.failIfNotReadyForSend(); txnManager.maybeAddPartitionToTransaction(tp0); client.prepareResponse(new AddPartitionsToTxnResponse(0, Collections.singletonMap(tp0, Errors.NONE))); sender.runOnce(); Future<RecordMetadata> request1 = appendToAccumulator(tp0); sender.runOnce(); time.sleep(1000L); <START> Future<RecordMetadata> request2 = appendToAccumulator(tp0); <END> sender.runOnce(); assertEquals(2, client.inFlightRequestCount()); sendIdempotentProducerResponse(0, tp0, Errors.NOT_LEADER_FOR_PARTITION, -1); sender.runOnce(); Node node = metadata.fetch().nodes().get(0); time.sleep(1000L); client.disconnect(node.idString()); client.blackout(node, 10); sender.runOnce(); assertFutureFailure(request1, TimeoutException.class); assertTrue(txnManager.hasUnresolvedSequence(tp0)); Future<RecordMetadata> request3 = appendToAccumulator(tp0); sender.runOnce(); assertTrue(txnManager.hasAbortableError()); }</code><technical_language>request2 is</technical_language>

Target:
public void testUnresolvedSequencesAreNotFatal() throws Exception { ProducerIdAndEpoch producerIdAndEpoch = new ProducerIdAndEpoch(123456L, (short) 0); apiVersions.update("0", NodeApiVersions.create(ApiKeys.INIT_PRODUCER_ID.id, (short) 0, (short) 3)); TransactionManager txnManager = new TransactionManager(logContext, "testUnresolvedSeq", 60000, 100, apiVersions); setupWithTransactionState(txnManager); doInitTransactions(txnManager, producerIdAndEpoch); txnManager.beginTransaction(); txnManager.failIfNotReadyForSend(); txnManager.maybeAddPartitionToTransaction(tp0); client.prepareResponse(new AddPartitionsToTxnResponse(0, Collections.singletonMap(tp0, Errors.NONE))); sender.runOnce(); Future<RecordMetadata> request1 = appendToAccumulator(tp0); sender.runOnce(); time.sleep(1000L); appendToAccumulator(tp0); sender.runOnce(); assertEquals(2, client.inFlightRequestCount()); sendIdempotentProducerResponse(0, tp0, Errors.NOT_LEADER_FOR_PARTITION, -1); sender.runOnce(); Node node = metadata.fetch().nodes().get(0); time.sleep(1000L); client.disconnect(node.idString()); client.blackout(node, 10); sender.runOnce(); assertFutureFailure(request1, TimeoutException.class); assertTrue(txnManager.hasUnresolvedSequence(tp0)); sender.runOnce(); assertTrue(txnManager.hasAbortableError()); }
Source:
<code><START> private ErrorCode(int httpCode) { <END> this.httpCode = httpCode; }</code><technical_language>\[Checkstyle\] ERROR: Redundant 'private' modifier\</technical_language>

Target:
ErrorCode(int httpCode) { this.httpCode = httpCode; }
Source:
<code>public Connector getConnector(String principal, AuthenticationToken token) throws AccumuloException, AccumuloSecurityException { Properties properties = ClientConfConverter.toProperties(clientConf); properties.setProperty(ClientProperty.AUTH_PRINCIPAL.getKey(), principal); properties.setProperty(ClientProperty.INSTANCE_NAME.getKey(), getInstanceName()); <START> SingletonManager.setMode(Mode.CONNECTOR); <END> return new ConnectorImpl(new AccumuloClientImpl(SingletonReservation.fake(), new ClientContext(new ClientInfoImpl(properties, token)), false)); }</code><technical_language>Is idea time API is used, stop managing static resources</technical_language>

Target:
public Connector getConnector(String principal, AuthenticationToken token) throws AccumuloException, AccumuloSecurityException { Properties properties = ClientConfConverter.toProperties(clientConf); properties.setProperty(ClientProperty.AUTH_PRINCIPAL.getKey(), principal); properties.setProperty(ClientProperty.INSTANCE_NAME.getKey(), getInstanceName()); return new ConnectorImpl(new AccumuloClientImpl(SingletonReservation.noop(), new ClientContext(new ClientInfoImpl(properties, token)))); }
Source:
<code>private static Object parse(final String value, final int startIdx, final int endIdx, final boolean allowMore) throws JSONException { final StringTokenizer stringTokenizer = new StringTokenizer(value, startIdx, endIdx); final Object result = parse(stringTokenizer); if (!allowMore) { final char unexpectedValue; try { unexpectedValue = stringTokenizer.nextUnskippable(); } catch (JSONException ignore) { return result; } <START> throw syntaxError("Unexpected symbol " + unexpectedValue, stringTokenizer); <END> } else { return result; } }</code><technical_language>please put symbol in single quotes</technical_language>

Target:
private static Object parse(final String value, final int startIdx, final int endIdx, final boolean allowMore) throws JSONException { final StringTokenizer stringTokenizer = new StringTokenizer(value, startIdx, endIdx); final Object result = parse(stringTokenizer); if (!allowMore) { final char unexpectedValue; try { unexpectedValue = stringTokenizer.nextUnskippable(); } catch (JSONException ignore) { return result; } throw syntaxError("Unexpected symbol '" + unexpectedValue + "'", stringTokenizer); } else { return result; } }
Source:
<code>RequestValueProvider(ExportOptions options) { <START> this.start = options.getBigtableStartRow(); <END> this.stop = options.getBigtableStopRow(); this.maxVersion = options.getBigtableMaxVersions(); this.filter = options.getBigtableFilter(); this.options = options; this.requestContext = RequestContext.create( InstanceName.of(options.getBigtableProject().get(), options.getBigtableInstanceId().get()), options.getBigtableAppProfileId().get()); }</code><technical_language>This a PR</technical_language>

Target:
RequestValueProvider(ExportOptions options) { this.start = options.getBigtableStartRow(); this.stop = options.getBigtableStopRow(); this.maxVersion = options.getBigtableMaxVersions(); this.filter = options.getBigtableFilter(); }
Source:
<code>public void log(IStatus status) { int severity = status.getSeverity(); log(status.getMessage(), severity); if (status.getException() != null) log(status.getException().getMessage(), severity); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus <START> nestedStatu : <END> nestedStatus) { log(nestedStatu); } }</code><technical_language>name needed</technical_language>

Target:
public void log(IStatus status) { int severity = status.getSeverity(); log(status.getMessage(), severity); if (status.getException() != null) log(status.getException().getMessage(), severity); IStatus[] nestedStatus = status.getChildren(); if (nestedStatus != null) for (IStatus s : nestedStatus) { log(s); } }
Source:
<code>public void removeUserFromKeycloak(String userId) throws ServerException { try { String token = requestToken(); int responseCode = requestFactory .fromUrl(keycloakRemoveUserUrl + userId) .setAuthorizationHeader("Bearer " + token) .useDeleteMethod() .request() .getResponseCode(); if (responseCode != 204) { <START> throw new ServerException("Can't remove user from KeyClock. UserId:" + userId); <END> } } catch (IOException | ApiException e) { LOG.warn("Exception during removing user from Keycloak", e); throw new ServerException("Exception during removing user from Keycloak", e); } }</code><technical_language>suggestion throw new ServerException("Can't remove user Keycloak. UserId:" + userId);</technical_language>

Target:
public void removeUserFromKeycloak(String userId) throws ServerException { try { String token = requestToken(); int responseCode = requestFactory .fromUrl(keycloakRemoveUserUrl + userId) .setAuthorizationHeader("Bearer " + token) .useDeleteMethod() .request() .getResponseCode(); if (responseCode != 204) { throw new ServerException("Can't remove user from Keycloak. UserId:" + userId); } } catch (IOException | ApiException e) { LOG.warn("Exception during removing user from Keycloak", e); throw new ServerException("Exception during removing user from Keycloak", e); } }
Source:
<code>private Sequence getSequence(String gappedSequenceString){ if (gappedSequenceString == null) return null; Sequence returnSeq = null; String sequenceString = gappedSequenceString.replace("-", ""); try { if (sequenceString.matches("^[ACTG]+$")) returnSeq = new DNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else if (sequenceString.matches("^[ACUG]+$")) returnSeq = new RNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); } catch (CompoundNotFoundException ex) { <START> Logger.getLogger(Hsp.class.getName()).log(Level.SEVERE, null, ex); <END> } return returnSeq; }</code><technical_language>Logging in Biojava (since Biojava 4) is happening slf4j interface. change this slf4j. simply need import top: java import org.slf4j.Logger; import org.slf4j.LoggerFactory; declare a static variable for logger: java private static final Logger logger = LoggerFactory.getLogger(Hsp.class); like: java logger.error("Unexpected error, find compound blah blah ", ex); for instance org.biojava.nbio.structure.StructureImpl for example of above</technical_language>

Target:
private Sequence getSequence(String gappedSequenceString){ if (gappedSequenceString == null) return null; Sequence returnSeq = null; String sequenceString = gappedSequenceString.replace("-", ""); try { if (sequenceString.matches("^[ACTG]+$")) returnSeq = new DNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else if (sequenceString.matches("^[ACUG]+$")) returnSeq = new RNASequence(sequenceString, DNACompoundSet.getDNACompoundSet()); else returnSeq = new ProteinSequence(sequenceString, AminoAcidCompoundSet.getAminoAcidCompoundSet()); } catch (CompoundNotFoundException ex) { logger.error("Unexpected error, could not find compound when creating Sequence object from Hsp", ex); } return returnSeq; }
Source:
<code>public boolean isEmpty() { <START> if(this.getTherapy().isEmpty() && this.getDisease().isEmpty() && this.getVersion().isEmpty() && this.getPages().isEmpty() && this.getCategory().isEmpty() && this.getDescription().isEmpty()) <END> return true; else return false; }</code><technical_language>null empty</technical_language>

Target:
public boolean isEmpty() { if (StringUtils.isNullOrEmpty(this.therapy) && StringUtils.isNullOrEmpty(this.disease) && StringUtils.isNullOrEmpty(this.version) && StringUtils.isNullOrEmpty(this.pages) && StringUtils.isNullOrEmpty(this.category) && StringUtils.isNullOrEmpty(this.description)) return true; else return false; }
Source:
<code>public ColumnFamilyOptions getColumnOptions() { ColumnFamilyOptions opt = predefinedOptions.createColumnOptions(handlesToClose); handlesToClose.add(opt); if (optionsFactory != null) { opt = optionsFactory.createColumnOptions(opt, handlesToClose); } if (sharedResources != null) { final RocksDBSharedResources rocksResources = sharedResources.getResourceHandle(); final Cache blockCache = rocksResources.getCache(); TableFormatConfig tableFormatConfig = opt.tableFormatConfig(); BlockBasedTableConfig blockBasedTableConfig; if (tableFormatConfig == null) { blockBasedTableConfig = new BlockBasedTableConfig(); } else { Preconditions.checkArgument(tableFormatConfig instanceof BlockBasedTableConfig, "We currently only support BlockBasedTableConfig When bounding total memory."); blockBasedTableConfig = (BlockBasedTableConfig) tableFormatConfig; } if (rocksResources.isUsingPartitionedIndex()) { blockBasedTableConfig.setIndexType(IndexType.kTwoLevelIndexSearch); blockBasedTableConfig.setPartitionFilters(true); blockBasedTableConfig.setPinTopLevelIndexAndFilter(true); } blockBasedTableConfig.setBlockCache(blockCache); blockBasedTableConfig.setCacheIndexAndFilterBlocks(true); <START> blockBasedTableConfig.setCacheIndexAndFilterBlocksWithHighPriority(true); <END> blockBasedTableConfig.setPinL0FilterAndIndexBlocksInCache(true); opt.setTableFormatConfig(blockBasedTableConfig); } return opt; }</code><technical_language>RocksDB's current implementation, partitioned index is compatible full bloom filter. point of view, check current filter is full instead of block based set a default full bloom filter if current filter is null</technical_language>

Target:
public ColumnFamilyOptions getColumnOptions() { ColumnFamilyOptions opt = predefinedOptions.createColumnOptions(handlesToClose); handlesToClose.add(opt); if (optionsFactory != null) { opt = optionsFactory.createColumnOptions(opt, handlesToClose); } if (sharedResources != null) { final RocksDBSharedResources rocksResources = sharedResources.getResourceHandle(); final Cache blockCache = rocksResources.getCache(); TableFormatConfig tableFormatConfig = opt.tableFormatConfig(); BlockBasedTableConfig blockBasedTableConfig; if (tableFormatConfig == null) { blockBasedTableConfig = new BlockBasedTableConfig(); } else { Preconditions.checkArgument(tableFormatConfig instanceof BlockBasedTableConfig, "We currently only support BlockBasedTableConfig When bounding total memory."); blockBasedTableConfig = (BlockBasedTableConfig) tableFormatConfig; } if (rocksResources.isUsingPartitionedIndex()) { blockBasedTableConfig.setIndexType(IndexType.kTwoLevelIndexSearch); blockBasedTableConfig.setPartitionFilters(true); blockBasedTableConfig.setPinTopLevelIndexAndFilter(true); this.overwriteFilterIfExist(blockBasedTableConfig); } blockBasedTableConfig.setBlockCache(blockCache); blockBasedTableConfig.setCacheIndexAndFilterBlocks(true); blockBasedTableConfig.setCacheIndexAndFilterBlocksWithHighPriority(true); blockBasedTableConfig.setPinL0FilterAndIndexBlocksInCache(true); opt.setTableFormatConfig(blockBasedTableConfig); } return opt; }
Source:
<code>protected void configureWebView() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); WebViewClient webViewClient; Bundle extras = getIntent().getExtras(); ArrayList<String> allowedURL = null; <START> if (extras != null && extras.getBoolean(DISABLE_LINKS_ON_PAGE, false)) { <END> String addressToLoad = extras.getString(URL_TO_LOAD); String authURL = extras.getString(AUTHENTICATION_URL); allowedURL = new ArrayList<>(); if (!TextUtils.isEmpty(addressToLoad)) { allowedURL.add(addressToLoad); } if (!TextUtils.isEmpty(authURL)) { allowedURL.add(authURL); } if(extras.getStringArray(ALLOWED_URLS) != null) { String[] urls = extras.getStringArray(ALLOWED_URLS); for (String currentURL: urls) { allowedURL.add(currentURL); } } } if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } webViewClient = new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL); } else { if (allowedURL == null || allowedURL.size() == 0) { AppLog.e(AppLog.T.UTILS, "No valid urls passed to WPWebViewActivity"); finish(); } webViewClient = new URLFilteredWebViewClient(allowedURL); } mWebView.setWebViewClient(webViewClient); mWebView.setWebChromeClient(new WPWebChromeClient(this, (ProgressBar) findViewById(R.id.progress_bar))); }</code><technical_language>for null check here</technical_language>

Target:
protected void configureWebView() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); WebViewClient webViewClient; Bundle extras = getIntent().getExtras(); ArrayList<String> allowedURL = null; if (extras != null && extras.getBoolean(DISABLE_LINKS_ON_PAGE, false)) { String addressToLoad = extras.getString(URL_TO_LOAD); String authURL = extras.getString(AUTHENTICATION_URL); allowedURL = new ArrayList<>(); if (!TextUtils.isEmpty(addressToLoad)) { allowedURL.add(addressToLoad); } if (!TextUtils.isEmpty(authURL)) { allowedURL.add(authURL); } if(extras.getStringArray(ALLOWED_URLS) != null) { String[] urls = extras.getStringArray(ALLOWED_URLS); for (String currentURL: urls) { allowedURL.add(currentURL); } } } if (getIntent().hasExtra(LOCAL_BLOG_ID)) { SiteModel site = mSiteStore.getSiteByLocalId(getIntent().getIntExtra(LOCAL_BLOG_ID, -1)); if (site == null) { AppLog.e(AppLog.T.UTILS, "No valid blog passed to WPWebViewActivity"); finish(); } webViewClient = new WPWebViewClient(site, mAccountStore.getAccessToken(), allowedURL); } else { webViewClient = new URLFilteredWebViewClient(allowedURL); } mWebView.setWebViewClient(webViewClient); mWebView.setWebChromeClient(new WPWebChromeClient(this, (ProgressBar) findViewById(R.id.progress_bar))); }
Source:
<code>private void createLockFileIfMissing() throws IOException { Path lockFile = getLockFilePath(); if (!lockFile.toFile().exists()) { FileChannel fc = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE); FileLock fl = fc.tryLock(); if (fl == null) { return; } try { Files.setPosixFilePermissions(lockFile, LOCK_FILE_PERMISSIONS); <START> } finally { <END> fl.release(); } } else { Files.setPosixFilePermissions(lockFile, LOCK_FILE_PERMISSIONS); } }</code><technical_language>do need lock if file exist need if exist</technical_language>

Target:
private void createLockFileIfMissing() throws IOException { Path lockFile = getLockFilePath(); if (!lockFile.toFile().exists()) { FileChannel fc = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE); try (FileLock fl = fc.tryLock()) { if (fl == null) { return; } Files.setPosixFilePermissions(lockFile, LOCK_FILE_PERMISSIONS); } } else { Files.setPosixFilePermissions(lockFile, LOCK_FILE_PERMISSIONS); } }
Source:
<code>public ConfigAccessor(HelixZkClient zkClient) { <START> this._zkClient = zkClient; <END> this._usesExternalZkClient = true; }</code><technical_language>This "this" is necessary change name _zkClient</technical_language>

Target:
public ConfigAccessor(HelixZkClient zkClient) { _zkClient = zkClient; _usesExternalZkClient = true; }
Source:
<code>int fillFrom(ByteBuffer channelReadBuffer) { int toWrite = Math.min(channelReadBuffer.remaining(), buf.remaining()); if (channelReadBuffer.remaining() > buf.remaining()) { int savedLimit = channelReadBuffer.limit(); channelReadBuffer.limit(channelReadBuffer.position() + buf.remaining()); buf.put(channelReadBuffer); <START> channelReadBuffer.limit(savedLimit); <END> } else { buf.put(channelReadBuffer); } return toWrite; }</code><technical_language>I for API do this surprised ! missing obvious here</technical_language>

Target:
int fillFrom(ByteBuffer channelReadBuffer) { int toWrite = Math.min(channelReadBuffer.remaining(), buf.remaining()); if (channelReadBuffer.remaining() > buf.remaining()) { int savedLimit = channelReadBuffer.limit(); channelReadBuffer.limit(channelReadBuffer.position() + buf.remaining()); buf.put(channelReadBuffer); channelReadBuffer.limit(savedLimit); } else { buf.put(channelReadBuffer); } if (!buf.hasRemaining()) { onFillComplete(); } return toWrite; }
Source:
<code>private static void createApiFile(File outFile, Map<String, ApiClass> classes) { PrintStream ps = null; try { <START> ps = new PrintStream(outFile); <END> ps.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); ps.println("<api version=\"1\">"); TreeMap<String, ApiClass> map = new TreeMap<String, ApiClass>(classes); for (ApiClass theClass : map.values()) { (theClass).print(ps); } ps.println("</api>"); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (ps != null) { ps.close(); } } }</code><technical_language>this default system encoding; UTF-8 instead -- new PrintStream(outFile, false, "UTF-8") (I this in previous version)</technical_language>

Target:
private static boolean createApiFile(File outFile, Map<String, ApiClass> classes) { PrintStream ps = null; try { ps = new PrintStream(outFile, "UTF-8"); ps.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); ps.println("<api version=\"1\">"); TreeMap<String, ApiClass> map = new TreeMap<String, ApiClass>(classes); for (ApiClass theClass : map.values()) { (theClass).print(ps); } ps.println("</api>"); } catch (Exception e) { e.printStackTrace(); return false; } finally { if (ps != null) { ps.close(); } } return true; }
Source:
<code>public void setup() throws ConfigurationException { <START> initMocks(this); <END> mTest = new TestDescription("HelloTest", "testDrive"); ITestDevice mockDevice = mock(ITestDevice.class); when(mockDevice.getSerialNumber()).thenReturn("serial1"); mDevices = new ArrayList<>(); mDevices.add(mockDevice); when(mContext.getDevices()).thenReturn(mDevices); when(mContext.getDeviceName(same(mockDevice))).thenReturn("device1"); when(mMockReceiver.getLogcatData()).thenReturn(createInputStreamSource()); mCollector.addLogcatReceiver(mockDevice, mMockReceiver); doReturn(createFakeTimingMetrics()).when(mCollector).parse(any(InputStreamSource.class)); mCollector.init(mContext, mListener); setPatterns(mCollector); }</code><technical_language>mockito's @Rule instead (as this is a JUnit 4 test)</technical_language>

Target:
public void setup() throws ConfigurationException { initMocks(this); mTest = new TestDescription("HelloTest", "testDrive"); ITestDevice mockDevice = mock(ITestDevice.class); when(mockDevice.getSerialNumber()).thenReturn("serial1"); mDevices = new ArrayList<>(); mDevices.add(mockDevice); when(mContext.getDevices()).thenReturn(mDevices); when(mContext.getDeviceName(same(mockDevice))).thenReturn("device1"); when(mMockReceiver.getLogcatData()).thenReturn(createInputStreamSource()); doReturn(mMockReceiver).when(mCollector).createLogcatReceiver(same(mockDevice), anyString()); doReturn(createFakeTimingMetrics()).when(mCollector).parse(any(InputStreamSource.class)); mCollector.init(mContext, mListener); setPatterns(mCollector); }
Source:
<code>public PageCacheByteArray( PagedFile pagedFile, long length, byte[] defaultValue, long base ) throws IOException { <START> super( pagedFile, defaultValue.length, length, 0, base ); <END> this.defaultValue = defaultValue; setDefaultValue( -1 ); }</code><technical_language>pass -1 a default value</technical_language>

Target:
PageCacheByteArray( PagedFile pagedFile, long length, byte[] defaultValue, long base ) throws IOException { super( pagedFile, defaultValue.length, length, base ); this.defaultValue = defaultValue; setDefaultValue( -1 ); }
Source:
<code>public final SQLSerializer handleSelect(final String sep, final List<? extends Expression<?>> expressions) { if (inSubquery) { Set<String> names = Sets.newHashSet(); List<Expression<?>> replacements = Lists.newArrayList(); for (Expression<?> expr : expressions) { if (expr instanceof Path) { String name = ColumnMetadata.getName((Path<?>) expr); <START> if (!names.add(name.toLowerCase())) { <END> expr = ExpressionUtils.as(expr, "col__" + name + replacements.size()); } } replacements.add(expr); } return handle(sep, replacements); } else { return handle(sep, expressions); } }</code><technical_language>Locale dependent :(</technical_language>

Target:
public final SQLSerializer handleSelect(final String sep, final List<? extends Expression<?>> expressions) { if (inSubquery) { Set<String> names = Sets.newHashSet(); List<Expression<?>> replacements = Lists.newArrayList(); for (Expression<?> expr : expressions) { if (expr instanceof Path) { String name = ColumnMetadata.getName((Path<?>) expr); if (!names.add(name.toLowerCase(Locale.ENGLISH))) { expr = ExpressionUtils.as(expr, "col__" + name + replacements.size()); } } replacements.add(expr); } return handle(sep, replacements); } else { return handle(sep, expressions); } }
Source:
<code>public static boolean debug() { if (debug == null) { <START> debug = "TRUE".equalsIgnoreCase(System.getProperty("run.flaky.tests.debug", "FALSE")); <END> } return debug; }</code><technical_language>debug = Boolean.getBoolean("run.flaky.tests.debug"); here</technical_language>

Target:
public static boolean debug() { return DEBUG; }
Source:
<code>public void notifyServerHasUpdates(String serverId, List<String> changelog, ConnectedSonarLintEngine engine, SonarQubeServer server, boolean onlyProjects) { <START> Notification notification = new Notification(GROUP_UPDATE_NOTIFICATION, <END> "<b>SonarLint - Configuration updates available.</b> <a href=\"#ignore\">Ignore...</a>", "\n<br>Some configuration updates are available from the SonarQube server '" + serverId + "': <ul><li>" + StringUtil.join(changelog, "<li>") + "</ul>If you want to apply them, click here to <a href=\"#update\">update binding</a>", NotificationType.INFORMATION, new NotificationListener.Adapter() { @Override public void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { switch (event.getDescription()) { case "#ignore": notification.hideBalloon(); break; case "#update": SonarQubeServerMgmtPanel.updateServerBinding(server, engine, true, onlyProjects); break; default: throw new IllegalArgumentException("Unknow event: " + event.getDescription()); } } }); notification.setImportant(false); notification.notify(myProject); }</code><technical_language>do "shown" flag? If a notification is shown need update global storage, I useful show another updates</technical_language>

Target:
public void notifyServerHasUpdates(String serverId, List<String> changelog, ConnectedSonarLintEngine engine, SonarQubeServer server, boolean onlyProjects) { Notification notification = new Notification(GROUP_UPDATE_NOTIFICATION, "<b>SonarLint - Configuration updates available.</b> <a href=\"#ignore\">Ignore...</a>", "\n<br>Some configuration updates are available from the SonarQube server '" + serverId + "': <ul><li>" + StringUtil.join(changelog, "<li>") + "</ul>If you want to apply them, <a href=\"#update\">click here to update binding</a>", NotificationType.INFORMATION, new NotificationListener.Adapter() { @Override public void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent event) { switch (event.getDescription()) { case "#ignore": notification.hideBalloon(); break; case "#update": SonarQubeServerMgmtPanel.updateServerBinding(server, engine, true, onlyProjects); break; default: throw new IllegalArgumentException("Unknow event: " + event.getDescription()); } } }); notification.setImportant(false); notification.notify(myProject); }
Source:
<code>public ConfigDef config() { <START> return new ConfigDef(); <END> }</code><technical_language>impact performance technically a single ConfigDef instance for entire class instead of creating a new time this method is called</technical_language>

Target:
public ConfigDef config() { return CONFIG_DEF; }
Source:
<code>public void testConsumingEndOfMonitorNotTreatedAsTrivial() { NullProgressMonitor npm = new NullProgressMonitor(); boolean threwException = false; SubMonitor subMonitor = SubMonitor.convert(npm, 1000); subMonitor.newChild(500); try { npm.setCanceled(true); subMonitor.split(500); } catch (OperationCanceledException exception) { <START> threwException = <END> true; } assertTrue("split should have thrown an exception", threwException); }</code><technical_language>add a fail call lines above</technical_language>

Target:
public void testConsumingEndOfMonitorNotTreatedAsTrivial() { NullProgressMonitor npm = new NullProgressMonitor(); SubMonitor subMonitor = SubMonitor.convert(npm, 1000); subMonitor.newChild(500); try { npm.setCanceled(true); subMonitor.split(500); fail("split should have thrown an exception"); } catch (OperationCanceledException exception) { } }
Source:
<code>protected StorageService getOrCreateStorageService(String storageServiceName) { StorageAccountApi storageApi = api.getStorageAccountApi(getResourceGroupName()); StorageService ss = storageApi.get(storageServiceName); if (ss != null) { return ss; } URI uri = storageApi.create(storageServiceName, LOCATION, ImmutableMap.of("property_name", "property_value"), ImmutableMap.of("accountType", StorageService.AccountType.Standard_ZRS.toString())); if (uri != null){ assertTrue(uri.toString().contains("api-version")); boolean jobDone = Predicates2.retry(new Predicate<URI>() { @Override public boolean apply(URI uri) { return ParseJobStatus.JobStatus.DONE == api.getJobApi().jobStatus(uri); } }, 60 * 1 * 1000 ).apply(uri); <START> assertTrue(jobDone, "delete operation did not complete in the configured timeout"); <END> } ss = storageApi.get(storageServiceName); Assert.assertEquals(ss.location(), LOCATION); Logger.getAnonymousLogger().log(Level.INFO, "created storageService: {0}", ss); return ss; }</code><technical_language>"create operation"</technical_language>

Target:
protected StorageService getOrCreateStorageService(String storageServiceName) { StorageAccountApi storageApi = api.getStorageAccountApi(getResourceGroupName()); StorageService ss = storageApi.get(storageServiceName); if (ss != null) { return ss; } URI uri = storageApi.create(storageServiceName, LOCATION, ImmutableMap.of("property_name", "property_value"), ImmutableMap.of("accountType", StorageService.AccountType.Standard_LRS.toString())); if (uri != null){ assertTrue(uri.toString().contains("api-version")); boolean jobDone = Predicates2.retry(new Predicate<URI>() { @Override public boolean apply(URI uri) { return ParseJobStatus.JobStatus.DONE == api.getJobApi().jobStatus(uri); } }, 60 * 1 * 1000 ).apply(uri); assertTrue(jobDone, "create operation did not complete in the configured timeout"); } ss = storageApi.get(storageServiceName); Assert.assertEquals(ss.location(), LOCATION); Logger.getAnonymousLogger().log(Level.INFO, "created storageService: {0}", ss); return ss; }
Source:
<code>public void testEmptyDelegationToken() throws IOException { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; try { <START> cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); <END> URI defaultUri = URI.create(conf.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY)); ConfigUtil.addLinkFallback(conf, defaultUri.getHost(), defaultUri); try (FileSystem fileSys = FileSystem.get(conf)) { fileSys.getDelegationToken(""); } } finally { if (cluster != null) { cluster.shutdown(); } } }</code><technical_language>nit: writing data, numDatanodes set 0</technical_language>

Target:
public void testEmptyDelegationToken() throws IOException { Configuration conf = getTestConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build(); URI defaultUri = URI.create(conf.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY)); ConfigUtil.addLinkFallback(conf, defaultUri.getHost(), defaultUri); try (FileSystem fileSys = FileSystem.get(conf)) { fileSys.getDelegationToken(""); } } finally { if (cluster != null) { cluster.shutdown(); } } }
Source:
<code>public void log(final CommitSession commitSession, final long tabletSeq, final Mutation m, final Durability durability) throws IOException { if (durability == Durability.NONE) { return; } <START> if (durability == Durability.DEFAULT) { <END> throw new IllegalArgumentException("Unexpected durability " + durability); } write(Collections.singletonList(commitSession), false, logger -> logger.log(tabletSeq, commitSession.getLogId(), m, durability), writeRetryFactory.createRetry()); logSizeEstimate.addAndGet(m.numBytes()); }</code><technical_language>a durability of is unexpected here, throw exception. check return removed</technical_language>

Target:
public void log(final CommitSession commitSession, final long tabletSeq, final Mutation m, final Durability durability) throws IOException { if (durability == Durability.DEFAULT || durability == Durability.NONE) { throw new IllegalArgumentException("Unexpected durability " + durability); } write(singletonList(commitSession), false, logger -> logger.log(tabletSeq, commitSession.getLogId(), m, durability), writeRetryFactory.createRetry()); logSizeEstimate.addAndGet(m.numBytes()); }
Source:
<code>public String getResponseFromQuery(String query) { try { final URL url = new URL( WEBSERVICE_URL + "&q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.toString())); final URLConnection connection = url.openConnection(); <START> return IOUtils.toString(connection.getInputStream()); <END> } catch (MalformedURLException e) { logger.debug("Constructed query url '{}' is not valid: {}", query, e.getMessage()); } catch (IOException e) { logger.warn("Communication error occurred while getting Yahoo weather information: {}", e.getMessage()); } return null; }</code><technical_language>Do need close input output stream? WRT: Invoking close() methods InputStream OutputStream of URLConnection a request free network resources this instance, protocol specifications behaviours for it</technical_language>

Target:
public String getResponseFromQuery(String query) { try { return HttpUtil.executeUrl("GET", WEBSERVICE_URL + "&q=" + URLEncoder.encode(query, StandardCharsets.UTF_8.toString()), WEBSERVICE_TIMEOUT); } catch (IOException e) { logger.warn("Communication error occurred while getting Yahoo weather information: {}", e.getMessage()); } return null; }
Source:
<code>@Override public final String toString() { return MoreObjects.toStringHelper(this) .add("name", name()) <START> .add("version", version()) END> .add("description", description()) .add("content", "[REDACTED]") .add("size", size()) .add("createdAtSeconds", createdAtSeconds()) .add("createdBy", createdBy()) .add("type", type()) .add("metadata", metadata()) .add("expiry", expiry()) .omitNullValues() .toString(); }</code><technical_language>If want expose user, I include all. add if a need for it. However, if this is part of building response, need include version for choosing prior versions roll to? least, need some kind of unique identifier for version enable feature. If want expose real primary key of table, sequential integers for version (sorted), of nature</technical_language>

Target:
@Override public final String toString() { return MoreObjects.toStringHelper(this) .add("name", name()) .add("description", description()) .add("content", "[REDACTED]") .add("size", size()) .add("createdAtSeconds", createdAtSeconds()) .add("createdBy", createdBy()) .add("type", type()) .add("metadata", metadata()) .add("expiry", expiry()) .omitNullValues() .toString(); }
Source:
<code><START> public static HtsgetResponse parse(final String s) { <END> final HtsgetResponse resp = new HtsgetResponse(); final mjson.Json j = mjson.Json.read(s); final mjson.Json htsget = j.at("htsget"); final mjson.Json md5 = htsget.at("md5"); if (md5 != null) { resp.md5 = md5.asString(); } final mjson.Json htsgetClass = htsget.at("format"); if (htsgetClass != null) { resp.format = HtsgetFormat.valueOf(htsgetClass.asString().toUpperCase()); } final mjson.Json blocksJson = htsget.at("urls"); if (blocksJson == null) { throw new IllegalArgumentException("No urls field found in Htsget Response"); } resp.blocks = blocksJson.asJsonList().stream() .map(Block::parse) .collect(Collectors.toList()); return resp; }</code><technical_language>checking API version header IF get warning if compatible version</technical_language>

Target:
public static HtsgetResponse parse(final String s) { final mjson.Json j = mjson.Json.read(s); final mjson.Json htsget = j.at("htsget"); if (htsget == null) { throw new HtsgetMalformedResponseException("No htsget key found in response"); } final mjson.Json md5Json = htsget.at("md5"); final mjson.Json formatJson = htsget.at("format"); final mjson.Json blocksJson = htsget.at("urls"); if (blocksJson == null) { throw new HtsgetMalformedResponseException("No urls field found in Htsget Response"); } final List<Block> blocks = blocksJson.asJsonList().stream() .map(Block::parse) .collect(Collectors.toList()); return new HtsgetResponse( formatJson == null ? null : HtsgetFormat.valueOf(formatJson.asString().toUpperCase()), blocks, md5Json == null ? null : md5Json.asString() ); }
Source:
<code>private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); <START> for (Object sel = selIterator.next(); selIterator.hasNext(); sel = selIterator <END> .next()) { if (sel instanceof RefNode) { RefNode node = (RefNode) sel; String refName = node.getObject().getName(); if (!refName.startsWith(Constants.R_HEADS)) return false; } else return false; } return true; }</code><technical_language>? I find this easier read : while (selIterator.hasNext()) { Object sel = selIterator.next(); ... }</technical_language>

Target:
private boolean onlyBranchesAreSelected(TreeSelection selection) { Iterator selIterator = selection.iterator(); while (selIterator.hasNext()) { Object sel = selIterator.next(); if (sel instanceof RefNode) { RefNode node = (RefNode) sel; String refName = node.getObject().getName(); if (!refName.startsWith(Constants.R_HEADS)) return false; } else return false; } return true; }
Source:
<code>public JRDataSource getDataSource() { String sessionId = getSessionIdProvider().getSessionId(); @SuppressWarnings("unchecked") List<SessionData> all = getHibernateTemplate().find("from SessionData sd where sd.sessionId=?", sessionId); if (all.size() > 1) { throw new IllegalStateException("To much session data was stored for the session."); } if (all.isEmpty()) { <START> throw new IllegalStateException("Session data for session "+sessionId+" was not stored"); <END> } all.get(0).setSessionName(sessionId); return new JRBeanCollectionDataSource(all); }</code><technical_language>formatting</technical_language>

Target:
public JRDataSource getDataSource() { String sessionId = getSessionIdProvider().getSessionId(); @SuppressWarnings("unchecked") List<SessionData> all = getHibernateTemplate().find("from SessionData sd where sd.sessionId=?", sessionId); if (all.size() > 1) { throw new IllegalStateException("To much session data was stored for the session " + sessionId); } if (all.isEmpty()) { throw new IllegalStateException("Session data for session " + sessionId + " was not stored"); } all.get(0).setSessionName(sessionId); return new JRBeanCollectionDataSource(all); }
Source:
<code>public List<BibEntry> performSearch(String query) { List<String> plainReferences = Arrays .stream(query.split("\\r\\r+|\\n\\n+|\\r\\n(\\r\\n)+")) .map(String::trim) .filter(str -> !str.isBlank()) .collect(Collectors.toCollection(ArrayList::new)); if (plainReferences.isEmpty()) { return Collections.emptyList(); <START> } else { <END> return plainReferences .stream() .map(reference -> parseUsingGrobid(reference)) .flatMap(Optional::stream) .map(reference -> parseBibToBibEntry(reference)) .flatMap(Optional::stream) .collect(Collectors.toList()); } }</code><technical_language>Else ommitted</technical_language>

Target:
public List<BibEntry> performSearch(String query) { return Arrays .stream(query.split("\\r\\r+|\\n\\n+|\\r\\n(\\r\\n)+")) .map(String::trim) .filter(str -> !str.isBlank()) .map(reference -> parseUsingGrobid(reference)) .flatMap(Optional::stream) .map(reference -> parseBibToBibEntry(reference)) .flatMap(Optional::stream) .collect(Collectors.toList()); }
Source:
<code>private DatabaseRow getNextRow() throws SQLException { numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow row = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String colName = rsmd.getColumnName(i); int colType = rsmd.getColumnType(i); String formattedColName = _interpreter.formatColumnName(colName); Object result = _interpreter.sqlObjectToAvro(_queryResultSet.getObject(i), formattedColName, _tableSchema); row.addField(formattedColName, result, colType); if (_chunkingKeys.containsKey(colName)) { _chunkingKeys.put(colName, result); } } return row; } catch (SQLException e) { <START> _metrics.updateErrorRate(); <END> if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); return null; } else { LOG.error("Failed to interpret row and skipBadMessage not enabled", e); throw e; } } }</code><technical_language>Log.ERROR SQL Exception</technical_language>

Target:
private DatabaseRow getNextRow() throws SQLException { _numRowsInResult++; try { ResultSetMetaData rsmd = _queryResultSet.getMetaData(); int colCount = rsmd.getColumnCount(); DatabaseRow row = new DatabaseRow(); for (int i = 1; i <= colCount; i++) { String colName = rsmd.getColumnName(i); int colType = rsmd.getColumnType(i); String formattedColName = _interpreter.formatColumnName(colName); Object result = _interpreter.sqlObjectToAvro(_queryResultSet.getObject(i), formattedColName, _tableSchema); row.addField(formattedColName, result, colType); if (_chunkingKeys.containsKey(colName)) { _chunkingKeys.put(colName, result); } } return row; } catch (SQLException e) { _metrics.updateErrorRate(); if (_skipBadMessagesEnabled) { LOG.warn("Skipping row due to SQL exception", e); _metrics.updateSkipBadMessagesRate(); return null; } else { LOG.error("Failed to interpret row and skipBadMessage not enabled", e); throw e; } } }
Source:
<code>protected void openIptablesImpl(Iterable<Integer> inboundPorts, SshMachineLocation machine) { if (inboundPorts == null || Iterables.isEmpty(inboundPorts)) { log.info("No ports to open in iptables (no inbound ports) for at {}", machine, this); } else { log.info("Opening ports in iptables for at {}", entity(), machine); List<String> iptablesRules = Lists.newArrayList(); <START> String iptablesInstallCommands = ""; <END> if (isLocationFirewalldEnabled(machine)) { for (Integer port : inboundPorts) { iptablesRules.add(IptablesCommands.addFirewalldRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT)); } } else { iptablesRules = createIptablesRulesForNetworkInterface(inboundPorts); iptablesInstallCommands = IptablesCommands.saveIptablesRules(); } insertIptablesRules(iptablesRules, iptablesInstallCommands, machine); listIptablesRules(machine); } }</code><technical_language>point in creating a task ssh-ing if command is empty, set null do ssh call in this case all</technical_language>

Target:
protected void openIptablesImpl(Iterable<Integer> inboundPorts, SshMachineLocation machine) { if (inboundPorts == null || Iterables.isEmpty(inboundPorts)) { log.info("No ports to open in iptables (no inbound ports) for at {}", machine, this); } else { log.info("Opening ports in iptables for at {}", entity(), machine); List<String> iptablesRules = Lists.newArrayList(); String iptablesInstallCommands = null; Task<Integer> checkFirewall = checkLocationFirewall(machine); if (checkFirewall.getUnchecked() == 0) { for (Integer port : inboundPorts) { iptablesRules.add(IptablesCommands.addFirewalldRule(Chain.INPUT, Protocol.TCP, port, Policy.ACCEPT)); } } else { iptablesRules = createIptablesRulesForNetworkInterface(inboundPorts); iptablesInstallCommands = IptablesCommands.saveIptablesRules(); } insertIptablesRules(iptablesRules, iptablesInstallCommands, machine); listIptablesRules(machine); } }
Source:
<code>AnonymousClassWriter(ClassName className) { super(className); this.arguments = Optional.absent(); <START> this.types = Lists.newArrayList(); <END> }</code><technical_language>nit: need this of</technical_language>

Target:
AnonymousClassWriter(ClassName className) { super(className); arguments = Optional.absent(); typeVariables = Lists.newArrayList(); }
Source:
<code>protected void executeCommand() { DbUserDAO dao = getDbUserDAO(); DbUser dbUser = dao.getByExternalId(getParameters().getDirectory(), principal.<String> get(PrincipalRecord.ID)); DbUser mappedDbUser = DirectoryUtils.mapPrincipalRecordToDbUser(getParameters().getDirectory(), principal); mappedDbUser.setId(dbUser != null ? dbUser.getId() : Guid.newGuid()); <START> mappedDbUser.setActive(dbUser != null ? dbUser.isActive() : true); <END> DirectoryUtils.syncAndReactivatePrincipal(principal, mappedDbUser, "the user is rectivated as it was added again to the system"); setActionReturnValue(mappedDbUser.getId()); setSucceeded(true); }</code><technical_language>set active... this is entire point no? perform sync this dbuser</technical_language>

Target:
protected void executeCommand() { DbUser userToAdd = getParameters().getUserToAdd(); SyncUsers.sync(Arrays.asList(userToAdd), "The user was found in authz provider while it was added to the oVirt engine"); setActionReturnValue(DbFacade.getInstance().getDbUserDao().getByExternalId(userToAdd.getDomain(), userToAdd.getExternalId()).getId()); setSucceeded(true); }
Source:
<code>public String toString() { <START> return MoreObjects.toStringHelper(this.getClass()) <END> .add("Required formals", requiredFormals) .add("Optional formals", optionalFormals) .add("Varargs formals", restFormals) .add("Return", returnType) .add("Nominal type", nominalType).toString(); }</code><technical_language>Actually, MoreObjects.toStringHelper(this) (without 'getClass'), Guava get class name automatically</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Required formals", requiredFormals) .add("Optional formals", optionalFormals) .add("Varargs formals", restFormals) .add("Return", returnType) .add("Nominal type", nominalType).toString(); }
Source:
<code>public DownloadRequestStrategy into(ImageView imageView) { ImageRequest imageRequest = imageRequestBuilder.build(); GenericDraweeHierarchy genericDraweeHierarchy = genericDraweeHierarchyBuilder.build(); <START> DraweeView draweeView = (DraweeView) imageView; <END> DraweeController draweeController = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .build(); draweeController.setHierarchy(genericDraweeHierarchy); draweeView.setController(draweeController); return new FrescoDownloadRequestStrategy(); }</code><technical_language>Instead of failing a cast here, please throw IllegalArgumentException (at beginning of method) if image view is a DraweeView</technical_language>

Target:
public DownloadRequestStrategy into(ImageView imageView) { if (!(imageView instanceof DraweeView)) { throw new IllegalArgumentException("ImageView must be an instance of DraweeView."); } ImageRequest imageRequest = imageRequestBuilder.build(); GenericDraweeHierarchy genericDraweeHierarchy = genericDraweeHierarchyBuilder.build(); DraweeView draweeView = (DraweeView) imageView; DraweeController draweeController = Fresco.newDraweeControllerBuilder() .setImageRequest(imageRequest) .build(); draweeController.setHierarchy(genericDraweeHierarchy); draweeView.setController(draweeController); return new FrescoDownloadRequestStrategy(); }
Source:
<code>public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; MetadataCacheKey that = (MetadataCacheKey) o; <START> return storeKey.equals( that.storeKey ) && path.equals( that.path ); <END> }</code><technical_language>Objects.equals() instead avoid storeKey null path null</technical_language>

Target:
public boolean equals( Object o ) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; MetadataCacheKey that = (MetadataCacheKey) o; return Objects.equals( storeKey, that.storeKey ) && Objects.equals( path, that.path ); }