auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setupAuthStrategies() { <START> if (config.getBoolean(ConfigProperties.KEYCLOAK_AUTHENTICATION) && <END> keycloakAdapterConfiguration.getAdapterConfig() != null) { providers.add(injector.getInstance(KeycloakAuth.class)); } if (config.getBoolean(ConfigProperties.OAUTH_AUTHENTICATION)) { providers.add(injector.getInstance(OAuth.class)); } if (config.getBoolean(ConfigProperties.BASIC_AUTHENTICATION)) { providers.add(injector.getInstance(BasicAuth.class)); } if (config.getBoolean(ConfigProperties.SSL_AUTHENTICATION)) { providers.add(injector.getInstance(SSLAuth.class)); } if (config.getBoolean(ConfigProperties.TRUSTED_AUTHENTICATION)) { providers.add(injector.getInstance(TrustedConsumerAuth.class)); providers.add(injector.getInstance(TrustedUserAuth.class)); } }</code><technical_language>Remember default reasonable (false) in cases avoid crashing unnecessarily</technical_language>

Target:
public void setupAuthStrategies() { if (config.getBoolean(ConfigProperties.KEYCLOAK_AUTHENTICATION)) { providers.add(injector.getInstance(KeycloakAuth.class)); } if (config.getBoolean(ConfigProperties.OAUTH_AUTHENTICATION)) { providers.add(injector.getInstance(OAuth.class)); } if (config.getBoolean(ConfigProperties.BASIC_AUTHENTICATION)) { providers.add(injector.getInstance(BasicAuth.class)); } if (config.getBoolean(ConfigProperties.SSL_AUTHENTICATION)) { providers.add(injector.getInstance(SSLAuth.class)); } if (config.getBoolean(ConfigProperties.TRUSTED_AUTHENTICATION)) { providers.add(injector.getInstance(TrustedConsumerAuth.class)); providers.add(injector.getInstance(TrustedUserAuth.class)); } }
Source:
<code>public void updateIdentifiersEmailSignInUpdatePhone() { mockHealthCodeAndAccountRetrieval(); when(accountDao.authenticate(STUDY, EMAIL_PASSWORD_SIGN_IN)).thenReturn(account); when(accountDao.getAccount(any())).thenReturn(account); IdentifierUpdate update = new IdentifierUpdate(EMAIL_PASSWORD_SIGN_IN, null, TestConstants.PHONE, null); StudyParticipant returned = participantService.updateIdentifiers(STUDY, CONTEXT, update); assertEquals(TestConstants.PHONE, account.getPhone()); assertEquals(Boolean.FALSE, account.getPhoneVerified()); verify(accountDao).authenticate(STUDY, EMAIL_PASSWORD_SIGN_IN); <START> verify(accountDao).updateAccount(eq(account), any()); <END> verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); assertEquals(PARTICIPANT.getId(), returned.getId()); }</code><technical_language>If update external ID, commit hook null. (Here in phone case.)</technical_language>

Target:
public void updateIdentifiersEmailSignInUpdatePhone() { mockHealthCodeAndAccountRetrieval(); when(accountDao.authenticate(STUDY, EMAIL_PASSWORD_SIGN_IN)).thenReturn(account); when(accountDao.getAccount(any())).thenReturn(account); IdentifierUpdate update = new IdentifierUpdate(EMAIL_PASSWORD_SIGN_IN, null, TestConstants.PHONE, null); StudyParticipant returned = participantService.updateIdentifiers(STUDY, CONTEXT, update); assertEquals(TestConstants.PHONE, account.getPhone()); assertEquals(Boolean.FALSE, account.getPhoneVerified()); verify(accountDao).authenticate(STUDY, EMAIL_PASSWORD_SIGN_IN); verify(accountDao).updateAccount(eq(account), eq(null)); verify(accountWorkflowService, never()).sendEmailVerificationToken(any(), any(), any()); assertEquals(PARTICIPANT.getId(), returned.getId()); }
Source:
<code>private boolean verifyLocalAvailableSpace(Set<Entity> entities) { val spaceRequired = downloadService.getSpaceRequired(entities); val spaceAvailable = getLocalAvailableSpace(); log.warn("space required: ({}) space available: ({})", FileUtils.byteCountToDisplaySize(spaceRequired), spaceRequired, <START> FileUtils.byteCountToDisplaySize(spaceAvailable), spaceAvailable); <END> if (spaceRequired > spaceAvailable) { terminal.printWarn("Insufficient space to download requested files: Require %s. %s Available", FileUtils.byteCountToDisplaySize(spaceRequired), FileUtils.byteCountToDisplaySize(spaceAvailable)); terminal.clearLine(); return false; } return true; }</code><technical_language>FormatUtils instead? dependency consistent</technical_language>

Target:
private boolean verifyLocalAvailableSpace(Set<Entity> entities) { val spaceRequired = downloadService.getSpaceRequired(entities); val spaceAvailable = getLocalAvailableSpace(); log.warn("space required: ({}) space available: ({})", FormatUtils.formatBytes(spaceRequired), spaceRequired, FormatUtils.formatBytes(spaceAvailable), spaceAvailable); if (spaceRequired > spaceAvailable) { terminal.printWarn("Insufficient space to download requested files: Require %s. %s Available", FormatUtils.formatBytes(spaceRequired), FormatUtils.formatBytes(spaceAvailable)); terminal.clearLine(); return false; } return true; }
Source:
<code>public void testBrokenStoreKeyConverter() throws Exception { InputAndExpected inputAndExpected = new InputAndExpected(pairList.get(0), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); StoreCopier.Message output = transformer.transform(inputAndExpected.getInput()); verifyOutput(output, inputAndExpected.getExpected()); factory.setException(new BlobIdTransformerTestException()); inputAndExpected = new InputAndExpected(pairList.get(1), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); try { transformer.transform(inputAndExpected.getInput()); fail("Did not throw StoreKeyConverterNotConvertedException"); <START> } catch (StoreKeyConverter.StoreKeyConverterNotConvertedException e) { <END> } factory.setException(null); inputAndExpected = new InputAndExpected(pairList.get(2), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); output = transformer.transform(inputAndExpected.getInput()); verifyOutput(output, inputAndExpected.getExpected()); }</code><technical_language>im need a new exception type for this - IllegalStateException I think</technical_language>

