auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static byte[] downloadBlob( GrpcRemoteDownloader downloader, URL url, Optional<Checksum> checksum) throws IOException, InterruptedException { <START> final List<URL> urls = ImmutableList.<URL>of(url); <END> com.google.common.base.Optional<Checksum> guavaChecksum = com.google.common.base.Optional.<Checksum>absent(); if (checksum.isPresent()) { guavaChecksum = com.google.common.base.Optional.<Checksum>of(checksum.get()); } final Map<URI, Map<String, String>> authHeaders = ImmutableMap.<URI, Map<String, String>>of(); final String canonicalId = ""; final ExtendedEventHandler eventHandler = mock(ExtendedEventHandler.class); final Map<String, String> clientEnv = ImmutableMap.<String, String>of(); Scratch scratch = new Scratch(); final Path destination = scratch.resolve("output file path"); downloader.download( urls, authHeaders, guavaChecksum, canonicalId, destination, eventHandler, clientEnv); try (InputStream in = destination.getInputStream()) { return ByteStreams.toByteArray(in); } }</code><technical_language>Modern java smart enough leave "<URL>" out of "ImmutableList.<URL>of(...)", rm it. for other occurrences compiler is fine it</technical_language>

Target:
private static byte[] downloadBlob( GrpcRemoteDownloader downloader, URL url, Optional<Checksum> checksum) throws IOException, InterruptedException { final List<URL> urls = ImmutableList.of(url); com.google.common.base.Optional<Checksum> guavaChecksum = com.google.common.base.Optional.<Checksum>absent(); if (checksum.isPresent()) { guavaChecksum = com.google.common.base.Optional.<Checksum>of(checksum.get()); } final Map<URI, Map<String, String>> authHeaders = ImmutableMap.of(); final String canonicalId = ""; final ExtendedEventHandler eventHandler = mock(ExtendedEventHandler.class); final Map<String, String> clientEnv = ImmutableMap.of(); Scratch scratch = new Scratch(); final Path destination = scratch.resolve("output file path"); downloader.download( urls, authHeaders, guavaChecksum, canonicalId, destination, eventHandler, clientEnv); try (InputStream in = destination.getInputStream()) { return ByteStreams.toByteArray(in); } }
Source:
<code>public void removeStandaloneMenuItems(Menu menu) { <START> removeItem(R.id.pocketpaint_nav_save_image); <END> removeItem(R.id.pocketpaint_nav_save_duplicate); removeItem(R.id.pocketpaint_nav_new_image); }</code><technical_language>calling removeItem(). call menu.removeItem(). idea is menu a member variable</technical_language>

Target:
public void removeStandaloneMenuItems(Menu menu) { menu.removeItem(R.id.pocketpaint_nav_save_image); menu.removeItem(R.id.pocketpaint_nav_save_duplicate); menu.removeItem(R.id.pocketpaint_nav_new_image); }
Source:
<code>public String toString() { return "LeastBytesUsedStorageLocationSelectorStrategy{" + <START> "ordering=" + ORDERING + <END> ", storageLocations=" + storageLocations + '}'; }</code><technical_language>I this a string representation in toString()</technical_language>

Target:
public String toString() { return "LeastBytesUsedStorageLocationSelectorStrategy{" + "storageLocations=" + storageLocations + '}'; }
Source:
<code>public void testTransform_nullParams() throws Exception { <START> <END> verifyZeroInteractions(layer); }</code><technical_language>forgot call transformer here..</technical_language>

