auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final Geocache cache = ECApi.searchByGeoCode(geocode); <START> if (cache == null) { <END> return null; } final SearchResult searchResult = new SearchResult(cache); return searchResult; }</code><technical_language>This line replaced single line java return cache != null ? new SearchResult(cache) : null;</technical_language>

Target:
public SearchResult searchByGeocode(final String geocode, final String guid, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_loadpage); final Geocache cache = ECApi.searchByGeoCode(geocode); return cache != null ? new SearchResult(cache) : null; }
Source:
<code>public String[] getPeerSupportedSignatureAlgorithms() { <START> return new String[0]; <END> }</code><technical_language>Consider returning a constant</technical_language>

Target:
public String[] getPeerSupportedSignatureAlgorithms() { return EmptyArrays.EMPTY_STRINGS; }
Source:
<code>public synchronized void bumpTimestamp(long newTimestamp) throws TimestampIOException { if (newTimestamp > _timestampCounter.get()) { timestampBlockManager.reserveNextBlock(newTimestamp); <START> _maxReservedTimestamp = newTimestamp; <END> _timestampCounter.updateAndGet(oldTS -> Math.max(oldTS, newTimestamp)); } }</code><technical_language>_reserveNextBlock_ assigns a new _maxReservedTimestamp, overwritten. updateAndGet ensures assignment (it a loop), is more needed here; a simple _compareAndSet_ initial _timestampCounter.get() suffice</technical_language>

Target:
public synchronized void bumpTimestamp(long newTimestamp) throws TimestampIOException { newTimestamp = roundUp(newTimestamp); if (newTimestamp > _timestampCounter.get()) { if (newTimestamp> _maxReservedTimestamp) { reserveNextBlock(newTimestamp); } long currentTimestampCounter; while ((currentTimestampCounter = _timestampCounter.get()) < newTimestamp) { if (_timestampCounter.compareAndSet(currentTimestampCounter, newTimestamp)) { break; } } } }
Source:
<code>public void waitForDialogVisible() { waitForElementByElement(dialog); <START> waitForElementVisibleByElement(dialog); <END> }</code><technical_language>methods similar. Consider one</technical_language>

Target:
public void waitForDialogVisible() { waitForElementVisibleByElement(dialog); }
Source:
<code>public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RC_SAVE) { if (resultCode != Activity.RESULT_OK) { Log.e(TAG, "SAVE: Canceled by user"); } <START> mPendingResolutionLiveData.setValue(null); <END> setSuccess(mPendingIdpResponse); return true; } return false; }</code><technical_language>I this is right approach. sense null out state done LiveDatas designed subscribed config change. Thus, noted elsewhere, need a SingleLiveEvent style LiveData prevent sign-in tasks spammed config change. Nulling out intent prevent sign-in is complete, in middle section, vulnerable config changes</technical_language>

Target:
public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == RC_SAVE) { if (resultCode != Activity.RESULT_OK) { Log.e(TAG, "SAVE: Canceled by user"); } setSuccess(mPendingIdpResponse); return true; } return false; }
Source:
<code>public DecisionNode getDecisionByName(String name) { if ( name == null ) { return null; } for ( DecisionNode dn : this.decisions.values() ) { <START> if (dn.getName() != null && name.equals(dn.getName())) { <END> return dn; } } return null; }</code><technical_language>dn.getName() != null is necessary if Objects.equals(name, dn.getName())</technical_language>

Target:
public DecisionNode getDecisionByName(String name) { if ( name == null ) { return null; } for ( DecisionNode dn : this.decisions.values() ) { if (Objects.equals(name, dn.getName())) { return dn; } } return null; }
Source:
<code><START> private void pushDataToImporters(int count, int loops) throws Exception { <END> CountDownLatch latch = asyncPushDataToImporters(count, loops); latch.await(); }</code><technical_language>Whats purpose of creating this wrapper? logic change. Is for change of name of method didnt like</technical_language>

Target:
private void pushDataToImporters(int count, int loops) throws Exception { asyncPushDataToImporters(count, loops); waitForData(); }
Source:
<code>public static void propagateIfFatal(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof ExecutionException) <START> propagateIfFatal(throwable.getCause()); <END> if (throwable instanceof Error) throw (Error) throwable; }</code><technical_language>Again, do this</technical_language>

Target:
public static void propagateIfFatal(Throwable throwable) { if (throwable instanceof InterruptedException) throw new RuntimeInterruptedException((InterruptedException) throwable); if (throwable instanceof Error) throw (Error) throwable; }
Source:
<code>public void clickInstallButton() { waitForElementVisibleByElement(bannerButton); if (bannerButton.getText().contains("Install")) { bannerButton.click(); PageObjectLogging.log("clickInstallButton", "Install button was clicked", true); } else { <START> PageObjectLogging.log("clickInstallButton", "Install button were not visible", false, driver); <END> } }</code><technical_language>install button visible\* :dancer:</technical_language>