Target:
public void testBrokenStoreKeyConverter() throws Exception { InputAndExpected inputAndExpected = new InputAndExpected(pairList.get(0), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); StoreCopier.Message output = transformer.transform(inputAndExpected.getInput()); verifyOutput(output, inputAndExpected.getExpected()); factory.setException(new BlobIdTransformerTestException()); inputAndExpected = new InputAndExpected(pairList.get(1), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); try { transformer.transform(inputAndExpected.getInput()); fail("Did not throw IllegalStateException"); } catch (IllegalStateException e) { } factory.setException(null); inputAndExpected = new InputAndExpected(pairList.get(2), VALID_MESSAGE_FORMAT_INPUT_STREAM_IMPLS[0]); output = transformer.transform(inputAndExpected.getInput()); verifyOutput(output, inputAndExpected.getExpected()); }
Source:
<code><START> public ProfitBricksImageExtension(ProfitBricksApi client, <END> @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, @Memoized Supplier<Set<? extends Location>> locations, @Named(POLL_PREDICATE_SNAPSHOT) Predicate<String> snapshotAvailablePredicate, Trackables trackables) { this.client = checkNotNull(client, "client"); this.userExecutor = checkNotNull(userExecutor, "userExecutor"); this.locations = checkNotNull(locations, "locations"); this.snapshotAvailablePredicate = checkNotNull(snapshotAvailablePredicate, "snapshotAvailablePredicate"); this.trackables = checkNotNull(trackables); }</code><technical_language>Remove public modifier, null checks, injector enforces that</technical_language>