Target:
public void testTransform_nullParams() throws Exception { transformer.transform(layer, null); verifyZeroInteractions(layer); }
Source:
<code>public static String generateMarkdownSnippet(String id, Set<FactoryImage> factoryImages, String style, URI baseUri) { String factoryURL = UriBuilder.fromUri(baseUri).replacePath("factory").queryParam("id", id).build().toString(); StringBuilder sb = new StringBuilder(); <START> Formatter formatter = new Formatter(sb); <END> switch (style) { case "Advanced": case "Advanced with Counter": formatter.format("[![alt](%1$s/api/factory/%2$s/image?imgId=%3$s)](%4$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), id, factoryImages.iterator().next().getName(), factoryURL); break; case "White": case "Horizontal,White": case "Vertical,White": formatter.format("[![alt](%1$s/factory/resources/factory-white.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), factoryURL); break; case "Dark": case "Horizontal,Dark": case "Vertical,Dark": formatter.format("[![alt](%1$s/factory/resources/factory-dark.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build(), factoryURL); break; default: throw new IllegalArgumentException("Invalid factory style."); } return sb.toString(); }</code><technical_language>in 40th line do call toString() explicitly, in this line explicitly. Choose way</technical_language>

Target:
public static String generateMarkdownSnippet(String id, Set<FactoryImage> factoryImages, String style, URI baseUri) { String factoryURL = UriBuilder.fromUri(baseUri).replacePath("factory").queryParam("id", id).build().toString(); Formatter formatter = new Formatter(); switch (style) { case "Advanced": case "Advanced with Counter": if (factoryImages.size() > 0) { formatter.format("[![alt](%1$s/api/factory/%2$s/image?imgId=%3$s)](%4$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), id, factoryImages.iterator().next().getName(), factoryURL); } else { throw new IllegalArgumentException("Factory with advanced style MUST have at leas one image."); } break; case "White": case "Horizontal,White": case "Vertical,White": formatter.format("[![alt](%1$s/factory/resources/factory-white.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), factoryURL); break; case "Dark": case "Horizontal,Dark": case "Vertical,Dark": formatter.format("[![alt](%1$s/factory/resources/factory-dark.png)](%2$s)", UriBuilder.fromUri(baseUri).replacePath("").build().toString(), factoryURL); break; default: throw new IllegalArgumentException("Invalid factory style."); } return formatter.toString(); }
Source:
<code>public DataTransactionResult set(DataHolder dataHolder, FlyingData manipulator, MergeFunction function) { <START> return null; <END> }</code><technical_language>This needs done</technical_language>

Target:
public DataTransactionResult set(DataHolder dataHolder, FlyingData manipulator, MergeFunction function) { if (this.supports(dataHolder)) { final FlyingData merged = checkNotNull(function, "MergeFunction cannot be null!").merge(checkNotNull(manipulator).copy(), from(dataHolder).orNull()); manipulator.set(Keys.IS_FLYING, merged.flying().get()); final ImmutableValue<Boolean> oldFlying = merged.flying().asImmutable(); final boolean value = merged.flying().get(); if (dataHolder instanceof EntityPlayer) { ((EntityPlayer) (dataHolder)).capabilities.isFlying = value; } else { ((Entity) (dataHolder)).isAirBorne = value; } return DataTransactionBuilder.successReplaceResult( ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_FLYING, oldFlying.get(), false), (ImmutableDataCachingUtil.getValue(ImmutableSpongeValue.class, Keys.IS_FLYING, value, false))); } return DataTransactionBuilder.failResult(manipulator.getValues()); }
Source:
<code>private void setupDynamicMdcFieldTypes(PropertyProvider propertyProvider) { int fieldNumber = 0; while (true) { <START> final String property = propertyProvider.getProperty(PropertyProvider.PROPERTY_DYNAMIC_MDC_FIELD_TYPES + fieldNumber); <END> if (null == property) { break; } final int index = property.indexOf('='); if (-1 != index) { String field = property.substring(0, index); String type = property.substring(index + 1); setDynamicMdcFieldType(field, type); } fieldNumber++; } }</code><technical_language>Nit: need for final</technical_language>

Target:
private void setupDynamicMdcFieldTypes(PropertyProvider propertyProvider) { int fieldNumber = 0; while (true) { String property = propertyProvider.getProperty(PropertyProvider.PROPERTY_DYNAMIC_MDC_FIELD_TYPES + fieldNumber); if (null == property) { break; } int index = property.indexOf('='); if (-1 != index) { String field = property.substring(0, index); String type = property.substring(index + 1); setDynamicMdcFieldType(field, type); } fieldNumber++; } }
Source:
<code>public static <E extends Enum<E>> String validateEnum(String reason, String detail, Class<E> clz,Set<String> externalValues, String name, boolean toUppercase) { <START> if (externalValues.contains(name)) { <END> return name; } try { return Enum.valueOf(clz, toUppercase ? name.toUpperCase() : name).name(); } catch (IllegalArgumentException e) { detail = detail + getPossibleValues(clz, OsTypeUtils.getAllValues()); throw new WebApplicationException(response(reason, MessageFormat.format(detail, name, clz.getSimpleName()))); } }</code><technical_language>externalValues in lowercase? "name" is in lowercase, i "toUppercase ? name.toUpperCase() : name" bellow for enum</technical_language>

Target:
public static <E extends Enum<E>> String validateEnum(String reason, String detail, Class<E> clz,Set<String> externalValues, String name, boolean toUppercase) { if (externalValues.contains(toUppercase ? name.toUpperCase() : name)) { return name; } try { return Enum.valueOf(clz, toUppercase ? name.toUpperCase() : name).name(); } catch (IllegalArgumentException e) { detail = detail + getPossibleValues(clz, OsTypeUtils.getAllValues()); throw new WebApplicationException(response(reason, MessageFormat.format(detail, name, clz.getSimpleName()))); } }
Source:
<code>DefaultSyncPoller(Duration pollInterval, Function<PollingContext<T>, PollResponse<T>> syncActivationOperation, Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation, BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation, Function<PollingContext<T>, Mono<U>> fetchResultOperation) { <START> Objects.requireNonNull(pollInterval, "'defaultPollInterval' cannot be null."); <END> if (pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.defaultPollInterval = pollInterval; Objects.requireNonNull(syncActivationOperation, "'syncActivationOperation' cannot be null."); this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null."); this.cancelOperation = Objects.requireNonNull(cancelOperation, "'cancelOperation' cannot be null."); this.fetchResultOperation = Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null."); this.activationResponse = syncActivationOperation.apply(this.pollingContext); this.pollingContext.setOnetimeActivationResponse(this.activationResponse); this.pollingContext.setLatestResponse(this.activationResponse); }</code><technical_language>suggestion Objects.requireNonNull(pollInterval, "'pollInterval' null.");</technical_language>

Target:
DefaultSyncPoller(Duration pollInterval, Function<PollingContext<T>, PollResponse<T>> syncActivationOperation, Function<PollingContext<T>, Mono<PollResponse<T>>> pollOperation, BiFunction<PollingContext<T>, PollResponse<T>, Mono<T>> cancelOperation, Function<PollingContext<T>, Mono<U>> fetchResultOperation) { Objects.requireNonNull(pollInterval, "'pollInterval' cannot be null."); if (pollInterval.compareTo(Duration.ZERO) <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Negative or zero value for 'defaultPollInterval' is not allowed.")); } this.defaultPollInterval = pollInterval; Objects.requireNonNull(syncActivationOperation, "'syncActivationOperation' cannot be null."); this.pollOperation = Objects.requireNonNull(pollOperation, "'pollOperation' cannot be null."); this.cancelOperation = Objects.requireNonNull(cancelOperation, "'cancelOperation' cannot be null."); this.fetchResultOperation = Objects.requireNonNull(fetchResultOperation, "'fetchResultOperation' cannot be null."); this.activationResponse = syncActivationOperation.apply(this.pollingContext); this.pollingContext.setOnetimeActivationResponse(this.activationResponse); this.pollingContext.setLatestResponse(this.activationResponse); }
Source:
<code>public void run() { while (!kernel.isConnected()) { try { this.coordinator.registerNode(kernel.getContext(), kernel.getWorkers(), new StatusChangeListener() { @Override public void onNodeStatusChanged(NodeId nodeId, NodeStatus status) { } @Override public void onCoordinatorDisconnected() { } @Override public void onCoordinatorConnected() { } }); kernel.setConnected(true); } catch (Throwable e) { log.info("ThreadId {}. KernelID Unable to connect to Coordinator. Waiting for ms", new Object[]{Thread.currentThread().getId(), kernel.getKernelId(), kernel.getReconnectPeriod()}); <START> log.warn("cause: ", e); <END> try { Thread.sleep(kernel.getReconnectPeriod()); } catch (InterruptedException ee) { log.warn("Reconnection thread was interrupted", ee); } } } }</code><technical_language>log levels</technical_language>

Target:
public void run() { while (!kernel.isConnected()) { try { this.coordinator.registerNode(kernel.getContext(), kernel.getWorkers(), new StatusChangeListener() { @Override public void onNodeStatusChanged(NodeId nodeId, NodeStatus status) { } @Override public void onCoordinatorDisconnected() { } @Override public void onCoordinatorConnected() { } }); kernel.setConnected(true); } catch (Throwable e) { log.warn("ThreadId {}. KernelID Unable to connect to Coordinator. Waiting for ms", new Object[]{Thread.currentThread().getId(), kernel.getKernelId(), kernel.getReconnectPeriod()}); log.warn("cause: ", e); try { Thread.sleep(kernel.getReconnectPeriod()); } catch (InterruptedException ee) { log.warn("Reconnection thread was interrupted", ee); } } } }
Source:
<code>public Map<String, String> extractStoreConfigs(String name) { Map<String, String> configs = new HashMap<>(); for (Map.Entry<String, String> store : storeConfigs.entrySet()) { if (store.getKey().startsWith(name)) { <START> configs.put(store.getKey().replace(name + ".", ""), store.getValue()); <END> } } return configs; }</code><technical_language>this replaced first</technical_language>

Target:
public Map<String, String> extractStoreConfigs(String name) { Map<String, String> configs = new HashMap<>(); for (Map.Entry<String, String> store : storeConfigs.entrySet()) { if (store.getKey().startsWith(name)) { configs.put(store.getKey().replaceFirst(name + ".", ""), store.getValue()); } } return configs; }
Source:
<code>public void preImport(final SubMonitor subMonitor) { subMonitor.setWorkRemaining(importers.size()); for (final Importer importer : importers) { importer.preImport(subMonitor.newChild(1, SubMonitor.SUPPRESS_NONE)); } <START> if (getImportBranchPath().getPath().equals(IBranchPath.MAIN_BRANCH)) { <END> getExistingVersions(importContext.getEditingContext()); } else { try (SnomedEditingContext snomedEditingContext = new SnomedEditingContext(BranchPathUtils.createMainPath())) { getExistingVersions(snomedEditingContext); } } }</code><technical_language>This if else construct required for existing SNOMED CT versions. editing context get stuff current ancestor branch (up MAIN)</technical_language>

Target:
public void preImport(final SubMonitor subMonitor) { subMonitor.setWorkRemaining(importers.size()); for (final Importer importer : importers) { importer.preImport(subMonitor.newChild(1, SubMonitor.SUPPRESS_NONE)); } collectExistingVersions(); }
Source:
<code>private static void copyDirectory(File src, File dest) { for (String current : src.list()) { final File srcFile = new File(src, current); final File destFile = new File(dest, current); if (srcFile.isDirectory()) { destFile.mkdir(); copyDirectory(srcFile, destFile); } else { try { <START> final InputStream in = new BufferedInputStream(new FileInputStream(srcFile)); <END> final OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile)); try { int i; while ((i = in.read()) != -1) { out.write(i); } } catch (IOException e) { throw ServerLogger.ROOT_LOGGER.errorCopyingFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath(), e); } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(out); } } catch (FileNotFoundException e) { throw EmbeddedLogger.ROOT_LOGGER.cannotSetupEmbeddedServer(e); } } } }</code><technical_language>Files#copy(....)</technical_language>

Target:
private static void copyDirectory(File src, File dest) { for (String current : src.list()) { final File srcFile = new File(src, current); final File destFile = new File(dest, current); try { Files.copy(srcFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); if (srcFile.isDirectory()) { copyDirectory(srcFile, destFile); } } catch (IOException e) { throw ServerLogger.ROOT_LOGGER.errorCopyingFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath(), e); } } }
Source:
<code>public static String getSelectedElementUUID(ClientSession clientSession) { SelectionControl selectionControl = null; if (clientSession instanceof EditorSession) { selectionControl = ((EditorSession) clientSession).getSelectionControl(); } else if (clientSession instanceof ViewerSession) { selectionControl = ((ViewerSession) clientSession).getSelectionControl(); } if (selectionControl != null) { @SuppressWarnings("unchecked") final Collection<String> selectedItems = selectionControl.getSelectedItems(); if (selectedItems != null && !selectedItems.isEmpty()) { <START> return selectedItems.iterator().next(); <END> } } return null; }</code><technical_language>conditional return sentence simplified Streams API, it</technical_language>

Target:
public static String getSelectedElementUUID(ClientSession clientSession) { Optional<Collection<String>> selectedItems = Optional.empty(); if (clientSession instanceof EditorSession) { selectedItems = Optional.ofNullable(((EditorSession) clientSession).getSelectionControl().getSelectedItems()); } else if (clientSession instanceof ViewerSession) { selectedItems = Optional.ofNullable(((ViewerSession) clientSession).getSelectionControl().getSelectedItems()); } return selectedItems.map(strings -> strings.stream().findFirst().orElse(null)).orElse(null); }
Source:
<code>public void run() { long now = System.currentTimeMillis(); <START> lastUpdateTimeMs = now; <END> List<RawPacket> pkts = report(); if (pkts == null || pkts.isEmpty()) { return; } for (RawPacket pkt : pkts) { try { getStream().injectPacket( pkt, false, BasicRTCPTerminationStrategy.this); } catch (TransmissionFailedException e) { logger.error(e); } } }</code><technical_language>point of variable here? turn 1 line 2</technical_language>

Target:
public void run() { lastUpdateTimeMs = System.currentTimeMillis(); List<RawPacket> pkts = report(); if (pkts == null || pkts.isEmpty()) { return; } for (RawPacket pkt : pkts) { try { getStream().injectPacket( pkt, false, BasicRTCPTerminationStrategy.this); } catch (TransmissionFailedException e) { logger.error(e); } } }
Source:
<code><START> public int hashCode() { <END> final int prime = 31; int result = 1; result = prime * result + fFilePath.hashCode(); result = prime * result + (int) (fOffset ^ (fOffset >>> 32)); return result; }</code><technical_language>guava, add a full <LINK_0> here</technical_language>

Target:
public int hashCode() { return Objects.hashCode(fFilePath, fOffset); }
Source:
<code>protected boolean canDoAction() { boolean retVal = true; List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); retVal = canDoAction_beforeCloneVm(retVal, canDoActionMessages, domainsMap); if (retVal && getParameters().isImportAsNewEntity()) { initImportClonedVm(); } retVal = retVal && canDoAction_afterCloneVm(retVal, canDoActionMessages, domainsMap); if (!retVal) { addCanDoActionMessage(VdcBllMessages.VAR__ACTION__IMPORT); addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM); <START> } <END> return retVal; }</code><technical_language>I setActionMessageParameters add parameter messages, instead add in CanDoAction. reason for is setActionMessageParameters is called part of flow in MoveOrCopyTemplateCommand, sets CDA list of parameter messages. happened is that, in this list, types of type, VM Template. bug in message performing template instead of VM entity type (Which now)</technical_language>