Target:
public void clickInstallButton() { waitForElementVisibleByElement(bannerButton); if (bannerButton.getText().contains("Install")) { bannerButton.click(); PageObjectLogging.log("clickInstallButton", "Install button was clicked", true); } else { PageObjectLogging.log("clickInstallButton", "Install button was not visible", false, driver); } }
Source:
<code>public void initialize() { INIConfiguration config = Utilities.parseConfig(abstractEntryClient.getConfigFile()); String cromwellVersion = config.getString("cromwell-version", DEFAULT_CROMWELL_VERSION); String cromwellLocation = "<LINK_0>" + cromwellVersion + "/cromwell-" + cromwellVersion + ".jar"; if (!Objects.equals(DEFAULT_CROMWELL_VERSION, cromwellVersion)) { System.out.println("Running with Cromwell " + cromwellVersion + " , Dockstore tests with " + DEFAULT_CROMWELL_VERSION); } String libraryLocation = System.getProperty("user.home") + File.separator + ".dockstore" + File.separator + "libraries" + File.separator; URL cromwellURL; String cromwellFileName; try { cromwellURL = new URL(cromwellLocation); cromwellFileName = new File(cromwellURL.toURI().getPath()).getName(); } catch (MalformedURLException | URISyntaxException e) { throw new RuntimeException("Could not create " + LAUNCHER_NAME + " location", e); } String cromwellTarget = libraryLocation + cromwellFileName; File cromwellTargetFile = new File(cromwellTarget); if (!cromwellTargetFile.exists()) { try { FileUtils.copyURLToFile(cromwellURL, cromwellTargetFile); } catch (IOException e) { throw new RuntimeException("Could not download " + LAUNCHER_NAME + " location", e); } } <START> exectionFile = cromwellTargetFile; <END> }</code><technical_language>spell exectionFile -> executionFile</technical_language>

Target:
public void initialize() { INIConfiguration config = Utilities.parseConfig(abstractEntryClient.getConfigFile()); String cromwellVersion = config.getString("cromwell-version", DEFAULT_CROMWELL_VERSION); String cromwellLocation = "<LINK_0>" + cromwellVersion + "/cromwell-" + cromwellVersion + ".jar"; if (!Objects.equals(DEFAULT_CROMWELL_VERSION, cromwellVersion)) { System.out.println("Running with Cromwell " + cromwellVersion + " , Dockstore tests with " + DEFAULT_CROMWELL_VERSION); } String libraryLocation = System.getProperty("user.home") + File.separator + ".dockstore" + File.separator + "libraries" + File.separator; URL cromwellURL; String cromwellFileName; try { cromwellURL = new URL(cromwellLocation); cromwellFileName = new File(cromwellURL.toURI().getPath()).getName(); } catch (MalformedURLException | URISyntaxException e) { throw new RuntimeException("Could not create " + launcherName + " location", e); } String cromwellTarget = libraryLocation + cromwellFileName; File cromwellTargetFile = new File(cromwellTarget); if (!cromwellTargetFile.exists()) { try { FileUtils.copyURLToFile(cromwellURL, cromwellTargetFile); } catch (IOException e) { throw new RuntimeException("Could not download " + launcherName + " location", e); } } executionFile = cromwellTargetFile; }
Source:
<code>public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(!Thread.holdsLock(this), "Can not enqueue pages while holding a lock on this"); requireNonNull(pages, "page is null"); if (!state.get().canAddPages()) { return; } long bytesAdded = pages.stream().mapToLong(SerializedPage::getRetainedSizeInBytes).sum(); memoryManager.updateMemoryUsage(bytesAdded); long rowCount = pages.stream().mapToLong(SerializedPage::getPositionCount).sum(); totalRowsAdded.addAndGet(rowCount); totalPagesAdded.addAndGet(pages.size()); <START> outstandingPagePerLifespan.computeIfAbsent(lifespan, ignore -> new AtomicLong()).addAndGet(pages.size()); <END> List<SerializedPageReference> serializedPageReferences = pages.stream() .map(pageSplit -> new SerializedPageReference( pageSplit, 1, () -> { long oustandingPage = outstandingPagePerLifespan.get(lifespan).decrementAndGet(); Consumer<Lifespan> callback = lifespanFinishedCallback; if (oustandingPage == 0 && callback != null && noMorePagesForLifespan.contains(lifespan)) { callback.accept(lifespan); } memoryManager.updateMemoryUsage(-pageSplit.getRetainedSizeInBytes()); })) .collect(toImmutableList()); masterBuffer.addPages(serializedPageReferences); for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { if (masterBuffer.isEmpty()) { break; } clientBuffer.loadPagesIfNecessary(masterBuffer); } }</code><technical_language>nit:</technical_language>

Target:
public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(!Thread.holdsLock(this), "Can not enqueue pages while holding a lock on this"); requireNonNull(lifespan, "lifespan is null"); requireNonNull(pages, "page is null"); checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback must be set before enqueueing data"); if (!state.get().canAddPages() || noMorePagesForLifespan.contains(lifespan)) { return; } long bytesAdded = pages.stream().mapToLong(SerializedPage::getRetainedSizeInBytes).sum(); memoryManager.updateMemoryUsage(bytesAdded); long rowCount = pages.stream().mapToLong(SerializedPage::getPositionCount).sum(); totalRowsAdded.addAndGet(rowCount); totalPagesAdded.addAndGet(pages.size()); outstandingPageCountPerLifespan.computeIfAbsent(lifespan, ignored -> new AtomicLong()).addAndGet(pages.size()); List<SerializedPageReference> serializedPageReferences = pages.stream() .map(pageSplit -> new SerializedPageReference( pageSplit, 1, () -> dereferencePage(pageSplit, lifespan))) .collect(toImmutableList()); masterBuffer.addPages(serializedPageReferences); for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { if (masterBuffer.isEmpty()) { break; } clientBuffer.loadPagesIfNecessary(masterBuffer); } }
Source:
<code>public void testGetBalance() throws Exception { client.getBalance(); <START> verify(client.balance).execute(); <END> }</code><technical_language>Alrighty</technical_language>