Target:
ProfitBricksImageExtension(ProfitBricksApi client, @Named(Constants.PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, @Memoized Supplier<Set<? extends Location>> locations, @Named(POLL_PREDICATE_SNAPSHOT) Predicate<String> snapshotAvailablePredicate, Trackables trackables) { this.client = client; this.userExecutor = userExecutor; this.locations = locations; this.snapshotAvailablePredicate = snapshotAvailablePredicate; this.trackables = trackables; }
Source:
<code>private void updateTree() { long startTimeMs = SystemClock.elapsedRealtime(); ShadowDOM.Update domUpdate = createShadowDOMUpdate(); boolean isEmpty = domUpdate.isEmpty(); if (isEmpty) { domUpdate.abandon(); } else { applyDOMUpdate(domUpdate); } long endTimeMs = SystemClock.elapsedRealtime(); <START> long deltaMs = endTimeMs - startTimeMs; <END> LogUtil.e(String.format( "DOM.updateTree() completed in %s ms%s", Long.toString(deltaMs), isEmpty ? " (no changes)" : "")); }</code><technical_language>nit: simplify this pattern with: java long deltaMs = SystemClock.elapseRealtime() - startTimeMs; rare care end time</technical_language>

Target:
private void updateTree() { long startTimeMs = SystemClock.elapsedRealtime(); ShadowDOM.Update domUpdate = createShadowDOMUpdate(); boolean isEmpty = domUpdate.isEmpty(); if (isEmpty) { domUpdate.abandon(); } else { applyDOMUpdate(domUpdate); } long deltaMs = SystemClock.elapsedRealtime() - startTimeMs; LogUtil.d( "DOM.updateTree() completed in %s ms%s", Long.toString(deltaMs), isEmpty ? " (no changes)" : ""); }
Source:
<code>public Resource getPublishedResource(String path) throws ZebedeeException, IOException { try { return publishedContentReader.getResource(path); } catch (BadRequestException e) { <START> return publishedContentReader.getResource(path + "/index.html"); <END> } }</code><technical_language>want apply this uris starting /visualisation? I index.html is a convention this code follows. I wary of applying this everything</technical_language>

Target:
public Resource getPublishedResource(String path) throws ZebedeeException, IOException { try { return publishedContentReader.getResource(path); } catch (BadRequestException e) { if(path.startsWith("/visualisations/")) { return publishedContentReader.getResource(path + "/index.html"); } throw e; } }
Source:
<code>void registerSelectorActiveConnections(final AtomicLong numActiveConnections) { <START> Gauge<Long> selectorActiveConnectionsCount = new Gauge<Long>() { <END> @Override public Long getValue() { return numActiveConnections.get(); } }; registry.register(MetricRegistry.name(Selector.class, selectorIndex++ + "SelectorActiveConnectionsCount"), selectorActiveConnectionsCount); }</code><technical_language>I original idea of grouping this is - is insight in selector level granularity for this metric. follow you</technical_language>

Target:
void registerSelectorActiveConnections(final AtomicLong numActiveConnections) { selectorActiveConnectionsList.add(numActiveConnections); }
Source:
<code>SSLSocketFactory sslSocketFactory(Provider<Credentials> credentials) { <START> List<Object> creds = ListCredentials.asList(credentials.get()); <END> String keystorePath = creds.get(0).toString(); String keystorePassword = creds.get(1).toString(); try { BufferedInputStream keystoreStream = new BufferedInputStream(new FileInputStream(keystorePath)); keystoreStream.mark(1024); KeyStore keystore = KeyStore.getInstance("JKS"); try { keystore.load(keystoreStream, keystorePassword.toCharArray()); } catch (IOException e) { if (!"Invalid keystore format".equals(e.getMessage())) throw e; keystoreStream.reset(); keystore = KeyStore.getInstance("PKCS12"); keystore.load(keystoreStream, keystorePassword.toCharArray()); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, keystorePassword.toCharArray()); KeyManager[] km = kmf.getKeyManagers(); SSLContext context = SSLContext.getInstance("TLSv1.1"); context.init(km, null, null); return context.getSocketFactory(); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Keystore file not found"); } catch (IOException e) { throw new IllegalArgumentException("Keystore could not be read"); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("Keystore could not be initialised"); } }</code><technical_language>ps create sslcontext a PEM. If need certs, this easier way. <LINK_0> <LINK_1></technical_language>

Target:
SSLSocketFactory sslSocketFactory(Provider<Credentials> credentials) { List<Object> creds = ListCredentials.asList(credentials.get()); String cert = creds.get(0).toString(); String key = creds.get(1).toString(); try { Certificate certObj = Pems.readCertificate(cert); PrivateKey keyObj = Pems.readPrivateKey(key); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(null, null); keyStore.setKeyEntry("dummy alias", keyObj, null, new Certificate[] { certObj }); kmf.init(keyStore, null); SSLContext context = SSLContext.getInstance("TLSv1.1"); context.init(kmf.getKeyManagers(), null, null); return context.getSocketFactory(); } catch (IOException e) { throw new IllegalArgumentException("Key or certificate could not be read"); } catch (GeneralSecurityException e) { throw new IllegalArgumentException("Key or certificate could not be initialised"); } }
Source:
<code>boolean testRow(final int i, final long startTime) throws IOException { try { RegionInfo regionInfo = connection.getRegionLocator(table.getName()) .getRegionLocation(getSplitKey(i), false).getRegion(); <START> if (LOG.isDebugEnabled()) { <END> LOG.debug("deleting region from meta: " + regionInfo); } Delete delete = MetaTableAccessor .makeDeleteFromRegionInfo(regionInfo, HConstants.LATEST_TIMESTAMP); try (Table t = MetaTableAccessor.getMetaHTable(connection)) { t.delete(delete); } } catch (IOException ie) { LOG.error("cannot find region with start key: " + i); } return true; }</code><technical_language>need of test for isdebug if parameterized logging</technical_language>

Target:
boolean testRow(final int i, final long startTime) throws IOException { try { RegionInfo regionInfo = connection.getRegionLocator(table.getName()) .getRegionLocation(getSplitKey(i), false).getRegion(); LOG.debug("deleting region from meta: " + regionInfo); Delete delete = MetaTableAccessor .makeDeleteFromRegionInfo(regionInfo, HConstants.LATEST_TIMESTAMP); try (Table t = MetaTableAccessor.getMetaHTable(connection)) { t.delete(delete); } } catch (IOException ie) { LOG.error("cannot find region with start key: " + i); } return true; }
Source:
<code>private void handleTagNamesMessage(final TagNamesMessage message) { if (message.isFailure()) { LOGGER.warn( <START> "Failed to get tag names for metric " + message.getMetricName(), <END> message.getThrowable()); getSelf().tell(FETCH_METRIC, ActorRef.noSender()); } else { _periodsInFlight = Lists.newArrayList(RollupPeriod.values()); final String metricName = message.getMetricName(); for (final RollupPeriod period : RollupPeriod.values()) { PatternsCS.pipe( fetchLastDataPoint(metricName + period.getSuffix(), period) .handle((response, failure) -> buildLastDataPointResponse(metricName, period, message.getTagNames(), response, failure) ), getContext().dispatcher()) .to(getSelf()); } } }</code><technical_language>structured logging possible: LOGGER.warn() .setMessage("Failed get tag names for metric") .addData("metricName", message.getMetricName()) .setThrowable(message.getThrowable()) .log();</technical_language>

Target:
private void handleTagNamesMessage(final TagNamesMessage message) { _metrics.recordCounter("rollup/tag_names_message/received", 1); if (message.isFailure()) { LOGGER.warn() .setMessage("Failed to get tag names for metric.") .addData("metricName", message.getMetricName()) .setThrowable(message.getFailure().get()) .log(); getSelf().tell(FETCH_METRIC, ActorRef.noSender()); } else { _periodsInFlight = Lists.newArrayList(RollupPeriod.values()); final String metricName = message.getMetricName(); final long startTime = System.nanoTime(); for (final RollupPeriod period : RollupPeriod.values()) { PatternsCS.pipe( fetchLastDataPoint(metricName + period.getSuffix(), period) .handle((response, failure) -> { final String baseMetricName = "rollup/last_data_point_" + period.name().toLowerCase(); _metrics.recordCounter(baseMetricName + "/success", failure == null ? 1 : 0); _metrics.recordTimer( baseMetricName + "/request", System.nanoTime() - startTime, Optional.of(Units.NANOSECOND)); return buildLastDataPointResponse(metricName, period, message.getTagNames(), response, failure); }), getContext().dispatcher()) .to(getSelf()); } } }
Source:
<code>private void setFocusToFilterBox() { if (TestController.isTestMode()) { ui.triggerEvent(new UIComponentFocusEvent(UIComponentFocusEvent.EventType.FILTER_BOX)); } filterTextField.requestFocus(); filterTextField.setText(filterTextField.getText().trim()); filterTextField.positionCaret(filterTextField.getLength()); <START> addEventHandler(KeyEvent.KEY_PRESSED, event -> { <END> if (KeyboardShortcuts.downIssue.match(event) || KeyboardShortcuts.upIssue.match(event)) { listView.selectNthItem(1); } }); }</code><technical_language>This a bug (from a while seems). time jump filter box this handler bound</technical_language>

Target:
private void setFocusToFilterBox() { if (TestController.isTestMode()) { ui.triggerEvent(new UIComponentFocusEvent(UIComponentFocusEvent.EventType.FILTER_BOX)); } filterTextField.requestFocus(); filterTextField.setText(filterTextField.getText().trim()); filterTextField.positionCaret(filterTextField.getLength()); }
Source:
<code>public void addContents(@NonNull Container result) { result.add( new Content("nodes/master/networkInterface.md") { @Override public void writeTo(OutputStream os) throws IOException { <START> os.write(getNetworkInterface(Jenkins.getInstance()).getBytes("utf-8")); <END> } } ); for (final Node node : Jenkins.getInstance().getNodes()) { result.add( new Content("nodes/slave/" + node.getNodeName() + "/networkInterface.md") { @Override public void writeTo(OutputStream os) throws IOException { os.write(getNetworkInterface(node).getBytes("utf-8")); } } ); } }</code><technical_language>"utf-8" is implementation specific. mandated "UTF-8" instead</technical_language>

Target:
public void addContents(@NonNull Container result) { result.add( new Content("nodes/master/networkInterface.md") { @Override public void writeTo(OutputStream os) throws IOException { os.write(getNetworkInterface(Jenkins.getInstance()).getBytes("UTF-8")); } } ); for (final Node node : Jenkins.getInstance().getNodes()) { result.add( new Content("nodes/slave/" + node.getNodeName() + "/networkInterface.md") { @Override public void writeTo(OutputStream os) throws IOException { os.write(getNetworkInterface(node).getBytes("UTF-8")); } } ); } }
Source:
<code>public TableViewerBuilder(TableViewer viewer, Composite tableContainer) { this.viewer = viewer; viewer.setComparer(new EqualityComparer()); tableLayout = new AutoResizeTableLayout(viewer.getTable()); System.out.println("TableViewerBuilder: Passed layout: " + tableContainer.getLayout()); if(tableContainer.getLayout() == null) { tableContainer.setLayout(new GridLayout()); GridData gd = new GridData(GridData.FILL_BOTH); viewer.getTable().setLayoutData(gd); <START> } else if(tableContainer.getLayout() instanceof FillLayout) { <END> } else if(tableContainer.getLayout() instanceof GridLayout) { GridData gd = new GridData(GridData.FILL_BOTH); viewer.getTable().setLayoutData(gd); } viewer.getTable().setLayout(tableLayout); }</code><technical_language>unnecessary branch</technical_language>

Target:
public TableViewerBuilder(TableViewer viewer, Composite tableContainer) { this.viewer = viewer; viewer.setComparer(new EqualityComparer()); this.tableLayout = new TableColumnLayout(); tableContainer.setLayout(tableLayout); }
Source:
<code>private Map<String, Object> getAlwaysMatch() throws IOException { CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8); try (Reader reader = charSource.openBufferedStream(); JsonInput input = json.newInput(reader)) { input.beginObject(); while (input.hasNext()) { String name = input.nextName(); if ("capabilities".equals(name)) { input.beginObject(); while (input.hasNext()) { name = input.nextName(); if ("alwaysMatch".equals(name)) { return input.read(MAP_TYPE); <START> } else { <END> input.skipValue(); } } input.endObject(); } else { input.skipValue(); } } } return null; }</code><technical_language>this else redundant</technical_language>

Target:
private @Nullable Map<String, Object> getAlwaysMatch() throws IOException { CharSource charSource = backingStore.asByteSource().asCharSource(UTF_8); try (Reader reader = charSource.openBufferedStream(); JsonInput input = json.newInput(reader)) { input.beginObject(); while (input.hasNext()) { String name = input.nextName(); if (CAPABILITIES.equals(name)) { input.beginObject(); while (input.hasNext()) { name = input.nextName(); if (ALWAYS_MATCH.equals(name)) { return input.read(MAP_TYPE); } input.skipValue(); } input.endObject(); } else { input.skipValue(); } } } return null; }
Source:
<code>protected Duration getConfirmTimeout() { <START> if (this.confirmTimeout == null) { <END> return DEFAULT_CONFIRM_TIMEOUT; } return this.confirmTimeout; }</code><technical_language>a confirmTimeout initialized DEFAULT_CONFIRM_TIMEOUT default? I is a logic if (this.confirmTimeout != null) though, return null @Nullable this method instead? I a consistency current logic is this getConfirmTimeout() in inheritors</technical_language>

Target:
protected Duration getConfirmTimeout() { return this.confirmTimeout; }
Source:
<code>protected void initListeners() { super.initListeners(); <START> videoTitleRoot.setLongClickable(true); <END> videoTitleRoot.setOnLongClickListener(this); uploaderRootLayout.setOnClickListener(this); uploaderRootLayout.setOnLongClickListener(this); videoTitleRoot.setOnClickListener(this); thumbnailBackgroundButton.setOnClickListener(this); detailControlsBackground.setOnClickListener(this); detailControlsPopup.setOnClickListener(this); detailControlsAddToPlaylist.setOnClickListener(this); detailControlsDownload.setOnClickListener(this); detailControlsDownload.setOnLongClickListener(this); detailControlsBackground.setLongClickable(true); detailControlsPopup.setLongClickable(true); detailControlsBackground.setOnLongClickListener(this); detailControlsPopup.setOnLongClickListener(this); detailControlsBackground.setOnTouchListener(getOnControlsTouchListener()); detailControlsPopup.setOnTouchListener(getOnControlsTouchListener()); }</code><technical_language>I this line is needed, setOnLongClickListener view long clickable: <LINK_0></technical_language>

Target:
protected void initListeners() { super.initListeners(); videoTitleRoot.setOnLongClickListener(this); uploaderRootLayout.setOnClickListener(this); uploaderRootLayout.setOnLongClickListener(this); videoTitleRoot.setOnClickListener(this); thumbnailBackgroundButton.setOnClickListener(this); detailControlsBackground.setOnClickListener(this); detailControlsPopup.setOnClickListener(this); detailControlsAddToPlaylist.setOnClickListener(this); detailControlsDownload.setOnClickListener(this); detailControlsDownload.setOnLongClickListener(this); detailControlsBackground.setLongClickable(true); detailControlsPopup.setLongClickable(true); detailControlsBackground.setOnLongClickListener(this); detailControlsPopup.setOnLongClickListener(this); detailControlsBackground.setOnTouchListener(getOnControlsTouchListener()); detailControlsPopup.setOnTouchListener(getOnControlsTouchListener()); }
Source:
<code>public void should_compile_as_containsAnyElementsOf_declares_bounded_wildcard_parameter() { Map<String, String> map = newHashMap("some_key", "some_value"); Iterable<Map<String, String>> iterable = list(map); <START> assertThat(iterable).extracting("some_key").containsAnyElementsOf(list("some_value", "some_other_value")); <END> }</code><technical_language>I agree, this test containsAnyElementsOf accept more a List<Object></technical_language>

Target:
public void should_compile_as_containsAnyElementsOf_declares_bounded_wildcard_parameter() { Iterable<String> iterable = list("some_value", "some_different_value"); assertThat(iterable).containsAnyElementsOf(list("some_value", "some_other_value")); }
Source:
<code>private static boolean executeJar(String jarPath, String argsAndOptions) { <START> String command = String.format("java -jar %1$s %2$s", jarPath, argsAndOptions).trim(); <END> log("Starting JAR with command: " + command); Process process; try { process = Runtime.getRuntime().exec(command); } catch (IOException e) { log("Failed to run command. Error: " + e.toString()); return false; } return process.isAlive(); }</code><technical_language>need positional arguments here. for other format strings</technical_language>

Target:
private static boolean executeJar(String jarPath, String argsAndOptions) { String command = String.format("java -jar %s %s", jarPath, argsAndOptions).trim(); log("Starting JAR with command: " + command); Process process; try { process = Runtime.getRuntime().exec(command); } catch (IOException e) { log("Failed to run command. Error: " + e.toString()); return false; } return process.isAlive(); }
Source:
<code>public static TaskShowDto map(Task task) { TaskShowDto dto = new TaskShowDto(task); if (task.getEndpoint() != null) { dto.setEndpoint(EndpointMapper.map(task.getEndpoint())); } <START> for (Template template: task.getTemplates()){ <END> dto.addTemplate(new TemplateShowDto(template)); } return dto; }</code><technical_language>if task.getTemplates() == null ? java8 java if(task.getTemplates()!=null){ dto.setTemplates(task.getTemplates().stream().map(TemplateShowDto::new).collect(Collectors.toList())); }</technical_language>

Target:
public static TaskShowDto map(Task task) { TaskShowDto dto = new TaskShowDto(task); if (task.getEndpoint() != null) { dto.setEndpoint(EndpointMapper.map(task.getEndpoint())); } if (task.getTemplates() != null){ dto.setTemplates(task .getTemplates() .stream() .map(TemplateShowDto::new) .collect(Collectors.toList())); } return dto; }
Source:
<code>private void printStageTree(StageStats stage, String indent, AtomicInteger stageNumberCounter) { long now = System.nanoTime(); String id = String.valueOf(stageNumberCounter.getAndIncrement()); String name = indent + id; name += Strings.repeat(".", max(0, 10 - name.length())); String bytesPerSecond; String rowsPerSecond; if (stage.isDone()) { bytesPerSecond = formatDataRate(new DataSize(0, BYTE), new Duration(0, SECONDS), false); rowsPerSecond = formatCountRate(0, new Duration(0, SECONDS), false); } else { <START> PreviousStageStatus previousStage = mappingPreviousStageStatuses.containsKey(id) ? mappingPreviousStageStatuses.get(id) : new PreviousStageStatus(start, 0, 0); <END> Duration elapsedTime = succinctNanos(now - previousStage.getNanoTime()); bytesPerSecond = formatDataRate(bytes(stage.getProcessedBytes() - previousStage.getProcessedBytes()), elapsedTime, false); rowsPerSecond = formatCountRate(stage.getProcessedRows() - previousStage.getProcessedRows(), elapsedTime, false); mappingPreviousStageStatuses.put(id, new PreviousStageStatus(now, stage.getProcessedBytes(), stage.getProcessedRows())); } String stageSummary = String.format("%10s%1s %5s %6s %5s %7s %6s %5s %5s", name, stageStateCharacter(stage.getState()), formatCount(stage.getProcessedRows()), rowsPerSecond, formatDataSize(bytes(stage.getProcessedBytes()), false), bytesPerSecond, stage.getQueuedSplits(), stage.getRunningSplits(), stage.getCompletedSplits()); reprintLine(stageSummary); for (StageStats subStage : stage.getSubStages()) { printStageTree(subStage, indent + " ", stageNumberCounter); } }</code><technical_language>this if/else</technical_language>

Target:
private void printStageTree(StageStats stage, String indent, AtomicInteger stageNumberCounter) { long now = System.nanoTime(); String id = String.valueOf(stageNumberCounter.getAndIncrement()); String name = indent + id; name += Strings.repeat(".", max(0, 10 - name.length())); String bytesPerSecond; String rowsPerSecond; if (stage.isDone()) { bytesPerSecond = formatDataRate(new DataSize(0, BYTE), new Duration(0, SECONDS), false); rowsPerSecond = formatCountRate(0, new Duration(0, SECONDS), false); } else { progressStatsHistory.addStageProgressStats(id, new ProgressStats(now, stage.getProcessedBytes(), stage.getProcessedRows())); bytesPerSecond = progressStatsHistory.formatStageInstantDataRate(id); rowsPerSecond = progressStatsHistory.formatStageInstantRowCountRate(id); } String stageSummary = String.format("%10s%1s %5s %6s %5s %7s %6s %5s %5s", name, stageStateCharacter(stage.getState()), formatCount(stage.getProcessedRows()), rowsPerSecond, formatDataSize(bytes(stage.getProcessedBytes()), false), bytesPerSecond, stage.getQueuedSplits(), stage.getRunningSplits(), stage.getCompletedSplits()); reprintLine(stageSummary); for (StageStats subStage : stage.getSubStages()) { printStageTree(subStage, indent + " ", stageNumberCounter); } }
Source:
<code><START> public void setTaskVariables(Map<String, Object> taskVariables) { <END> this.taskVariables = taskVariables; }</code><technical_language>This method is in scope of this class, need a public setter for it. private field directly</technical_language>

Target:
private void setTaskVariables(Map<String, Object> taskVariables) { this.taskVariables = taskVariables; }
Source:
<code>public void process(Exchange exchange) throws Exception { HttpClient httpClient = this.component.getHttpClient(); GetMethod getMethod = new GetMethod(workdayUri); this.autheticationClient.configure(httpClient, getMethod); try { int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { throw new IllegalStateException("Got the invalid http status value '" + getMethod.getStatusLine() + "' as the result of the RAAS '" + workdayUri + "'"); } String report = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, getMethod.getResponseBodyAsStream()); <START> if ("".equals(report)) { <END> throw new IllegalStateException("Got the unexpected value '" + report + "' as the result of the report '" + workdayUri + "'"); } exchange.getIn().setBody(report); exchange.getIn().setHeader(WORKDAY_RAAS_HEADER , workdayUri); } finally { getMethod.releaseConnection(); } }</code><technical_language>I more efficient report.isEmpty()</technical_language>

Target:
public void process(Exchange exchange) throws Exception { PoolingHttpClientConnectionManager httpClientConnectionManager = endpoint .getWorkdayConfiguration().getHttpConnectionManager(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setConnectionManager(httpClientConnectionManager).build(); HttpGet httpGet = new HttpGet(this.workdayUri); this.autheticationClient.configure(httpClient, httpGet); CloseableHttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IllegalStateException("Got the invalid http status value '" + httpResponse.getStatusLine() + "' as the result of the RAAS '" + workdayUri + "'"); } String report = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, httpResponse.getEntity().getContent()); if (report.isEmpty()) { throw new IllegalStateException("Got the unexpected value '" + report + "' as the result of the report '" + workdayUri + "'"); } exchange.getIn().setBody(report); exchange.getIn().setHeader(WORKDAY_RAAS_HEADER , workdayUri); }
Source:
<code>public static void main(final String[] args) throws IOException { if (args.length < 4) { System.out.println("Please enter the command-line parameters: "); <START> System.out.println("submit-jar $jar_path$ $driver_address$ $driver_port"); <END> return; } final String type = args[0]; if (type.compareToIgnoreCase("submit-jar") == 0) { final String jarPath = args[1]; final File file = new File(jarPath); if (!file.exists()) { System.out.println("File " + jarPath + " does not exist"); return; } final String address = args[2]; final int port = Integer.valueOf(args[3]); try (final MISTExecutionEnvironment ee = new MISTDefaultExecutionEnvironmentImpl(address, port)) { final JarUploadResult result = ee.submitJar(Arrays.asList(jarPath)); if (result.getIsSuccess()) { System.out.println("App identifier: " + result.getIdentifier()); return; } else { System.out.println("Submission failed: " + result.getMsg()); } } catch (final Exception e) { e.printStackTrace(); } } else { System.out.println("Not supported operation"); return; } }</code><technical_language>is removed</technical_language>