Target:
protected boolean canDoAction() { boolean retVal = true; List<String> canDoActionMessages = getReturnValue().getCanDoActionMessages(); Map<Guid, storage_domains> domainsMap = new HashMap<Guid, storage_domains>(); retVal = canDoAction_beforeCloneVm(retVal, canDoActionMessages, domainsMap); if (retVal && getParameters().isImportAsNewEntity()) { initImportClonedVm(); } return retVal && canDoAction_afterCloneVm(retVal, canDoActionMessages, domainsMap); }
Source:
<code>public ActivationKey createActivationKey( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, ActivationKey activationKey) { Owner owner = findOwner(ownerKey); activationKey.setOwner(owner); if (activationKey.getName() == null || activationKey.getName().trim().equals("")) { throw new BadRequestException( i18n.tr("Must provide a name for activation key.")); } String testName = activationKey.getName().replace("-", "0") .replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters '-' or '_'", activationKey.getName())); } if (activationKeyCurator.lookupForOwner(activationKey.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", activationKey.getName(), ownerKey)); } if (activationKey.getContentOverrides() != null) { contentOverrideValidator.validate(activationKey.getContentOverrides()); } <START> if (activationKey.getServiceLevel() != null) { <END> serviceLevelValidator.validate(owner, activationKey.getServiceLevel()); } ActivationKey newKey = activationKeyCurator.create(activationKey); sink.emitActivationKeyCreated(newKey); return newKey; }</code><technical_language>I StringUtils.isBlank() here, remove 'serviceLevel = ""' Consumer.java</technical_language>