Target:
public void testGetBalance() throws Exception { BalanceResponse response = client.getBalance(); verify(client.balance).execute(); Assert.assertEquals(sentinel, response); }
Source:
<code>public void testCounts(String acc, int numberAlignments, int numberUnalignments) { <START> if (!SRAAccession.isSupported()) return; <END> SamReader reader = SamReaderFactory.make().validationStringency(ValidationStringency.SILENT).open( SamInputResource.of(new SRAAccession(acc)) ); final SAMRecordIterator samRecordIterator = reader.iterator(); int countAlignments = 0, countUnalignments = 0; while (true) { boolean hasRecord = samRecordIterator.hasNext(); SAMRecord record = null; try { record = samRecordIterator.next(); Assert.assertTrue(hasRecord); } catch (NoSuchElementException e) { Assert.assertFalse(hasRecord); } Assert.assertEquals(hasRecord, record != null); if (record == null) { break; } if (record.getReadUnmappedFlag()) { countUnalignments++; } else { countAlignments++; } } Assert.assertEquals(numberAlignments, countAlignments); Assert.assertEquals(numberUnalignments, countUnalignments); }</code><technical_language>If test skipped, throw a SkipException in accordance TestNG standard practice (applies tests well)</technical_language>

Target:
public void testCounts(String acc, int numberAlignments, int numberUnalignments) { if (!SRAAccession.isSupported()) return; SamReader reader = SamReaderFactory.make().validationStringency(ValidationStringency.SILENT).open( SamInputResource.of(new SRAAccession(acc)) ); final SAMRecordIterator samRecordIterator = reader.iterator(); checkAlignedUnalignedCountsByIterator(samRecordIterator, numberAlignments, numberUnalignments); }
Source:
<code>public void testIncorrectProperty() { final String content = DOCKSTORE12_YAML.replaceFirst("workflows", "workflow"); try { <START> DockstoreYamlHelper.readAsDockstoreYaml12(content); <END> } catch (DockstoreYamlHelper.DockstoreYamlException e) { Assert.assertTrue(e.getMessage().contains("Error reading .dockstore.yml:")); } }</code><technical_language>This test work if throws some other exception throw exception</technical_language>

Target:
public void testIncorrectProperty() { final String content = DOCKSTORE12_YAML.replaceFirst("workflows", "workflow"); try { DockstoreYamlHelper.readAsDockstoreYaml12(content); TestCase.fail("Should not be able to validate .dockstore.yml"); } catch (DockstoreYamlHelper.DockstoreYamlException e) { Assert.assertTrue(e.getMessage().contains("Error reading .dockstore.yml: Cannot create property=workflow")); } catch (Exception e) { TestCase.fail("Should have seen a DockstoreYamlException"); } }
Source:
<code>private List<Broker> fetchBrokers() { final List<Broker> brokers = new ArrayList<Broker>(); try { final CuratorFramework curator = zkFactory.get(); for (final String brokerId : curator.getChildren().forPath(_BROKERS_IDS_PATH)) { try { final byte[] brokerData = curator.getData().forPath(_BROKERS_IDS_PATH + "/" + brokerId); brokers.add(getBroker(brokerData)); } catch (Exception e) { <START> LOG.info("Failed to fetch connection string for broker {}: {}", brokerId, e); <END> } } } catch (Exception e) { LOG.error("Failed to fetch list of brokers from ZooKeeper: {}", e); } brokers.sort(null); return brokers; }</code><technical_language>I is working way. interface of slf4j is: info(String msg); info(String format, Object arg); info(String format, Object... args); info(String msg, Throwable t); if pass in parameters treat Throwable object calls e.toString() loose stacktrace</technical_language>

Target:
private List<Broker> fetchBrokers() { final List<Broker> brokers = new ArrayList<Broker>(); try { final CuratorFramework curator = zkFactory.get(); for (final String brokerId : curator.getChildren().forPath(_BROKERS_IDS_PATH)) { try { final byte[] brokerData = curator.getData().forPath(_BROKERS_IDS_PATH + "/" + brokerId); brokers.add(Broker.fromByteJson(brokerData)); } catch (Exception e) { LOG.info(String.format("Failed to fetch connection string for broker %s", brokerId), e); } } } catch (Exception e) { LOG.error("Failed to fetch list of brokers from ZooKeeper", e); } return brokers; }
Source:
<code>public int[] readSensor() throws InvalidSensorException { ByteBuffer rawData = super.readBuffer(); if (rawData != null && rawData.remaining() > 7) { rawData.rewind(); long data = Long.reverseBytes(rawData.getLong()); values[0] = (int) data & 0xFFFFFFFF; values[1] = (int) (data >> 32) & 0xFFFFFFFF; age = System.currentTimeMillis(); return values; } <START> if (System.currentTimeMillis() - age > MAX_AGE) { <END> throw new InvalidSensorException("CAN data oudated For CAN sensor " + getName()); } LogKitten.v("Cached Sensor Value Used\n"); return values; }</code><technical_language>name age is misleading, especially MAX_AGE is maximum of age</technical_language>