Target:
public static void main(final String[] args) throws IOException { if (args.length < 4) { System.out.println("Please enter the command-line parameters: "); System.out.println("submit-jar $jar_path$ $driver_address$ $driver_port$"); return; } final String type = args[0]; if (type.compareToIgnoreCase("submit-jar") == 0) { final String jarPath = args[1]; final File file = new File(jarPath); if (!file.exists()) { System.out.println("File " + jarPath + " does not exist"); return; } final String address = args[2]; final int port = Integer.valueOf(args[3]); try (final MISTExecutionEnvironment ee = new MISTDefaultExecutionEnvironmentImpl(address, port)) { final JarUploadResult result = ee.submitJar(Arrays.asList(jarPath)); if (result.getIsSuccess()) { System.out.println("App identifier: " + result.getIdentifier()); return; } else { System.out.println("Submission failed: " + result.getMsg()); } } catch (final Exception e) { e.printStackTrace(); } } else { System.out.println("Not supported operation"); return; } }
Source:
<code>public RequestItemRest fromModel(RequestItem requestItem) { RequestItemRest requestItemRest = new RequestItemRest(); requestItemRest.setAccept_request(requestItem.isAccept_request()); requestItemRest.setAllfiles(requestItem.isAllfiles()); requestItemRest.setBitstream(bitstreamConverter.fromModel(requestItem.getBitstream())); requestItemRest.setDecision_date(requestItem.getDecision_date()); requestItemRest.setExpires(requestItem.getExpires()); requestItemRest.setId(requestItem.getID()); requestItemRest.setItem(itemConverter.fromModel(requestItem.getItem())); <START> requestItemRest.setReq_email(requestItem.getReqEmail()); <END> requestItemRest.setReq_message(requestItem.getReqMessage()); requestItemRest.setReq_name(requestItem.getReqName()); requestItemRest.setRequest_date(requestItem.getRequest_date()); requestItemRest.setToken(requestItem.getToken()); return requestItemRest; }</code><technical_language>personally I prefer camel case approach is widely in rest of code. Anyway, is current "JAVA" request item class mix approach</technical_language>