Target:
public ActivationKey createActivationKey( @PathParam("owner_key") @Verify(Owner.class) String ownerKey, ActivationKey activationKey) { Owner owner = findOwner(ownerKey); activationKey.setOwner(owner); if (activationKey.getName() == null || activationKey.getName().trim().equals("")) { throw new BadRequestException( i18n.tr("Must provide a name for activation key.")); } String testName = activationKey.getName().replace("-", "0") .replace("_", "0"); if (!testName.matches("[a-zA-Z0-9]*")) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' must be alphanumeric or " + "include the characters '-' or '_'", activationKey.getName())); } if (activationKeyCurator.lookupForOwner(activationKey.getName(), owner) != null) { throw new BadRequestException( i18n.tr("The activation key name ''{0}'' is already in use for owner {1}", activationKey.getName(), ownerKey)); } if (activationKey.getContentOverrides() != null) { contentOverrideValidator.validate(activationKey.getContentOverrides()); } serviceLevelValidator.validate(owner, activationKey.getServiceLevel()); ActivationKey newKey = activationKeyCurator.create(activationKey); sink.emitActivationKeyCreated(newKey); return newKey; }
Source:
<code>public void testJSEEJava8() throws IOException { assumeTrue(System.getProperty("java.version").startsWith("1.8")); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.Default_JSSE); <START> assertTrue(Arrays.stream(OpenSSLSocketFactory.getDefaultFactory() <END> .getSupportedCipherSuites()).noneMatch("GCM"::contains)); }</code><technical_language>again, needs text. Nice trick "GCM::contains" BTW</technical_language>