Target:
public int[] readSensor() throws InvalidSensorException { ByteBuffer rawData = super.readBuffer(); if (rawData != null && rawData.remaining() >= 8) { rawData.rewind(); long data = Long.reverseBytes(rawData.getLong()); values[0] = (int) data & 0xFFFFFFFF; values[1] = (int) (data >> 32) & 0xFFFFFFFF; lastRead = System.currentTimeMillis(); return values; } if (System.currentTimeMillis() - lastRead > CANSensor.MAX_AGE) { throw new InvalidSensorException("CAN data oudated For CAN sensor " + getName()); } LogKitten.v("Cached Sensor Value Used\n"); return values; }
Source:
<code>public InternalFetchConnection(PackTransport transport, <START> final UploadPackFactory<C> uploadPackFactory, final C req, <END> final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream() { { buffer = new byte[MIN_CLIENT_BUFFER]; } }; out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Upload-Pack") { @Override public void run() { try { final UploadPack rp = uploadPackFactory.create(req, remote); rp.upload(out_r, in_w, null); } catch (ServiceNotEnabledException | ServiceNotAuthorizedException e) { } catch (IOException | RuntimeException err) { err.printStackTrace(); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }</code><technical_language>Unrelated formatting changes</technical_language>

Target:
public InternalFetchConnection(PackTransport transport, final UploadPackFactory<C> uploadPackFactory, final C req, final Repository remote) throws TransportException { super(transport); final PipedInputStream in_r; final PipedOutputStream in_w; final PipedInputStream out_r; final PipedOutputStream out_w; try { in_r = new PipedInputStream(); in_w = new PipedOutputStream(in_r); out_r = new PipedInputStream() { { buffer = new byte[MIN_CLIENT_BUFFER]; } }; out_w = new PipedOutputStream(out_r); } catch (IOException err) { remote.close(); throw new TransportException(uri, JGitText.get().cannotConnectPipes, err); } worker = new Thread("JGit-Upload-Pack") { @Override public void run() { try { final UploadPack rp = uploadPackFactory.create(req, remote); rp.upload(out_r, in_w, null); } catch (ServiceNotEnabledException | ServiceNotAuthorizedException e) { } catch (IOException err) { err.printStackTrace(); } catch (RuntimeException err) { err.printStackTrace(); } finally { try { out_r.close(); } catch (IOException e2) { } try { in_w.close(); } catch (IOException e2) { } remote.close(); } } }; worker.start(); init(in_r, out_w); readAdvertisedRefs(); }
Source:
<code>public static boolean isDefault(final String type) { return Stream .of(BuiltInType.values()) <START> .anyMatch(dataType -> Objects.equals(upperCase(dataType.getName()), upperCase(type))); <END> }</code><technical_language>check BuiltInType.getNames() some alias too</technical_language>

Target:
public static boolean isDefault(final String type) { return builtInTypeNames() .anyMatch(builtInTypeName -> Objects.equals(upperCase(builtInTypeName), upperCase(type))); }
Source:
<code>public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; if (errorMessageText != null && !errorMessageText.isDisposed()) { errorMessageText.setText(errorMessage == null ? " \n " : errorMessage); boolean isNotEmpty = <START> !StringConverter.removeWhiteSpaces(errorMessage).isEmpty(); <END> boolean hasError = errorMessage != null && !isNotEmpty; errorMessageText.setEnabled(hasError); errorMessageText.setVisible(hasError); errorMessageText.getParent().update(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { button.setEnabled(errorMessage == null); } } }</code><technical_language>This NPE. failing test. Please check other changes failing pattern</technical_language>

Target:
public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; if (errorMessageText != null && !errorMessageText.isDisposed()) { errorMessageText.setText(errorMessage == null ? " \n " : errorMessage); boolean hasError = errorMessage != null && (StringConverter.removeWhiteSpaces(errorMessage)).length() > 0; errorMessageText.setEnabled(hasError); errorMessageText.setVisible(hasError); errorMessageText.getParent().update(); Control button = getButton(IDialogConstants.OK_ID); if (button != null) { button.setEnabled(errorMessage == null); } } }
Source:
<code>private void importDatabase() { <START> new AlertDialog.Builder(getActivity()) <END> .setTitle(R.string.database_import_label) .setMessage(R.string.database_import_warning) .setNegativeButton(R.string.no, null) .setPositiveButton(R.string.confirm_label, (dialog, which) -> { if (Build.VERSION.SDK_INT >= 19) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT) .setType("* *"); startActivityForResult(Intent.createChooser(intent, getString(R.string.import_select_file)), REQUEST_CODE_RESTORE_DATABASE); } }) .show(); }</code><technical_language>In this case, I find easier read original version. needs indentation shows more belongs together</technical_language>

Target:
private void importDatabase() { final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); alert.setTitle(R.string.database_import_label); alert.setMessage(R.string.database_import_warning); alert.setNegativeButton(R.string.no, null); alert.setPositiveButton(R.string.confirm_label, (dialog, which) -> { if (Build.VERSION.SDK_INT >= 19) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.setType("* *"); startActivityForResult(Intent.createChooser(intent, getString(R.string.import_select_file)), REQUEST_CODE_RESTORE_DATABASE); } } ); alert.show(); }
Source:
<code>public ExternalIdPConfig getIdPConfigByRealm(String realm, String tenantDomain) { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for realm: " + realm); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager .getEnabledIdPByRealmId(realm, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given realm"); } } } catch (IdentityProviderManagementException e) { <START> log.error("Exception while getting IdP by realm", e); <END> } return externalIdPConfig; }</code><technical_language>Ideally throwing this exception client decide do it. Lets change this throw exception in authentication framework catch exception, log continue</technical_language>