Target:
public RequestItemRest fromModel(RequestItem requestItem) { RequestItemRest requestItemRest = new RequestItemRest(); requestItemRest.setAccept_request(requestItem.isAccept_request()); requestItemRest.setAllfiles(requestItem.isAllfiles()); requestItemRest.setBitstream_id(requestItem.getBitstream().getID().toString()); requestItemRest.setDecision_date(requestItem.getDecision_date()); requestItemRest.setExpires(requestItem.getExpires()); requestItemRest.setId(requestItem.getID()); requestItemRest.setItem_id(requestItem.getItem().getID().toString()); requestItemRest.setRequest_email(requestItem.getReqEmail()); requestItemRest.setRequest_message(requestItem.getReqMessage()); requestItemRest.setRequest_name(requestItem.getReqName()); requestItemRest.setRequest_date(requestItem.getRequest_date()); requestItemRest.setToken(requestItem.getToken()); return requestItemRest; }
Source:
<code>public void onFavoriteButtonClicked(View favorite) { displayKissBar(false); Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve) .get(Integer.parseInt((String) favorite.getTag())); final Result result = Result.fromPojo(MainActivity.this, pojo); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { result.fastLaunch(MainActivity.this); } <START> }, KissApplication.TOUCH_DELAY_FAVORITE); <END> }</code><technical_language>I this fix, if 0, I call fastLaunch() deferring this another handler. faster (no threading) code easier read</technical_language>