Target:
public void testJSEEJava8() throws IOException { assumeTrue(System.getProperty("java.version").startsWith("1.8")); OpenSSLSocketFactory.initializeDefaultFactory( OpenSSLSocketFactory.SSLChannelMode.Default_JSSE); assertThat(Arrays.stream(OpenSSLSocketFactory.getDefaultFactory() .getSupportedCipherSuites())).noneMatch("GCM"::contains); }
Source:
<code>protected List<File> mGet(Message<?> message, Session<F> session, String remoteDirectory, String remoteFilename) throws IOException { if (this.options.contains(Option.RECURSIVE)) { if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) { logger.warn("File name pattern must be '*' when using recursion"); } if (this.options.contains(Option.NAME_ONLY)) { this.options.remove(Option.NAME_ONLY); } return mGetWithRecursion(message, session, remoteDirectory, remoteFilename); } else { remoteDirectory = (remoteDirectory != null ? remoteDirectory <START> : "." + this.remoteFileTemplate.getRemoteFileSeparator()); <END> return mGetWithoutRecursion(message, session, remoteDirectory, remoteFilename); } }</code><technical_language>No; need support MGET a null path; especially if recursion - allow, recursion</technical_language>

Target:
protected List<File> mGet(Message<?> message, Session<F> session, String remoteDirectory, String remoteFilename) throws IOException { if (this.options.contains(Option.RECURSIVE)) { if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) { logger.warn("File name pattern must be '*' when using recursion"); } if (this.options.contains(Option.NAME_ONLY)) { this.options.remove(Option.NAME_ONLY); } return mGetWithRecursion(message, session, remoteDirectory, remoteFilename); } else { return mGetWithoutRecursion(message, session, remoteDirectory, remoteFilename); } }
Source:
<code>public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); <START> throttled.json(); <END> MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo("{}") ); }</code><technical_language>Hm.. testing Mockito here, instead of Throttled class :) familiar TDD, Mockito JUnit? explain logic of this test method</technical_language>

Target:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); throttled.json(); }
Source:
<code>public void testPackageLink() { when(menu.findMenuItemPath(NAVIGATOR)).thenReturn("menu/main/navigation/navigator"); when(menuReaderService.getMenu()).thenReturn(menu); <START> LinkedList<NavigatorLink> expected = new LinkedList(); <END> expected.add(NavigatorLink.create("menu/main/navigation/navigator/", "glyphicon-home")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/parentId", "parent")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/packId", "pack")); assertEquals(controller.getNavigatorLinks(entityTypeId), expected); }</code><technical_language>Intelij warns type conversion</technical_language>

Target:
public void testPackageLink() { when(menu.findMenuItemPath(NAVIGATOR)).thenReturn("menu/main/navigation/navigator"); when(menuReaderService.getMenu()).thenReturn(menu); List<NavigatorLink> expected = new LinkedList<>(); expected.add(NavigatorLink.create("menu/main/navigation/navigator/", "glyphicon-home")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/parentId", "parent")); expected.add(NavigatorLink.create("menu/main/navigation/navigator/packId", "pack")); assertEquals(controller.getNavigatorLinks(entityTypeId), expected); }
Source:
<code>public void testMissingProfile() { <START> org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester <END> tableRequirementTester = new org.eclipse.papyrus.sysml14.nattable.requirement.tester.RequirementTableTester(); org.eclipse.uml2.uml.Package pck = UMLFactory.eINSTANCE.createPackage(); IStatus missingStereotypeNotAllowed = tableRequirementTester.isAllowed(pck); Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); }</code><technical_language>why</technical_language>

Target:
public void testMissingProfile() { RequirementTableTester tableRequirementTester = new RequirementTableTester(); org.eclipse.uml2.uml.Package pck = UMLFactory.eINSTANCE.createPackage(); IStatus missingStereotypeNotAllowed = tableRequirementTester.isAllowed(pck); Assert.assertEquals("The tester should not work on a non profiled entry", IStatus.ERROR, missingStereotypeNotAllowed.getSeverity()); }
Source:
<code>public static LinkdEdge create(String id, AbstractVertex sourceV, AbstractVertex targetV, OnmsSnmpInterface sourceinterface, OnmsSnmpInterface targetInterface, String sourceAddr, String targetAddr, ProtocolSupported discoveredBy) { SimpleConnector source = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, sourceV.getId()+"-"+id+"-connector", sourceV); SimpleConnector target = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, targetV.getId()+"-"+id+"-connector", targetV); LinkdEdge edge = new LinkdEdge(id, source, target,discoveredBy); try { <START> edge.setSourceNodeid(Integer.parseInt(sourceV.getId())); <END> } catch (NumberFormatException e) { } try { edge.setTargetNodeid(Integer.parseInt(targetV.getId())); } catch (NumberFormatException e) { } edge.setSourceLabel(sourceV.getLabel()); edge.setTargetLabel(targetV.getLabel()); if (sourceinterface != null) { edge.setSourceIfIndex(sourceinterface.getIfIndex()); edge.setSourceIfName(sourceinterface.getIfName()); if (sourceinterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(sourceinterface.getIfSpeed())); } } if (targetInterface != null) { edge.setTargetIfIndex(targetInterface.getIfIndex()); edge.setTargetIfName(targetInterface.getIfName()); if (edge.getSpeed() == null && targetInterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(targetInterface.getIfSpeed())); } } edge.setSourceAddr(sourceAddr); edge.setTargetAddr(targetAddr); return edge; }</code><technical_language>Is a reason sourceV.getId() is instead of sourceV.getNodeID()</technical_language>