Target:
public ExternalIdPConfig getIdPConfigByRealm(String realm, String tenantDomain) throws IdentityProviderManagementException { ExternalIdPConfig externalIdPConfig = null; IdentityProvider idpDO = null; if (log.isDebugEnabled()) { log.debug("Trying to find the IdP for realm: " + realm); } try { IdentityProviderManager idpManager = IdentityProviderManager.getInstance(); idpDO = idpManager .getEnabledIdPByRealmId(realm, tenantDomain); if (idpDO != null) { if (log.isDebugEnabled()) { log.debug("A registered IdP was found"); } externalIdPConfig = new ExternalIdPConfig(idpDO); } else { if (log.isDebugEnabled()) { log.debug("A registered IdP was not found the given realm"); } } } catch (IdentityProviderManagementException e) { throw new IdentityProviderManagementException("Exception while getting IdP by realm", e); } return externalIdPConfig; }
Source:
<code>public static int handleTwitterError(Twitter twitter, Exception exception) { if(exception instanceof TwitterException) { TwitterException e = (TwitterException)exception; if(e.exceededRateLimitation()) { LOGGER.warn("Rate Limit Exceeded"); try { Thread.sleep(retry); <START> } catch (InterruptedException e1) <END> return 1; } else if(e.isCausedByNetworkIssue()) { LOGGER.info("Twitter Network Issues Detected. Backing off..."); LOGGER.info("{} - {}", e.getExceptionCode(), e.getLocalizedMessage()); try { Thread.sleep(retry); } catch (InterruptedException e1) return 1; } else if(e.isErrorMessageAvailable()) { if(e.getMessage().toLowerCase().contains("does not exist")) { LOGGER.warn("User does not exist..."); return 100; } else { return 1; } } else { if(e.getExceptionCode().equals("ced778ef-0c669ac0")) { return 5; } else { LOGGER.warn("Unknown Twitter Exception..."); LOGGER.warn(" Account: {}", twitter); LOGGER.warn(" Access: {}", e.getAccessLevel()); LOGGER.warn(" Code: {}", e.getExceptionCode()); LOGGER.warn(" Message: {}", e.getLocalizedMessage()); return 1; } } } else if(exception instanceof RuntimeException) { LOGGER.warn("TwitterGrabber: Unknown Runtime Error", exception.getMessage()); return 1; } else { LOGGER.info("Completely Unknown Exception: {}", exception); return 1; } }</code><technical_language>I this party of pull request, swallowing InterruptedExceptions. fix this open a ticket fix it</technical_language>

Target:
public static int handleTwitterError(Twitter twitter, Exception exception) { if(exception instanceof TwitterException) { TwitterException e = (TwitterException)exception; if(e.exceededRateLimitation()) { LOGGER.warn("Rate Limit Exceeded"); try { Thread.sleep(retry); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return 1; } else if(e.isCausedByNetworkIssue()) { LOGGER.info("Twitter Network Issues Detected. Backing off..."); LOGGER.info("{} - {}", e.getExceptionCode(), e.getLocalizedMessage()); try { Thread.sleep(retry); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } return 1; } else if(e.isErrorMessageAvailable()) { if(e.getMessage().toLowerCase().contains("does not exist")) { LOGGER.warn("User does not exist..."); return 100; } else { return 1; } } else { if(e.getExceptionCode().equals("ced778ef-0c669ac0")) { return 5; } else { LOGGER.warn("Unknown Twitter Exception..."); LOGGER.warn(" Account: {}", twitter); LOGGER.warn(" Access: {}", e.getAccessLevel()); LOGGER.warn(" Code: {}", e.getExceptionCode()); LOGGER.warn(" Message: {}", e.getLocalizedMessage()); return 1; } } } else if(exception instanceof RuntimeException) { LOGGER.warn("TwitterGrabber: Unknown Runtime Error", exception.getMessage()); return 1; } else { LOGGER.info("Completely Unknown Exception: {}", exception); return 1; } }
Source:
<code>public List<QualifiedObjectName> listTables(Session session, QualifiedTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); Optional<CatalogMetadata> catalog = getOptionalCatalogMetadata(session, prefix.getCatalogName()); Set<QualifiedObjectName> tables = new LinkedHashSet<>(); if (catalog.isPresent()) { CatalogMetadata catalogMetadata = catalog.get(); <START> Optional<String> schemaName = prefix.getSchemaName(); <END> for (ConnectorId connectorId : catalogMetadata.listConnectorIds()) { ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); ConnectorSession connectorSession = session.toConnectorSession(connectorId); metadata.listTables(connectorSession, schemaName).stream() .map(convertFromSchemaTableName(prefix.getCatalogName())::apply) .forEach(tables::add); } } return ImmutableList.copyOf(tables); }</code><technical_language>inline this (like do for prefix.getCatalogName())</technical_language>

Target:
public List<QualifiedObjectName> listTables(Session session, QualifiedTablePrefix prefix) { requireNonNull(prefix, "prefix is null"); Optional<CatalogMetadata> catalog = getOptionalCatalogMetadata(session, prefix.getCatalogName()); Set<QualifiedObjectName> tables = new LinkedHashSet<>(); if (catalog.isPresent()) { CatalogMetadata catalogMetadata = catalog.get(); for (ConnectorId connectorId : catalogMetadata.listConnectorIds()) { ConnectorMetadata metadata = catalogMetadata.getMetadataFor(connectorId); ConnectorSession connectorSession = session.toConnectorSession(connectorId); metadata.listTables(connectorSession, prefix.getSchemaName()).stream() .map(convertFromSchemaTableName(prefix.getCatalogName())) .filter(prefix::matches) .forEach(tables::add); } } return ImmutableList.copyOf(tables); }
Source:
<code>public boolean isSpider(String userAgent) { <START> return spiderPattern.matcher(userAgent).find() && ! wikimediaBotPattern.matcher(userAgent).find(); <END> }</code><technical_language>Suggest changing to: if(userAgent.equals("-"){ return true; } return spiderPattern.matcher(userAgent).find() && ! wikimediaBotPattern.matcher(userAgent).find(); A lot of automata in a user agent full stop get it. This is unhelpful analytics perspective exceedingly helpful a user-agent perspective, 99.99999% of actual humans do this</technical_language>

Target:
public boolean isSpider(String userAgent) { if ("-".equals(userAgent)) return true; else return spiderPattern.matcher(userAgent).find() && ! wikimediaBotPattern.matcher(userAgent).find(); }
Source:
<code>protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoUtil.allowed(file)) { return; } GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)){ return; } PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { <START> problemsHolder.registerProblem(packageClause, "Multiple packages in directory", new GoMultiplePackagesQuickFix(packageClause, packages, problemsHolder.isOnTheFly())); <END> } } }</code><technical_language>For !onTheFly mode add quick fix for variant of package renaming</technical_language>