Target:
public void onFavoriteButtonClicked(View favorite) { Pojo pojo = KissApplication.getDataHandler(MainActivity.this).getFavorites(tryToRetrieve) .get(Integer.parseInt((String) favorite.getTag())); final Result result = Result.fromPojo(MainActivity.this, pojo); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { result.fastLaunch(MainActivity.this); } }, KissApplication.TOUCH_DELAY); }
Source:
<code>public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result = null; if (VIEW_STATS.equals(name)) { Map<String, String> map = new HashMap<>(); for (Entry<String, Long> stat : InMemoryStats.getStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { map.put(stat.getKey(), stat.getValue().toString()); } result = new ApiResponseSet(name, map); } else if (VIEW_ALL_SITES_STATS.equals(name)) { result = new ApiResponseList(name); for (Entry<String, Map<String, Long>> stats : InMemoryStats.getAllSiteStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { ((ApiResponseList)result).addItem(new SiteStatsApiResponse(stats.getKey(), stats.getValue())); } } else if (VIEW_SITE_STATS.equals(name)) { <START> String site = this.getParam(params, PARAM_SITE, null); <END> URI siteURI; try { siteURI = new URI(site, true); site = SessionStructure.getHostName(siteURI); } catch (Exception e) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } String scheme = siteURI.getScheme(); if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } result = new SiteStatsApiResponse(site, InMemoryStats.getSiteStats(site, this.getParam(params, PARAM_KEY_PREFIX, ""))); } else { throw new ApiException(ApiException.Type.BAD_VIEW); } return result; }</code><technical_language>This params.getString(PARAM_SITE), a mandatory parameter</technical_language>