Target:
public static LinkdEdge create(String id, AbstractVertex sourceV, AbstractVertex targetV, OnmsSnmpInterface sourceinterface, OnmsSnmpInterface targetInterface, String sourceAddr, String targetAddr, ProtocolSupported discoveredBy) { SimpleConnector source = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, sourceV.getId()+"-"+id+"-connector", sourceV); SimpleConnector target = new SimpleConnector(LinkdTopologyProvider.TOPOLOGY_NAMESPACE_LINKD, targetV.getId()+"-"+id+"-connector", targetV); LinkdEdge edge = new LinkdEdge(id, source, target,discoveredBy); edge.setSourceNodeid(sourceV.getNodeID()); edge.setTargetNodeid(targetV.getNodeID()); edge.setSourceLabel(sourceV.getLabel()); edge.setTargetLabel(targetV.getLabel()); if (sourceinterface != null) { edge.setSourceIfIndex(sourceinterface.getIfIndex()); edge.setSourceIfName(sourceinterface.getIfName()); if (sourceinterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(sourceinterface.getIfSpeed())); } } if (targetInterface != null) { edge.setTargetIfIndex(targetInterface.getIfIndex()); edge.setTargetIfName(targetInterface.getIfName()); if (edge.getSpeed() == null && targetInterface.getIfSpeed() != null) { edge.setSpeed(InetAddressUtils.getHumanReadableIfSpeed(targetInterface.getIfSpeed())); } } edge.setSourceAddr(sourceAddr); edge.setTargetAddr(targetAddr); return edge; }
Source:
<code>public boolean hasNext() { if (bufferedRecord != null) { return true; } try { bufferedRecord = readNextWarcRecord(stream, Document.WARC_VERSION); } catch (IOException e) { <START> LOG.error("Exception from BufferedReader:", e); <END> return false; } return bufferedRecord != null; }</code><technical_language>update indexing counter here</technical_language>

Target:
public boolean hasNext() { if (bufferedRecord != null) { return true; } try { bufferedRecord = readNextWarcRecord(stream, Document.WARC_VERSION); } catch (NoSuchElementException e1) { return false; } catch (IOException e2) { LOG.error("Exception from BufferedReader:", e2); return false; } return bufferedRecord != null; }
Source:
<code>private URI addCookieInterceptorIfRequired(URI uri) throws URISyntaxException { String uriProtocol = uri.getScheme(); String uriHost = uri.getHost(); String uriPath = uri.getRawPath(); int uriPort = uri.getPort(); if (uriPort < 0) { if ("http".equals(uriProtocol)) { uriPort = 80; } else if ("https".equals(uriProtocol)) { uriPort = 443; } } Misc.checkArgument(uriPort >= 0, String.format(Locale.ENGLISH, <START> "Could not determine default port for protocol \"%s\"", uriProtocol)); <END> if (uri.getUserInfo() != null) { String[] parts = uri.getUserInfo().split(":"); if (parts.length == 2) { CookieInterceptor ci = new CookieInterceptor(parts[0], parts[1]); requestInterceptors.add(ci); responseInterceptors.add(ci); } } URI redacted = new URI(uriProtocol + "://" + uriHost + ":" + uriPort + (uriPath != null ? uriPath : "")); return redacted; }</code><technical_language>a bit odd IllegalArgumentException thrown a port determined. Unsupported protocol message more sense</technical_language>

Target:
private URI addCookieInterceptorIfRequired(URI uri) { String uriProtocol = uri.getScheme(); String uriHost = uri.getHost(); String uriPath = uri.getRawPath(); int uriPort = uri.getPort(); if ("http".equals(uriProtocol)) { uriPort = uriPort < 0 ? 80 : uriPort; } else if ("https".equals(uriProtocol)) { uriPort = uriPort < 0 ? 443 : uriPort; } else { throw new IllegalArgumentException(String.format(Locale.ENGLISH, "Protocol %s not supported", uriProtocol)); } if (uri.getUserInfo() != null) { String[] parts = uri.getUserInfo().split(":"); if (parts.length == 2) { CookieInterceptor ci = new CookieInterceptor(parts[0], parts[1]); requestInterceptors.add(ci); responseInterceptors.add(ci); } } try { return new URI(uriProtocol + "://" + uriHost + ":" + uriPort + (uriPath != null ? uriPath : "")); } catch (URISyntaxException use) { throw new RuntimeException("Failed to construct URI", use); } }
Source:
<code><START> @Override protected void onFinishInflate() { <END> super.onFinishInflate(); ((TextView) findViewById(R.id.email)).setText(editor.email); EditText nameView = (EditText) findViewById(R.id.edit_name); nameView.setText(editor.name); nameView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { editor.name = s.toString(); } @Override public void afterTextChanged(Editable s) { } }); nameView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Flow.get(v).set(new EditEmailScreen(editor.id)); return true; } }); }</code><technical_language>onAttachedToWindow</technical_language>

Target:
@Override protected void onFinishInflate() { super.onFinishInflate(); emailView = (TextView) findViewById(R.id.email); nameView = (EditText) findViewById(R.id.edit_name); }
Source:
<code>public void addUpdate(String updatedItemName, byte[] updatedItemData) { synchronized (itemsToUpdate) { itemsToUpdate.add(updatedItemName); serializedMaps.put(updatedItemName, updatedItemData); <START> itemsToUpdate.notify(); <END> } }</code><technical_language>notifier notifies update time. collect updates for a time (like 100 ms) send in bulk reduce API calls. this I guess credentials frequently updated. If want current behavior, itemsToUpdate serializedMaps a single element in them. Instead, I AtomicReference<Pair<String, byte[]>> simply put a Pair<String, byte[]> blockingQueue if decide it</technical_language>