Target:
protected void checkFile(@NotNull GoFile file, @NotNull ProblemsHolder problemsHolder) { if (!GoUtil.allowed(file)) { return; } GoPackageClause packageClause = file.getPackage(); if (packageClause != null) { String packageName = file.getPackageName(); if (packageName == null || packageName.equals(GoConstants.DOCUMENTATION)){ return; } PsiDirectory dir = file.getContainingDirectory(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir); packages.remove(GoConstants.DOCUMENTATION); if (packages.size() > 1) { ArrayList<LocalQuickFix> fixes = new ArrayList<LocalQuickFix>(); if (problemsHolder.isOnTheFly()) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, packageName, packages, true)); } else { for (String name : packages) { fixes.add(new GoMultiplePackagesQuickFix(packageClause, name, packages, false)); } } problemsHolder.registerProblem(packageClause, "Multiple packages in directory", fixes.toArray(new LocalQuickFix[fixes.size()])); } } }
Source:
<code>public IServer createEAP5Server(String homeDir) { IServer s = null; try { s = createRemoteServer(IJBossToolingConstants.EAP_50, host, homeDir, "default"); } catch(CoreException ce) { <START> fail(ce.getMessage()); <END> } if( s == null ) { fail("Server not created."); } return s; }</code><technical_language>Recommendation for this similar "no context" failures: fail("Failure creating remote server " + ce.getMessage()); This error reports CI builds more informative needing lookup source grok it</technical_language>

Target:
public IServer createEAP5Server(String homeDir) { IServer s = null; try { s = createRemoteServer(IJBossToolingConstants.EAP_50, host, homeDir, "default"); } catch(CoreException ce) { fail("Server not created: " + ce.getMessage()); } if( s == null ) { fail("Server not created."); } return s; }
Source:
<code>private String transformToHeaderValue(Directive... directives) { <START> final StringBuilder sb = new StringBuilder(); <END> for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); }</code><technical_language>For consistency project, please remove final keyword here</technical_language>

Target:
private String transformToHeaderValue(Directive... directives) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < directives.length - 1; i++) { sb.append(directives[i].headerValue).append(", "); } sb.append(directives[directives.length - 1].headerValue); return sb.toString(); }
Source:
<code>public void testBuilderWithDefaultValues() { AccountAttributes observedAccountAttributes = AccountAttributes.builder().build(); <START> assertEquals(null, observedAccountAttributes.createdAt); <END> assertEquals(null, observedAccountAttributes.getEmail()); assertEquals(null, observedAccountAttributes.getGoogleId()); assertEquals(null, observedAccountAttributes.getInstitute()); assertFalse(observedAccountAttributes.isInstructor()); assertEquals(null, observedAccountAttributes.getName()); assertEquals(null, observedAccountAttributes.studentProfile); }</code><technical_language>assertNull() instead? applies for other places</technical_language>

Target:
public void testBuilderWithDefaultValues() { AccountAttributes observedAccountAttributes = AccountAttributes.builder().build(); assertNull(observedAccountAttributes.createdAt); assertNull(observedAccountAttributes.getEmail()); assertNull(observedAccountAttributes.getGoogleId()); assertNull(observedAccountAttributes.getInstitute()); assertFalse(observedAccountAttributes.isInstructor()); assertNull(observedAccountAttributes.getName()); assertNull(observedAccountAttributes.studentProfile); }
Source:
<code>public VelocityEngine getVelocityEngine(@VelocityProperties String velocityProperties, Logger logger) throws UnableToCompleteException { InputStream inputStream = null; Properties properties = new Properties(); try { inputStream = this.getClass().getClassLoader().getResourceAsStream(velocityProperties); properties.load(inputStream); return new VelocityEngine(properties); } catch (Exception e) { logger.die("Cannot load velocity properties from " + velocityProperties); } finally { if (inputStream != null) { <START> try { <END> inputStream.close(); } catch (IOException e) { logger.die("Cannot load velocity properties from " + velocityProperties); } } } return null; }</code><technical_language>is this needed</technical_language>