Target:
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException { ApiResponse result = null; InMemoryStats memStats = extension.getInMemoryStats(); if (memStats == null) { throw new ApiException(ApiException.Type.DOES_NOT_EXIST); } if (VIEW_STATS.equals(name)) { Map<String, String> map = new HashMap<>(); for (Entry<String, Long> stat : memStats.getStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { map.put(stat.getKey(), stat.getValue().toString()); } result = new ApiResponseSet(name, map); } else if (VIEW_ALL_SITES_STATS.equals(name)) { result = new ApiResponseList(name); for (Entry<String, Map<String, Long>> stats : memStats.getAllSiteStats(this.getParam(params, PARAM_KEY_PREFIX, "")).entrySet()) { ((ApiResponseList)result).addItem(new SiteStatsApiResponse(stats.getKey(), stats.getValue())); } } else if (VIEW_SITE_STATS.equals(name)) { String site = params.getString(PARAM_SITE); URI siteURI; try { siteURI = new URI(site, true); site = SessionStructure.getHostName(siteURI); } catch (Exception e) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } String scheme = siteURI.getScheme(); if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) { throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_SITE); } result = new SiteStatsApiResponse(site, memStats.getSiteStats(site, this.getParam(params, PARAM_KEY_PREFIX, ""))); } else { throw new ApiException(ApiException.Type.BAD_VIEW); } return result; }
Source:
<code>public Response waitForResponse(long timeoutInMs) throws InterruptedException { Response r; synchronized (lock) { if (currentResponse != null) r = currentResponse; else { lock.wait(timeoutInMs); r = currentResponse; } currentResponse = null; } <START> System.out.println("waitForResponse " + i + " " + r); <END> return r; }</code><technical_language>point_up:</technical_language>

Target:
public Response waitForResponse(long timeoutInMs) throws InterruptedException { Response r; synchronized (lock) { if (currentResponse != null) r = currentResponse; else { lock.wait(timeoutInMs); r = currentResponse; } currentResponse = null; } return r; }
Source:
<code>protected void testAddStereotypedElementMergeRToL(Resource left, Resource right) throws IOException { final Comparison comparison = compare(left, right); EList<Diff> differences = comparison.getDifferences(); final StereotypedElementChange stereotypedElementChange = getStereotypedElementChange(differences, DifferenceKind.ADD, 2); assertAddedBaseElementDiff(differences, "model.Class0", stereotypedElementChange); mergeRightToLeft(stereotypedElementChange); for (Diff diff : differences) { assertSame(DifferenceState.MERGED, diff.getState()); } <START> <END> assertEqualsB4Right(right); }</code><technical_language>For Right Left test, need test left models (those modified).Please verify other tests present problem</technical_language>