Target:
public void addUpdate(String updatedItemName, byte[] updatedItemData) { updateQueue.add( new Pair<>(updatedItemName, updatedItemData) ); }
Source:
<code>protected void executeQueryCommand() { Guid vdsId = getParameters().getId(); String[] names = new String[0]; setLldpVDSCommandParameters(new <START> GetLldpVDSCommandParameters(vdsId, names)); <END> super.executeQueryCommand(); }</code><technical_language>getVdsId()</technical_language>

Target:
protected void executeQueryCommand() { String[] names = new String[0]; setLldpVDSCommandParameters(new GetLldpVDSCommandParameters(getVdsId(), names)); super.executeQueryCommand(); }
Source:
<code>public boolean isType(String value) { GlusterStatus volStatus = <START> GlusterStatus.valueOf(value); <END> for (GlusterStatus status : values) { if (status.equals(volStatus)) { return true; } } return false; }</code><technical_language>This throw IllegalArgumentException in case match enum constant. easier compare name() of enum constants: for (GlusterStatus status : values) { if (status.name().equals(value)) { return true; } } return false;</technical_language>

Target:
public boolean isType(String value) { for (GlusterStatus status : values) { if (status.name().equals(value)) { return true; } } return false; }
Source:
<code>public CPPASTLiteralExpression copy(CopyStyle style) { CPPASTLiteralExpression copy = new CPPASTLiteralExpression(fKind, this.getValue()); copy.fNumericCompilerSuffixes = <START> fNumericCompilerSuffixes.clone(); <END> copy.fStringLiteralSize = fStringLiteralSize; copy.fEvaluation = fEvaluation; copy.fUserDefinedLiteralOperator = fUserDefinedLiteralOperator; copy.fImplicitNames = fImplicitNames == null ? null : fImplicitNames.clone(); return copy(copy, style); }</code><technical_language>is unfortunate compiler suffixes, supposed change, cloned here. Cloning avoided passing compiler suffixes constructor a parameter</technical_language>

Target:
public CPPASTLiteralExpression copy(CopyStyle style) { CPPASTLiteralExpression copy = new CPPASTLiteralExpression(fKind, this.getValue(), fNumericCompilerSuffixes); copy.fStringLiteralSize = fStringLiteralSize; copy.fEvaluation = fEvaluation; copy.fUserDefinedLiteralOperator = fUserDefinedLiteralOperator; copy.fImplicitNames = fImplicitNames; return copy(copy, style); }
Source:
<code>public ResponseEntity<String> upload(@RequestPart("file") MultipartFile file) throws SdkClientException, AmazonServiceException, URISyntaxException, IOException { String documentName = file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, documentName, file.getInputStream(), objectMetadata) .withCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectRequest); String objectUrl = s3Client.getUrl(this.bucketName, documentName).toExternalForm(); log.info("Uploaded " + documentName + " to S3 bucket: " + objectUrl); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(new URI(objectUrl)); List<String> headerNames = new ArrayList<>(); headerNames.add("location"); <START> responseHeaders.setAccessControlExposeHeaders(headerNames); <END> return new ResponseEntity<String>(responseHeaders, HttpStatus.CREATED); }</code><technical_language>work this adjustment exposed headers in <LINK_0>, in place</technical_language>

Target:
public ResponseEntity<String> upload(@RequestPart("file") MultipartFile file) throws SdkClientException, AmazonServiceException, URISyntaxException, IOException { String documentName = file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, documentName, file.getInputStream(), objectMetadata) .withCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectRequest); String objectUrl = s3Client.getUrl(this.bucketName, documentName).toExternalForm(); log.info("Uploaded " + documentName + " to S3 bucket: " + objectUrl); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setLocation(new URI(objectUrl)); return new ResponseEntity<String>(responseHeaders, HttpStatus.CREATED); }
Source:
<code>TerminationData killTask(JobId jobId, String taskName) throws UnknownJobException, UnknownTaskException { JobData jobData = lockJob(jobId); if (jobData == null) { throw new UnknownJobException(jobId); } try { InternalTask task = jobData.job.getTask(taskName); if (!task.getStatus().isTaskAlive()) { tlogger.info(task.getId(), "task isn't alive: " + task.getStatus()); return emptyResult(task.getId()); } RunningTaskData taskData = runningTasksData.remove(TaskIdWrapper.wrap(task.getId())); if (taskData == null) { throw new IllegalStateException("No information for: " + task.getId()); } TaskResultImpl taskResult = new TaskResultImpl(task.getId(), new TaskAbortedException("Aborted by user"), new SimpleTaskLogs("", "Aborted by user"), System.currentTimeMillis() - task.getStartTime()); TerminationData terminationData = TerminationData.newTerminationData(); <START> terminationData.addTaskData(jobData.job, taskData, false, taskResult); <END> if (onErrorPolicyInterpreter.requiresCancelJobOnError(task)) { endJob(jobData, terminationData, task, taskResult, "The task has been manually killed. " + "You also ask to cancel the job in such a situation!", JobStatus.CANCELED); } else { terminateTask(jobData, task, true, taskResult, terminationData); } return terminationData; } finally { jobData.unlock(); } }</code><technical_language>This 2 lines of code repeated 3 times. wrap instructions in a private method a name</technical_language>