Target:
public VelocityEngine getVelocityEngine(@VelocityProperties String velocityProperties, Logger logger) throws UnableToCompleteException { try { InputStream inputStream = null; try { inputStream = this.getClass().getClassLoader().getResourceAsStream(velocityProperties); Properties properties = new Properties(); properties.load(inputStream); return new VelocityEngine(properties); } finally { if (inputStream != null) { inputStream.close(); } } } catch (Exception e) { logger.die("Cannot load velocity properties from " + velocityProperties); return null; } }
Source:
<code>public JSONObject searchProjectsByCreationDateandString(HttpSession session, JSONObject json) { String searchStr = json.getString("str"); String from = json.getString("from"); String to = json.getString("to"); String progress = json.getString("progress"); JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); try { Collection<Project> projects = null; <START> if (searchStr != null && !isStringEmptyOrNull(searchStr)) { <END> projects = requestManager.listAllProjectsBySearch(searchStr); } else { projects = requestManager.listAllProjects(); } for (Project project : projects) { if (progress.equals("all") || progress.equals(project.getProgress().getKey())) { if (!isStringEmptyOrNull(from) && !isStringEmptyOrNull(to)) { if (project.getCreationDate() != null) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date startDate = df.parse(from); Date endDate = df.parse(to); Date creationDate = project.getCreationDate(); if ((creationDate.after(startDate) && creationDate.before(endDate)) || creationDate.equals(startDate) || creationDate.equals(endDate)) { jsonArray.add(projectRowBuilder(project)); } } } else { jsonArray.add(projectRowBuilder(project)); } } } jsonObject.put("html", jsonArray); return jsonObject; } catch (Exception e) { log.error("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }</code><technical_language>This shortened to: if (isStringEmptyOrNull(searchStr))</technical_language>

Target:
public JSONObject searchProjectsByCreationDateandString(HttpSession session, JSONObject json) { String searchStr = json.getString("str"); String from = json.getString("from"); String to = json.getString("to"); String progress = json.getString("progress"); JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); try { Collection<Project> projects = null; if (!isStringEmptyOrNull(searchStr)) { projects = requestManager.listAllProjectsBySearch(searchStr); } else { projects = requestManager.listAllProjects(); } for (Project project : projects) { if (progress.equals("all") || progress.equals(project.getProgress().getKey())) { if (!isStringEmptyOrNull(from) && !isStringEmptyOrNull(to)) { if (project.getCreationDate() != null) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date startDate = df.parse(from); Date endDate = df.parse(to); Date creationDate = project.getCreationDate(); if ((creationDate.after(startDate) && creationDate.before(endDate)) || creationDate.equals(startDate) || creationDate.equals(endDate)) { jsonArray.add(projectRowBuilder(project)); } } } else { jsonArray.add(projectRowBuilder(project)); } } } jsonObject.put("html", jsonArray); return jsonObject; } catch (Exception e) { log.error("Failed", e); return JSONUtils.SimpleJSONError("Failed: " + e.getMessage()); } }
Source:
<code>public void canSerializeWithSubstudy() throws Exception { ExternalIdentifierInfo info = new ExternalIdentifierInfo("AAA", "oneSubstudy", false); JsonNode node = BridgeObjectMapper.get().valueToTree(info); assertEquals("AAA", node.get("identifier").asText()); <START> assertEquals(false, node.get("assigned").asBoolean()); <END> assertEquals("oneSubstudy", node.get("substudyId").asText()); assertEquals("ExternalIdentifier", node.get("type").asText()); assertEquals(4, node.size()); ExternalIdentifierInfo resInfo = BridgeObjectMapper.get().treeToValue(node, ExternalIdentifierInfo.class); assertEquals(info, resInfo); }</code><technical_language>Minor: asBoolean() parses strings. booleanValue()</technical_language>

Target:
public void canSerializeWithSubstudy() throws Exception { ExternalIdentifierInfo info = new ExternalIdentifierInfo("AAA", "oneSubstudy", false); JsonNode node = BridgeObjectMapper.get().valueToTree(info); assertEquals("AAA", node.get("identifier").textValue()); assertEquals(false, node.get("assigned").booleanValue()); assertEquals("oneSubstudy", node.get("substudyId").textValue()); assertEquals("ExternalIdentifier", node.get("type").textValue()); assertEquals(4, node.size()); ExternalIdentifierInfo resInfo = BridgeObjectMapper.get().treeToValue(node, ExternalIdentifierInfo.class); assertEquals(info, resInfo); }
Source:
<code>public void testAutoReconnect() throws Exception { ClientConfig config = new ClientConfig(); config.setReconnectOnConnectionLoss(true); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); tearDown(); for (int i = 0; (i < 40) && (client.getConnectedHostList().size() > 0); i++) { Thread.sleep(500); } assertTrue(client.getConnectedHostList().isEmpty()); Thread.sleep(2000); setUp(); boolean failed = true; for (int i = 0; i < 40; i++) { if (client.getConnectedHostList().size() > 0) { failed = false; break; } Thread.sleep(500); } if (failed) { fail("Client should have been reconnected"); } tearDown(); for (int i = 0; (i < 40) && (client.getConnectedHostList().size() > 0); i++) { Thread.sleep(500); } assertTrue(client.getConnectedHostList().isEmpty()); client.close(); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); for (StackTraceElement[] st : stMap.values()) { for (StackTraceElement ste : st) { <START> if (ste.getMethodName().contains("connectToOneServerWithRetry")) { <END> fail("Client reconnect thread didn't die."); } } } }</code><technical_language>This is kind of hackish. If method name changes, this catch it</technical_language>

Target:
public void testAutoReconnect() throws Exception { ClientConfig config = new ClientConfig(); config.setReconnectOnConnectionLoss(true); Client client = ClientFactory.createClient(config); client.createConnection("localhost"); tearDown(); for (int i = 0; (i < 40) && (client.getConnectedHostList().size() > 0); i++) { Thread.sleep(500); } assertTrue(client.getConnectedHostList().isEmpty()); Thread.sleep(2000); setUp(); boolean failed = true; for (int i = 0; i < 40; i++) { if (client.getConnectedHostList().size() > 0) { failed = false; break; } Thread.sleep(500); } if (failed) { fail("Client should have been reconnected"); } tearDown(); for (int i = 0; (i < 40) && (client.getConnectedHostList().size() > 0); i++) { Thread.sleep(500); } assertTrue(client.getConnectedHostList().isEmpty()); client.close(); Map<Thread, StackTraceElement[]> stMap = Thread.getAllStackTraces(); for (Entry<Thread, StackTraceElement[]> e : stMap.entrySet()) { StackTraceElement[] st = e.getValue(); Thread t = e.getKey(); if (t == Thread.currentThread()) { continue; } for (StackTraceElement ste : st) { if (ste.getClassName().toLowerCase().contains("voltdb.client")) { System.err.println(ste.getClassName().toLowerCase()); fail("Something failed to clean up."); } } } }
Source:
<code>public String resolve() { if (applicationContext == null) { log.error("ApplicationContext has not been set: Cannot determine service version"); return UNKNOWN_VERSION; } if (resolvedServiceVersion == null) { for (VersionResolver resolver : resolvers) { final String resolverName = resolver.getClass().getSimpleName(); log.trace("Attempting to resolve service version: {}", resolverName); try { String version = resolver.resolve(applicationContext.getApplicationName()); if (version != null) { resolvedServiceVersion = version; break; } } catch (Exception e) { log.error("Failed while resolving version: {}", resolverName, e); } } if (resolvedServiceVersion == null) { <START> return UNKNOWN_VERSION; <END> } } return resolvedServiceVersion; }</code><technical_language>is a reasonable expectation if resolvers find a result, is worth continuing check? (should cache UNKNOWN_VERSION result?)</technical_language>