Target:
protected void testAddStereotypedElementMergeRToL(Resource left, Resource right) throws IOException { final Comparison comparison = compare(left, right); EList<Diff> differences = comparison.getDifferences(); final StereotypedElementChange stereotypedElementChange = getStereotypedElementChange(differences, DifferenceKind.ADD, 2); assertAddedBaseElementDiff(differences, "model.Class0", stereotypedElementChange); mergeRightToLeft(stereotypedElementChange); for (Diff diff : differences) { assertSame(DifferenceState.MERGED, diff.getState()); } assertEqualsM2(right); assertEqualsM2(left); }
Source:
<code>public Response perform(Context context) throws Exception { <START> kafkaConfig = kafkaConfigProvider.getProperties(); <END> int timeout = Math.toIntExact(context.getTimeout()); kafkaConfig.put("request.timeout.ms", timeout); try (AdminClient client = Utils.runWithNullContextClassLoader(() -> AdminClient.create(kafkaConfig))) { ListTopicsResult listTopicsResult = client.listTopics(); listTopicsResult.names().get(); return new Response(Status.Success); } catch (Exception e) { return new Response(e); } }</code><technical_language>Okay, sense, encounter for timeout responses then</technical_language>

Target:
public Response perform(Context context) throws Exception { Properties kafkaConfig = kafkaConfigProvider.getProperties(); int timeout = Math.toIntExact(context.getTimeout()); kafkaConfig.put("request.timeout.ms", timeout); try (AdminClient client = Utils.runWithNullContextClassLoader(() -> AdminClient.create(kafkaConfig))) { ListTopicsResult listTopicsResult = client.listTopics(); listTopicsResult.names().get(); return new Response(Status.Success); } catch (Exception e) { return new Response(e); } }
Source:
<code>private void formatInternal(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { char[] chars = pattern.toCharArray(); if (chars.length == 0) { return; } <START> CharBuffer formatBuffer = CharBuffer.wrap(chars); <END> while (formatBuffer.remaining() > 0) { boolean outputCurrentChar = true; char currentChar = formatBuffer.get(formatBuffer.position()); if (currentChar == '%') { outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfo); } if (outputCurrentChar) { outputBuilder.append(formatBuffer.get(formatBuffer.position())); } formatBuffer.position(formatBuffer.position() + 1); } }</code><technical_language>wrap(CharSequence), need for explicit char[]</technical_language>

Target:
private void formatInternal(String pattern, ZoneInfo.WallTime wallTime, ZoneInfo zoneInfo) { if (pattern.length() == 0) { return; } CharBuffer formatBuffer = CharBuffer.wrap(pattern); while (formatBuffer.remaining() > 0) { boolean outputCurrentChar = true; char currentChar = formatBuffer.get(formatBuffer.position()); if (currentChar == '%') { outputCurrentChar = handleToken(formatBuffer, wallTime, zoneInfo); } if (outputCurrentChar) { outputBuilder.append(formatBuffer.get(formatBuffer.position())); } formatBuffer.position(formatBuffer.position() + 1); } }
Source:
<code>public void testInterleavingNoPause() throws InterruptedException { ExecutorService executorService = PTExecutors.newFixedThreadPool(3); accumulator = new LeaderElectionDurationAccumulator(mockConsumer, 300); <START> executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_2, 300, 1)); <END> executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_2, LEADER_3, 300, 17)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_3, 300, 76)); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); verify(mockConsumer).accept(1L); verify(mockConsumer).accept(17L); verify(mockConsumer).accept(76L); verifyNoMoreInteractions(mockConsumer); }</code><technical_language>I technically (assuming election generates thing) 1L call on, is clearer in terms of readability non-overlapping ranges</technical_language>

Target:
public void testInterleavingNoPause() throws InterruptedException { ExecutorService executorService = PTExecutors.newFixedThreadPool(3); accumulator = new LeaderElectionDurationAccumulator(mockConsumer, 300); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_2, 300, 1)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_2, LEADER_3, 300, 1017)); executorService.submit(() -> leaderElectionResultsWithDurationInRandomOrder(LEADER_1, LEADER_3, 300, 2076)); executorService.shutdown(); executorService.awaitTermination(1, TimeUnit.MINUTES); verify(mockConsumer).accept(1L); verify(mockConsumer).accept(1017L); verify(mockConsumer).accept(2076L); verifyNoMoreInteractions(mockConsumer); }
Source:
<code>private void initInterpreterSetting(InterpreterSetting interpreterSetting) { interpreterSetting.setConf(conf) .setInterpreterSettingManager(this) .setAngularObjectRegistryListener(angularObjectRegistryListener) .setRemoteInterpreterProcessListener(remoteInterpreterProcessListener) .setAppEventListener(appEventListener) .setDependencyResolver(dependencyResolver) .setLifecycleManager(lifecycleManager) .setRecoveryStorage(recoveryStorage) .setInterpreterEventServer(interpreterEventServer) .postProcessing(); if (conf.isClusterMode()) { try { String pluginName = interpreterSetting.getLauncherPlugin(); <START> PluginManager.get().loadInterpreterLauncher(pluginName, recoveryStorage); <END> } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } }</code><technical_language>init IntepreterLauncher instead of InterpreterSetting</technical_language>

Target:
private void initInterpreterSetting(InterpreterSetting interpreterSetting) { interpreterSetting.setConf(conf) .setInterpreterSettingManager(this) .setAngularObjectRegistryListener(angularObjectRegistryListener) .setRemoteInterpreterProcessListener(remoteInterpreterProcessListener) .setAppEventListener(appEventListener) .setDependencyResolver(dependencyResolver) .setLifecycleManager(lifecycleManager) .setRecoveryStorage(recoveryStorage) .setInterpreterEventServer(interpreterEventServer) .postProcessing(); }