Target:
TerminationData killTask(JobId jobId, String taskName) throws UnknownJobException, UnknownTaskException { JobData jobData = lockJob(jobId); if (jobData == null) { throw new UnknownJobException(jobId); } try { InternalTask task = jobData.job.getTask(taskName); if (!task.getStatus().isTaskAlive()) { tlogger.info(task.getId(), "task isn't alive: " + task.getStatus()); return emptyResult(task.getId()); } RunningTaskData taskData = runningTasksData.remove(TaskIdWrapper.wrap(task.getId())); if (taskData == null) { throw new IllegalStateException("No information for: " + task.getId()); } TaskResultImpl taskResult = new TaskResultImpl(task.getId(), new TaskAbortedException("Aborted by user"), new SimpleTaskLogs("", "Aborted by user"), System.currentTimeMillis() - task.getStartTime()); TerminationData terminationData = createAndFillTerminationData(taskResult,taskData,jobData.job,false); if (onErrorPolicyInterpreter.requiresCancelJobOnError(task)) { endJob(jobData, terminationData, task, taskResult, "The task has been manually killed. " + "You also ask to cancel the job in such a situation!", JobStatus.CANCELED); } else { terminateTask(jobData, task, true, taskResult, terminationData); } return terminationData; } finally { jobData.unlock(); } }
Source:
<code>public <T> Vector<T> intersection(Vector<T> a, Vector<T> b) { <START> Vector<T> result = new Vector<>(); <END> HashSet<T> setA = new HashSet<>(a); HashSet<T> setB = new HashSet<>(b); setA.retainAll(setB); result.addAll(setA); return result; }</code><technical_language>move initializing this right used? readability a bit</technical_language>

Target:
public <T> Vector<T> intersection(Vector<T> a, Vector<T> b) { HashSet<T> setA = new HashSet<>(a); HashSet<T> setB = new HashSet<>(b); setA.retainAll(setB); return new Vector<>(setA); }
Source:
<code>public void doGet(HttpServletRequest req, HttpServletResponse resp) { String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); try { StudentsLogic.inst().sendRegistrationInviteToStudent(courseId, studentEmail); } catch (EntityDoesNotExistException e) { <START> log.severe("Unexpected error while sending emails " + e.getMessage()); <END> } }</code><technical_language>TeammatesException.toStringWithStackTrace(e) e.getMessage() swallows else other error message</technical_language>

Target:
public void doGet(HttpServletRequest req, HttpServletResponse resp) { String courseId = HttpRequestHelper.getValueFromRequestParameterMap(req, ParamsNames.COURSE_ID); Assumption.assertNotNull(courseId); String studentEmail = HttpRequestHelper.getValueFromRequestParameterMap(req, ParamsNames.STUDENT_EMAIL); Assumption.assertNotNull(studentEmail); try { StudentsLogic.inst().sendRegistrationInviteToStudent(courseId, studentEmail); } catch (EntityDoesNotExistException e) { log.severe("Unexpected error while sending emails " + TeammatesException.toStringWithStackTrace(e)); } }
Source:
<code>void throwingEvaluatorIsCreatedWhenScriptEngineIsNotAvailable() { String nameOfScriptEngine = "javax.script.DoesNotExist"; String name = "org.junit.jupiter.engine.extension.ScriptExecutionEvaluator"; ScriptExecutionCondition.Evaluator evaluator = ScriptExecutionCondition.Evaluator.forName(nameOfScriptEngine, name); Exception e = assertThrows(Exception.class, () -> evaluator.evaluate(null, null)); assertTrue(e instanceof ExtensionConfigurationException); String message = e.getMessage(); System.out.println(message); assertTrue(message.startsWith("Class `" + nameOfScriptEngine + "` is not loadable")); <START> assertTrue(message.endsWith("`--add-modules ...,java.scripting`")); <END> }</code><technical_language>java assertThat(e).isInstanceOf(ExtensionConfigurationException.class) .hasMessageStartingWith("Class " + nameOfScriptEngine + " is loadable") .hasMessageEndingWith("--add-modules ...,java.scripting")</technical_language>

Target:
void throwingEvaluatorIsCreatedWhenScriptEngineIsNotAvailable() { String nameOfScriptEngine = "javax.script.DoesNotExist"; String name = "org.junit.jupiter.engine.extension.ScriptExecutionEvaluator"; ScriptExecutionCondition.Evaluator evaluator = ScriptExecutionCondition.Evaluator.forName(nameOfScriptEngine, name); Exception e = assertThrows(Exception.class, () -> evaluator.evaluate(null, null)); assertThat(e) .isInstanceOf(ExtensionConfigurationException.class) .hasMessageStartingWith("Class `" + nameOfScriptEngine + "` is not loadable") .hasMessageEndingWith("`--add-modules ...,java.scripting`"); }
Source:
<code>public void testCallbackOnCancel() throws Exception { TestCancellableCallable callable = new TestCancellableCallable("results"); Future<String> future = admin.schedule(callable, callback); <START> Thread.sleep(500); <END> future.cancel(true); verify(callback, times(0)).onSuccess(Matchers.anyString()); verify(callback).onCancelled(); verify(callback, times(0)).onFailure(Matchers.<Throwable> any()); assertEquals(true, callable.isCancelled()); assertEquals(true, future.isCancelled()); thrown.expect(CancellationException.class); future.get(); }</code><technical_language>Instead of sleeping, wait future is scheduled</technical_language>

Target:
public void testCallbackOnCancel() throws Exception { TestCancellableCallable callable = new TestCancellableCallable("results"); Future<String> future = admin.schedule(callable, callback); while (!callable.hasBeenCalled()) { Thread.sleep(20); } future.cancel(true); verify(callback, times(0)).onSuccess(Matchers.anyString()); verify(callback).onCancelled(); verify(callback, times(0)).onFailure(Matchers.<Throwable> any()); assertEquals(true, callable.isCancelled()); assertEquals(true, future.isCancelled()); thrown.expect(CancellationException.class); future.get(); }