Target:
public String resolve() { if (resolvedServiceVersion == null) { for (VersionResolver resolver : resolvers) { final String resolverName = resolver.getClass().getSimpleName(); log.trace("Attempting to resolve service version: {}", resolverName); try { String version = resolver.resolve(applicationContext.getApplicationName()); if (version != null) { resolvedServiceVersion = version; break; } } catch (Exception e) { log.error("Failed while resolving version: {}", resolverName, e); } } resolvedServiceVersion = UNKNOWN_VERSION; } return resolvedServiceVersion; }
Source:
<code>private void createImageForVmMetaData() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePool.getId(), storageDomainId, vmConfImageGroupId, MemoryUtils.METADATA_SIZE_IN_BYTES, <START> getVolumeTypeForDomain(), <END> VolumeFormat.RAW, vmConfVolumeId, "")); if (!retVal.getSucceeded()) { throw new EngineException(EngineError.VolumeCreationError, "Failed to create image for vm configuration!"); } Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_VM_TASK_KEY); Guid guid = enclosingCommand.createTask( taskId, retVal.getCreationInfo(), enclosingCommand.getActionType()); enclosingCommand.getTaskIdList().add(guid); }</code><technical_language>I agree Arik preallocated disk is option. storage side, block storage this disk 128MiB, this is extent size. file storage, sparse preallocated same, blocks, typically block (4KiB). Arik, do change import side if preallocated raw</technical_language>

Target:
private void createImageForVmMetaData() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePool.getId(), storageDomainId, vmConfImageGroupId, MemoryUtils.METADATA_SIZE_IN_BYTES, VolumeType.Preallocated, VolumeFormat.RAW, vmConfVolumeId, "")); if (!retVal.getSucceeded()) { throw new EngineException(EngineError.VolumeCreationError, "Failed to create image for vm configuration!"); } Guid taskId = enclosingCommand.persistAsyncTaskPlaceHolder(CREATE_IMAGE_FOR_VM_TASK_KEY); Guid guid = enclosingCommand.createTask( taskId, retVal.getCreationInfo(), enclosingCommand.getActionType()); enclosingCommand.getTaskIdList().add(guid); }
Source:
<code>void resolvingUniqueIdWithWrongParamsResolvesNothing(LogRecordListener listener) { UniqueId uniqueId = uniqueIdForMethod(HerTestClass.class, "test7(java.math.BigDecimal)"); EngineDiscoveryRequest request = request().selectors(selectUniqueId(uniqueId)).build(); resolver.resolveSelectors(request, engineDescriptor); assertTrue(engineDescriptor.getDescendants().isEmpty()); assertThat(listener.stream() .filter(logRecord -> logRecord.getLevel() == Level.WARNING) .filter(logRecord -> JavaElementsResolver.class.getName().equals(logRecord.getLoggerName())) <START> .map(LogRecord::getMessage) <END> .filter(isEqual("Unique ID '" + uniqueId + "' could only be partially resolved. " + "All resolved segments will be executed; however, the following segments " + "could not be resolved: [Segment [type = 'method', value = 'test7(java.math.BigDecimal)']]")) ).hasSize(1); }</code><technical_language>able remove filters org.junit.platform.commons.logging.LogRecordListener.stream(Class<?>, Level)</technical_language>

Target:
void resolvingUniqueIdWithWrongParamsResolvesNothing(LogRecordListener listener) { UniqueId uniqueId = uniqueIdForMethod(HerTestClass.class, "test7(java.math.BigDecimal)"); EngineDiscoveryRequest request = request().selectors(selectUniqueId(uniqueId)).build(); resolver.resolveSelectors(request, engineDescriptor); assertTrue(engineDescriptor.getDescendants().isEmpty()); assertThat(listener.stream(JavaElementsResolver.class, Level.WARNING).map(LogRecord::getMessage)) .contains("Unique ID '" + uniqueId + "' could only be partially resolved. " + "All resolved segments will be executed; however, the following segments " + "could not be resolved: [Segment [type = 'method', value = 'test7(java.math.BigDecimal)']]"); }
Source:
<code>private static String normalizeIfCommaSeparated(String value) { String integerPart; String decimalPart; int decimalIndex = value.indexOf("."); if (decimalIndex < 0) { integerPart = value; decimalPart = ""; } else { integerPart = value.substring(0, decimalIndex); decimalPart = value.substring(decimalIndex); } <START> String normalizedIntegerPart = integerPart.replaceAll("(?<=\\d),(?=\\d{3}(,|$))", ""); <END> return normalizedIntegerPart + decimalPart; }</code><technical_language>If a regex is used, a static constant, regexes tend slow. Simply removing commas input string simpler good enough</technical_language>

Target:
private static String normalizeIfCommaSeparated(String value) { if (!value.startsWith(",") && !value.startsWith("-,") && !value.endsWith(",") && !value.contains(",,")) { List<String> parts = ImmutableList.copyOf(DOT_SPLITTER.split(value)); if (parts.size() == 1 || (parts.size() == 2 && !parts.get(1).contains(","))) { return value.replace(",", ""); } } return value; }