auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { ExtensionContext extensionContext = context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = extensionContext.getRequiredTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, extensionContext, <START> context.getExtensionRegistry(), INTERCEPTOR_CALL); <END> TestSource defaultTestSource = getSource().orElseThrow( () -> new JUnitException("Illegal state: TestSource must be present")); try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { int index = 1; Iterator<DynamicNode> iterator = dynamicNodeStream.iterator(); while (iterator.hasNext()) { DynamicNode dynamicNode = iterator.next(); Optional<JupiterTestDescriptor> descriptor = createDynamicDescriptor(this, dynamicNode, index++, defaultTestSource, getDynamicDescendantFilter(), configuration); descriptor.ifPresent(dynamicTestExecutor::execute); } } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } dynamicTestExecutor.awaitFinished(); }); }</code><technical_language>suggestion context.getExtensionRegistry(), interceptorCall);</technical_language>

Target:
protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { ExtensionContext extensionContext = context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = extensionContext.getRequiredTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, extensionContext, context.getExtensionRegistry(), interceptorCall); TestSource defaultTestSource = getSource().orElseThrow( () -> new JUnitException("Illegal state: TestSource must be present")); try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { int index = 1; Iterator<DynamicNode> iterator = dynamicNodeStream.iterator(); while (iterator.hasNext()) { DynamicNode dynamicNode = iterator.next(); Optional<JupiterTestDescriptor> descriptor = createDynamicDescriptor(this, dynamicNode, index++, defaultTestSource, getDynamicDescendantFilter(), configuration); descriptor.ifPresent(dynamicTestExecutor::execute); } } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } dynamicTestExecutor.awaitFinished(); }); }
Source:
<code>private int index(final Talk talk) throws IOException { final List<Integer> indexes = new ListOf<>( new Mapped<>( input -> new NumberOf(input).intValue(), talk.read() .xpath("/talk/archive/log/@index|/talk/request/@index") ) ); final int index; if (indexes.iterator().hasNext()) { try { index = new MaxOf( indexes.toArray(new Integer[indexes.size()]) ).intValue(); <START> } catch (final Throwable ex) { <END> throw new IOException(ex); } } else { index = 0; } return index; }</code><technical_language>@filfreire UncheckedScalar instead</technical_language>

Target:
private int index(final Talk talk) throws IOException { final SolidList<Number> indexes = new SolidList<>( new Mapped<>( input -> new NumberOf(input), talk.read() .xpath("/talk/archive/log/@index|/talk/request/@index") ) ); final int index; if (indexes.iterator().hasNext()) { index = new MaxOf(indexes).intValue(); } else { index = 0; } return index; }
Source:
<code>public ProviderNetworkListModel() { setTitle(ConstantsManager.getInstance().getConstants().providerNetworksTitle()); setHashName("networks"); setDiscoverCommand(new UICommand(CMD_DISCOVER, this)); <START> setComparator(new Comparator() { <END> private Comparator<Network> netComparator = new Linq.NetworkByNameComparer(); @Override public int compare(Object o1, Object o2) { return netComparator.compare((Network) o1, (Network) o2); } }); }</code><technical_language>do- setComparator(new Linq.NetworkByNameComparer())</technical_language>

Target:
public ProviderNetworkListModel() { setTitle(ConstantsManager.getInstance().getConstants().providerNetworksTitle()); setHashName("networks"); setDiscoverCommand(new UICommand(CMD_DISCOVER, this)); setComparator(new NameableComparator()); }
Source:
<code>public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (stack == null || stack.stackSize == 0) return null; <START> ItemStack[] stacks = this.stacks; <END> validateSlotIndex(slot, stacks); ItemStack existing = stacks[slot]; int limit = getStackLimit(slot, stack); if (existing != null) { if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) return stack; limit -= existing.stackSize; } if (limit == 0) return stack; boolean reachedLimit = stack.stackSize > limit; if (!simulate) { if (existing == null) { stacks[slot] = reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, stack.stackSize - limit) : stack; } else { existing.stackSize += reachedLimit ? limit : stack.stackSize; } onContentsChanged(slot); } return reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : null; }</code><technical_language>minor, a bit redundant</technical_language>

Target:
public ItemStack insertItem(int slot, ItemStack stack, boolean simulate) { if (stack == null || stack.stackSize == 0) return null; validateSlotIndex(slot); ItemStack existing = this.stacks[slot]; int limit = getStackLimit(slot, stack); if (existing != null) { if (!ItemHandlerHelper.canItemStacksStack(stack, existing)) return stack; limit -= existing.stackSize; } if (limit <= 0) return stack; boolean reachedLimit = stack.stackSize > limit; if (!simulate) { if (existing == null) { this.stacks[slot] = reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, limit) : stack; } else { existing.stackSize += reachedLimit ? limit : stack.stackSize; } onContentsChanged(slot); } return reachedLimit ? ItemHandlerHelper.copyStackWithSize(stack, stack.stackSize - limit) : null; }
Source:
<code>public Object[][] arbFracSensDataProvider() { final File wgsMetricsFile = new File(TEST_DIR, "test_Solexa-332667.wgs_metrics"); return new Object[][] { <START> {0.90, wgsMetricsFile, .5, 100}, <END> {0.77, wgsMetricsFile, .3, 100}, {0.29, wgsMetricsFile, .1, 100}, {0.08, wgsMetricsFile, .05, 100}, }; }</code><technical_language>space here</technical_language>

Target:
public Object[][] arbFracSensDataProvider() { final File wgsMetricsFile = new File(TEST_DIR, "test_Solexa-332667.wgs_metrics"); return new Object[][] { {0.90, wgsMetricsFile, 0.5, 100}, {0.77, wgsMetricsFile, 0.3, 100}, {0.29, wgsMetricsFile, 0.1, 100}, {0.08, wgsMetricsFile, 0.05, 100}, }; }
Source:
<code>public Configuration removeConfiguration(String name) { Configuration conf = getConfiguration(name); <START> if (conf != null && !conf.equals(containerConfiguration)) <END> { configList.remove(conf); namedConfigurations.remove(name); } return conf; }</code><technical_language>sense throw IllegalArgumentException if conf is containerConfiguration? return containerConfiguration behaves config is removed</technical_language>

Target:
public Configuration removeConfiguration(String name) { Configuration conf = getConfiguration(name); if (conf != null && !conf.equals(containerConfiguration)) { configList.remove(conf); namedConfigurations.remove(name); } else if (conf != null && conf.equals(containerConfiguration)) { throw new IllegalArgumentException("Can't remove container configuration"); } return conf; }
Source:
<code>protected void executeQueryCommand() { String suggestedDiskName = null; if (getParameters().getId() == null) { getQueryReturnValue().setReturnValue(suggestedDiskName); } else { VM vm = getDbFacade().getVmDao().get(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (vm != null) { updateDisksFromDb(vm); <START> List<String> aliases = createDiskAliasesList(vm); <END> int i = 0; do { i++; suggestedDiskName = ImagesHandler.getDefaultDiskAlias(vm.getName(), Integer.toString(vm.getDiskMapCount() + i)); } while(aliases.contains(suggestedDiskName)); } getQueryReturnValue().setReturnValue(suggestedDiskName); } }</code><technical_language>a Set, a List</technical_language>

Target:
protected void executeQueryCommand() { String suggestedDiskName = null; if (getParameters().getId() == null) { getQueryReturnValue().setReturnValue(suggestedDiskName); } else { VM vm = getDbFacade().getVmDao().get(getParameters().getId(), getUserID(), getParameters().isFiltered()); if (vm != null) { updateDisksFromDb(vm); suggestedDiskName = getSuggestedDiskName(vm); } getQueryReturnValue().setReturnValue(suggestedDiskName); } }
Source:
<code>public Response add(ClusterFeature feature) { validateParameters(feature); org.ovirt.engine.core.common.businessentities.AdditionalFeature featureEntity = map(feature, null); org.ovirt.engine.core.common.businessentities.Cluster cluster = BackendClusterFeatureHelper.getClusterEntity(this, asGuid(clusterId)); SupportedAdditionalClusterFeature supportedFeature = new SupportedAdditionalClusterFeature(); supportedFeature.setFeature(featureEntity); supportedFeature.setEnabled(true); supportedFeature.setClusterId(asGuid(clusterId)); cluster.getAddtionalFeaturesSupported().add(supportedFeature); ManagementNetworkOnClusterOperationParameters param = new ManagementNetworkOnClusterOperationParameters(cluster); return <START> performAction(ActionType.UpdateCluster, <END> param); }</code><technical_language>This method return "Action" object, generated XML response this: <action ..> </action> is want, this method return added feature: <cluster_feature ...> </cluster_feature> achieve "performCreate" method</technical_language>

Target:
public Response add(ClusterFeature feature) { validateParameters(feature); org.ovirt.engine.core.common.businessentities.AdditionalFeature featureEntity = map(feature, null); org.ovirt.engine.core.common.businessentities.Cluster cluster = BackendClusterFeatureHelper.getClusterEntity(this, clusterId); SupportedAdditionalClusterFeature supportedFeature = new SupportedAdditionalClusterFeature(); supportedFeature.setFeature(featureEntity); supportedFeature.setEnabled(true); supportedFeature.setClusterId(clusterId); cluster.getAddtionalFeaturesSupported().add(supportedFeature); ManagementNetworkOnClusterOperationParameters param = new ManagementNetworkOnClusterOperationParameters(cluster); return performCreate(ActionType.UpdateCluster, param, new ClusterFeatureIdResolver(clusterId, featureEntity.getId())); }
Source:
<code>protected void modified(Map<String, Object> config) { <START> config.keySet().stream().filter(k -> k.startsWith(CONFIG_DAYSET_PREFIX)).forEach(k -> { <END> String[] setDefinition = config.get(k).toString().split(","); String[] setNameParts = k.split("-"); if (setDefinition.length > 0 && setNameParts.length > 1) { Set<DayOfWeek> dayset = new HashSet<>(); Stream.of(setDefinition).forEach(day -> { dayset.add(DayOfWeek.valueOf(day.toUpperCase())); }); daysets.put(setNameParts[1], dayset); } else { logger.warn("Erroneus dayset definition : {}", k, config.get(k)); } }); country = getValueAsString(config, CONFIG_COUNTRY); if (country == null && localeProvider != null) { country = localeProvider.getLocale().getCountry(); logger.debug("Using system default country '{}' ", country); } if (config.containsKey(CONFIG_REGION)) { countryParameters.add(getValueAsString(config, CONFIG_REGION)); } if (config.containsKey(CONFIG_CITY)) { countryParameters.add(getValueAsString(config, CONFIG_CITY)); } }</code><technical_language>If interested in key sense entry set instead of a key set call config.get(k)</technical_language>

Target:
protected void modified(Map<String, Object> config) { config.entrySet().stream().filter(e -> e.getKey().startsWith(CONFIG_DAYSET_PREFIX)).forEach(e -> { String[] setDefinition = e.getValue().toString().toUpperCase().split(","); String[] setNameParts = e.getKey().split("-"); if (setDefinition.length > 0 && setNameParts.length > 1) { Set<DayOfWeek> dayset = new HashSet<>(); Stream.of(setDefinition).forEach(day -> { dayset.add(DayOfWeek.valueOf(day)); }); daysets.put(setNameParts[1], dayset); } else { logger.warn("Erroneous dayset definition : {}", e.getKey(), e.getValue()); } }); if (config.containsKey(CONFIG_COUNTRY)) { country = config.get(CONFIG_COUNTRY).toString(); } else { country = localeProvider.getLocale().getCountry(); logger.debug("Using system default country '{}' ", country); } if (config.containsKey(CONFIG_REGION)) { countryParameters.add(config.get(CONFIG_REGION).toString()); } if (config.containsKey(CONFIG_CITY)) { countryParameters.add(config.get(CONFIG_CITY).toString()); } }
Source:
<code>public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { <START> assert PING_TIMEOUT < this.apnsClient.idlePingIntervalMillis; <END> log.trace("Sending ping due to inactivity."); final ByteBuf pingDataBuffer = context.alloc().ioBuffer(8, 8); pingDataBuffer.writeLong(this.nextPingId++); this.encoder().writePing(context, false, pingDataBuffer, context.newPromise()).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { ApnsClientHandler.this.pingTimeoutFuture = future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); future.channel().close(); } }, PING_TIMEOUT, TimeUnit.SECONDS); } else { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.flush(context); } super.userEventTriggered(context, event); }</code><technical_language>For folks this thread, discussed this in <LINK_0></technical_language>

Target:
public void userEventTriggered(final ChannelHandlerContext context, final Object event) throws Exception { if (event instanceof IdleStateEvent) { log.trace("Sending ping due to inactivity."); final ByteBuf pingDataBuffer = context.alloc().ioBuffer(Long.SIZE, Long.SIZE); pingDataBuffer.writeLong(System.currentTimeMillis()); this.encoder().writePing(context, false, pingDataBuffer, context.newPromise()).addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { log.debug("Failed to write PING frame.", future.cause()); future.channel().close(); } } }); this.pingTimeoutFuture = context.channel().eventLoop().schedule(new Runnable() { @Override public void run() { log.debug("Closing channel due to ping timeout."); context.channel().close(); } }, pingTimeoutMillis, TimeUnit.MILLISECONDS); this.flush(context); } super.userEventTriggered(context, event); }
Source:
<code>private Service getCheWorkspaceService() throws IOException { ServiceList services = openShiftClient.services().inNamespace(this.cheOpenShiftProjectName).list(); Service service = services.getItems().stream() .filter(s -> s.getMetadata().getName().startsWith(CHE_OPENSHIFT_RESOURCES_PREFIX)) .findFirst().orElse(null); if (service == null) { <START> LOG.error("No service with prefix " + CHE_OPENSHIFT_RESOURCES_PREFIX +" found"); <END> throw new IOException("No service with prefix " + CHE_OPENSHIFT_RESOURCES_PREFIX +" found"); } return service; }</code><technical_language>do + +</technical_language>

Target:
private Service getCheWorkspaceService() throws IOException { ServiceList services = openShiftClient.services().inNamespace(this.openShiftCheProjectName).list(); Service service = services.getItems().stream() .filter(s -> s.getMetadata().getName().startsWith(CHE_OPENSHIFT_RESOURCES_PREFIX)) .findFirst().orElse(null); if (service == null) { LOG.error("No service with prefix found", CHE_OPENSHIFT_RESOURCES_PREFIX); throw new IOException("No service with prefix " + CHE_OPENSHIFT_RESOURCES_PREFIX +" found"); } return service; }
Source:
<code>public void showPage(Control page) { if (page.isDisposed() || page.getParent() != this) { return; } currentPage = page; page.setVisible(true); layout(true); Control[] children = getChildren(); for (Control element : children) { <START> Control child = element; <END> if (child != page && !child.isDisposed()) { child.setVisible(false); } } }</code><technical_language>remove</technical_language>

Target:
public void showPage(Control page) { if (page.isDisposed() || page.getParent() != this) { return; } currentPage = page; page.setVisible(true); layout(true); for (Control child : getChildren()) { if (child != page && !child.isDisposed()) { child.setVisible(false); } } }
Source:
<code>void initializeLags() { Map<TopicPartition, Long> endOffsets; synchronized (kafkaConsumer) { endOffsets = kafkaConsumer.endOffsets(topicPartitionToSSP.keySet()); } if (endOffsets == null) { <START> throw new SamzaException("Failed to fetch kafka consumer endoffsets for system " + systemName); <END> } endOffsets.forEach((tp, offset) -> { SystemStreamPartition ssp = topicPartitionToSSP.get(tp); long startingOffset = nextOffsets.get(ssp); long initialLag = endOffsets.get(tp) - startingOffset; LOG.info("Initial lag for SSP is (end={}, startOffset={})", ssp, initialLag, endOffsets.get(tp), startingOffset); latestLags.put(ssp, initialLag); sink.setIsAtHighWatermark(ssp, initialLag == 0); }); refreshLagMetrics(); }</code><technical_language>I good idea fail meaningful errors instead of a potential NPE. Although, is this new contract necessary part of this change? 1. Is for kafkaConsmer.endOffsets(...) return null in place? 2. If above, issues NPE is this purely standpoint of defensive programming</technical_language>

Target:
private void initializeLags() { Map<TopicPartition, Long> endOffsets; synchronized (kafkaConsumer) { endOffsets = kafkaConsumer.endOffsets(topicPartitionToSSP.keySet()); } if (endOffsets == null) { throw new SamzaException("Failed to fetch kafka consumer endoffsets for system " + systemName); } endOffsets.forEach((tp, offset) -> { SystemStreamPartition ssp = topicPartitionToSSP.get(tp); long startingOffset = nextOffsets.get(ssp); long initialLag = endOffsets.get(tp) - startingOffset; LOG.info("Initial lag for SSP is (end={}, startOffset={})", ssp, initialLag, endOffsets.get(tp), startingOffset); latestLags.put(ssp, initialLag); sink.setIsAtHighWatermark(ssp, initialLag == 0); }); refreshLagMetrics(); }
Source:
<code>public void givenRedirectWithSmallBodyThenItRaisesNoAlert() { <START> msg.getResponseHeader().setStatusCode(300); <END> msg.getResponseHeader().setHeader("Location", URI); msg.setResponseBody(new byte[getAllowableBodySize()]); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(0)); }</code><technical_language>HttpStatusCodes instead</technical_language>

Target:
public void givenRedirectWithSmallBodyThenItRaisesNoAlert() { msg.getResponseHeader().setStatusCode(HttpStatusCode.MOVED_PERMANENTLY); msg.getResponseHeader().setHeader(HttpHeader.LOCATION, URI); msg.setResponseBody(new byte[ALLOWABLE_BODY_SIZE]); rule.scanHttpResponseReceive(msg, -1, createSource(msg)); assertThat(alertsRaised.size(), is(0)); }
Source:
<code>public StringType inputSource(String input){ String in = input.toLowerCase(); <START> if(in.contains("extinput:btaudio".toLowerCase())){ <END> return new StringType("btaudio"); } if(in.contains("extinput:tv".toLowerCase())){ return new StringType("tv"); } if(in.contains("extinput:hdmi?port=1".toLowerCase())){ return new StringType("hdmi1"); } if(in.contains("extinput:hdmi?port=2".toLowerCase())){ return new StringType("hdmi2"); } if(in.contains("extinput:hdmi?port=3".toLowerCase())){ return new StringType("hdmi3"); } if(in.contains("extinput:line".toLowerCase())){ return new StringType("analog"); } if(in.contains("storage:usb1".toLowerCase())){ return new StringType("usb"); } if(in.contains("dlna:music".toLowerCase())){ return new StringType("network"); } return new StringType(input); }</code><technical_language>Is input undeterministic do "contains"? If not, a switch statement more elegant here. (same for other handlers)</technical_language>

Target:
public StringType inputSource(String input) { String in = input.toLowerCase(); if (in.contains("extinput:btaudio".toLowerCase())) { return new StringType("btaudio"); } if (in.contains("extinput:tv".toLowerCase())) { return new StringType("tv"); } if (in.contains("extinput:hdmi?port=1".toLowerCase())) { return new StringType("hdmi1"); } if (in.contains("extinput:hdmi?port=2".toLowerCase())) { return new StringType("hdmi2"); } if (in.contains("extinput:hdmi?port=3".toLowerCase())) { return new StringType("hdmi3"); } if (in.contains("extinput:line".toLowerCase())) { return new StringType("analog"); } if (in.contains("storage:usb1".toLowerCase())) { return new StringType("usb"); } if (in.contains("dlna:music".toLowerCase())) { return new StringType("network"); } if (in.contains("cast:audio".toLowerCase())) { return new StringType("cast"); } return new StringType(input); }
Source:
<code>public void addLhs(final T object, final Locatable interval) { if (object == null) { throw new IllegalArgumentException("null object"); } if (interval == null) { throw new IllegalArgumentException("null interval"); } final String seqId = interval.getContig(); IntervalTree<Set<T>> tree = this.cache.get(seqId); if (tree == null) { tree = new IntervalTree<>(); this.cache.put(seqId, tree); } final int start = interval.getStart() + this.lhsBuffer; final int end = interval.getEnd() - this.lhsBuffer; final Set<T> newValue = Collections.singleton(object); if (start <= end) { final Set<T> alreadyThere = tree.put(start, end, newValue); if (alreadyThere != null) { <START> if( alreadyThere.size() == 1){ <END> Set<T> mutableSet = new HashSet<>(2); mutableSet.addAll(alreadyThere); mutableSet.add(object); tree.put(start, end, mutableSet); } else { alreadyThere.add(object); tree.put(start, end, alreadyThere); } } } }</code><technical_language>I this implemented IntervalTree class a computeIfPresent method..</technical_language>

Target:
public void addLhs(final T object, final Locatable interval) { if (object == null) { throw new IllegalArgumentException("null object"); } if (interval == null) { throw new IllegalArgumentException("null interval"); } final String seqId = interval.getContig(); IntervalTree<Set<T>> tree = this.cache.get(seqId); if (tree == null) { tree = new IntervalTree<>(); this.cache.put(seqId, tree); } final int start = interval.getStart() + this.lhsBuffer; final int end = interval.getEnd() - this.lhsBuffer; if (start <= end) { tree.merge(start, end, Collections.singleton(object), mergeSetsAccountingForSingletons()); } }
Source:
<code>public TestDescription createTestDescription() { <START> final String name = String.format("%s(%s)", displayName, uniqueId); <END> return new TestDescription(testClass, name, name, annotations.toArray(ANNOTATIONS_TYPE)); }</code><technical_language>I final for local variables in JUnit. extra noise me</technical_language>

Target:
public ImmutableDescription createTestDescription() { final String name = String.format("%s(%s)", displayName, uniqueId); return new TestDescription(testClass, name, name, annotations.toArray(ANNOTATIONS_TYPE)); }
Source:
<code>private boolean validateNoRunningJobs(Guid vdsId) { List<Step> steps = stepDao.getStartedStepsByStepSubjectEntity(new SubjectEntity(VdcObjectType.EXECUTION_HOST, vdsId)); if (!steps.isEmpty()) { <START> getReturnValue().getValidationMessages().add(String.format("$jobs %1$s", steps.stream().map(s -> s.getDescription()).collect(Collectors.joining(System.lineSeparator())))); return failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_HOST_WITH_RUNNING_JOBS); } <END> return true; }</code><technical_language>noticed beforehand, apologies: failValidation a String... parameter for replacements, return failValidation(msg, step.stream().etc...)</technical_language>

Target:
private boolean validateNoRunningJobs(Guid vdsId) { List<Step> steps = stepDao.getStartedStepsByStepSubjectEntity(new SubjectEntity(VdcObjectType.EXECUTION_HOST, vdsId)); if (!steps.isEmpty()) { return failValidation(EngineMessage.VDS_CANNOT_MAINTENANCE_HOST_WITH_RUNNING_JOBS, String.format("$jobs %1$s", steps.stream() .map(s -> s.getDescription()) .collect(Collectors.joining(System.lineSeparator())))); } return true; }
Source:
<code>public Map<EndpointQualifier, NetworkStats> getNetworkStats() { if (unifiedConnectionManager != null) { return emptyMap(); } return connectionManagers.entrySet() .stream() <START> .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().getNetworkStats(), (a, b) -> b)); <END> }</code><technical_language>minor: a merge function instead of Collectors.toMap(keyMapper, valueMapper)? Collisions expected here</technical_language>

Target:
public Map<EndpointQualifier, NetworkStats> getNetworkStats() { if (unifiedConnectionManager != null) { return emptyMap(); } Map<EndpointQualifier, NetworkStats> stats = new HashMap<>(); for (Map.Entry<EndpointQualifier, TcpServerConnectionManager> entry : connectionManagers.entrySet()) { stats.put(entry.getKey(), entry.getValue().getNetworkStats()); } return stats; }
Source:
<code>public void testBug() throws CoreException { boolean <START> interrupted = <END> Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at start of test"); } workspace.run(new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) { ProgressMonitorDialog dialog = new ProgressMonitorDialog(new Shell()); try { dialog.run(true, false, new TransferTestOperation()); } catch (InvocationTargetException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InterruptedException e) { } } }, workspace.getRoot(), IResource.NONE, null); interrupted = Thread.interrupted(); if (interrupted) { fail("Thread was interrupted at end of test"); } }</code><technical_language>Inline variable</technical_language>

Target:
public void testBug() throws CoreException { if (Thread.interrupted()) { fail("Thread was interrupted at start of test"); } workspace.run(new IWorkspaceRunnable() { @Override public void run(IProgressMonitor monitor) { ProgressMonitorDialog dialog = new ProgressMonitorDialog(new Shell()); try { dialog.run(true, false, new TransferTestOperation()); } catch (InvocationTargetException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InterruptedException e) { } } }, workspace.getRoot(), IResource.NONE, null); if (Thread.interrupted()) { fail("Thread was interrupted at end of test"); } }
Source:
<code>protected String getAuthToken() { try { <START> return authServiceClient.login(testUser.getEmail(), testUser.getPassword()); <END> } catch (Exception ex) { throw new RuntimeException( format("Failed to access get token for user '%s'", testUser.getName())); } }</code><technical_language>**testUser.getAuthToken()** here, we</technical_language>

Target:
protected String getAuthToken() { try { return authServiceClient.login(email, password); } catch (Exception ex) { throw new RuntimeException(format("Failed to get access token for user '%s'", email)); } }
Source:
<code>void receiveSeveral() { ImmutableList<OrderServed> eventsToEmit = ImmutableList.of( someOrderServedInTime(), someOrderServedInTime(), someOrderServedLate() ); eventsToEmit.forEach(restaurantContext::receivesEvent); ImmutableList<OrderServed> ordersServed = performanceTracker.ordersServed(); ImmutableList<OrderServedLate> ordersServedLate = performanceTracker.ordersServedLate(); assertThat(ordersServed).hasSize(eventsToEmit.size()); <START> @SuppressWarnings("Guava") <END> long ordersInTime = ordersServed .stream() .filter(not(this::isServedLate)) .count(); assertThat(ordersInTime).isEqualTo(2); assertThat(ordersServedLate).hasSize(1); }</code><technical_language>do JDK API</technical_language>

Target:
void receiveSeveral() { ImmutableList<OrderServed> eventsToEmit = ImmutableList.of( someOrderServedInTime(), someOrderServedInTime(), someOrderServedLate() ); eventsToEmit.forEach(restaurantContext::receivesEvent); ImmutableList<OrderServed> ordersServed = performanceTracker.ordersServed(); ImmutableList<OrderServedLate> ordersServedLate = performanceTracker.ordersServedLate(); assertThat(ordersServed).hasSize(eventsToEmit.size()); long ordersInTime = ordersServed .stream() .filter(orderServed -> !performanceTracker.servedLate(orderServed)) .count(); assertThat(ordersInTime).isEqualTo(2); assertThat(ordersServedLate).hasSize(1); }
Source:
<code>private void refresh() { try { String serviceId = this.config.getDiscovery().getServiceId(); List<String> listOfUrls = new ArrayList<>(); List<ServiceInstance> serviceInstances = this.instanceProvider .getConfigServerInstance(serviceId); <START> for(int i=0;i< serviceInstances.size();i++) { <END> ServiceInstance server = serviceInstances.get(i); String url = getHomePage(server); if (server.getMetadata().containsKey("password")) { String user = server.getMetadata().get("user"); user = user == null ? "user" : user; this.config.setUsername(user); String password = server.getMetadata().get("password"); this.config.setPassword(password); } if (server.getMetadata().containsKey("configPath")) { String path = server.getMetadata().get("configPath"); if (url.endsWith("/") && path.startsWith("/")) { url = url.substring(0, url.length() - 1); } url = url + path; } listOfUrls.add(url); } String[] uri = new String[listOfUrls.size()]; uri = listOfUrls.toArray(uri); this.config.setUri(uri); } catch (Exception ex) { if (config.isFailFast()) { throw ex; } else { logger.warn("Could not locate configserver via discovery", ex); } } }</code><technical_language>spacing formatting</technical_language>

Target:
private void refresh() { try { String serviceId = this.config.getDiscovery().getServiceId(); List<String> listOfUrls = new ArrayList<>(); List<ServiceInstance> serviceInstances = this.instanceProvider .getConfigServerInstances(serviceId); for (int i = 0; i < serviceInstances.size(); i++) { ServiceInstance server = serviceInstances.get(i); String url = getHomePage(server); if (server.getMetadata().containsKey("password")) { String user = server.getMetadata().get("user"); user = user == null ? "user" : user; this.config.setUsername(user); String password = server.getMetadata().get("password"); this.config.setPassword(password); } if (server.getMetadata().containsKey("configPath")) { String path = server.getMetadata().get("configPath"); if (url.endsWith("/") && path.startsWith("/")) { url = url.substring(0, url.length() - 1); } url = url + path; } listOfUrls.add(url); } String[] uri = new String[listOfUrls.size()]; uri = listOfUrls.toArray(uri); this.config.setUri(uri); } catch (Exception ex) { if (config.isFailFast()) { throw ex; } else { logger.warn("Could not locate configserver via discovery", ex); } } }
Source:
<code>public static void initialize() throws Exception { Transport.register(TransportAmazonS3.PROTO_S3); loadBouncyCastle(); if (permitLongTests()) { logInfo("Long running testes are enabled."); } else { logWarn("Long running testes are <START> not enabled."); <END> } if (isTectConfigPresent()) { logInfo("Amazon S3 test configuration is present."); remoteCreate(); } else { logError( "Amazon S3 test configuration is missing, tests will not run."); } }</code><technical_language>disabled</technical_language>

Target:
public static void initialize() throws Exception { Transport.register(TransportAmazonS3.PROTO_S3); loadBouncyCastle(); if (permitLongTests()) { logger.info("Long running tests are enabled."); } else { logger.warn("Long running tests are disabled."); } if (isTestConfigPresent()) { logger.info("Amazon S3 test configuration is present."); remoteCreate(); } else { logger.error( "Amazon S3 test configuration is missing, tests will not run."); } }
Source:
<code>private String tableToString(Map<String, boolean[]> table) { StringBuilder tableStringBuilder = new StringBuilder(); table.forEach((key, value) -> { tableStringBuilder.append('{' + key + "={" + value[0] + ',' <START> + value[1] + "}},"); <END> }); String tableString = tableStringBuilder.toString(); if (!tableString.isEmpty()) { tableString = tableString.substring(0, tableString.length() - 1); } return tableString; }</code><technical_language>in append(...) fit line</technical_language>

Target:
private String tableToString(Map<String, boolean[]> table) { StringBuilder tableStringBuilder = new StringBuilder(); table.forEach((key, value) -> tableStringBuilder.append('{' + key + "={" + value[0] + ',' + value[1] + "}},")); String tableString = tableStringBuilder.toString(); if (!tableString.isEmpty()) { tableString = tableString.substring(0, tableString.length() - 1); } return tableString; }
Source:
<code>public void hideExportProgressBar() { <START> exportProgressBar.setValue(100); <END> exportProgressBar.setIndeterminate(false); exportProgressBar.setVisible(false); }</code><technical_language>setVisible(false)? I setting indeterminate properties effect here..</technical_language>

Target:
public void hideExportProgressBar() { exportProgressBar.setVisible(false); }
Source:
<code>public boolean matches(final Notification notification) { boolean match = false; Object notifier = notification.getNotifier(); EObject value = null; if <START> (notifier instanceof Package) { <END> if (Notification.REMOVE == notification.getEventType()) { if (notification.getOldValue() instanceof EObject) { value = (EObject) notification.getOldValue(); notificationMatch.put(value, new ResourceNotificationMatch((Package) notifier, value)); } } if (Notification.ADD == notification.getEventType()) { if (notification.getNewValue() instanceof EObject) { value = (EObject) notification.getNewValue(); ResourceNotificationMatch preMatch = notificationMatch.get(value); if (null != preMatch) { preMatch.setContainerTarget((Package) notifier); match = preMatch.isMatch(); } } } } else if (notifier instanceof Resource) { ResourceNotificationMatch matchNotification = null; if (Notification.REMOVE == notification.getEventType()) { if (notification.getOldValue() instanceof EObject) { value = (EObject) notification.getOldValue(); EObject rootContainer = EcoreUtil.getRootContainer(value, true); if (rootContainer instanceof Package) { matchNotification = new ResourceNotificationMatch((Resource) notifier, value); matchNotification.setContainerTarget((Package) rootContainer); notificationMatch.put(value, matchNotification); } } } if (Notification.ADD == notification.getEventType()) { if (notification.getNewValue() instanceof EObject) { value = (EObject) notification.getNewValue(); EObject rootContainer = EcoreUtil.getRootContainer(value, true); if (rootContainer instanceof Package) { matchNotification = new ResourceNotificationMatch((Package) rootContainer, value); matchNotification.setContainerTarget((Resource) notifier); notificationMatch.put(value, matchNotification); } } } match = null != matchNotification && matchNotification.isMatch(); } if (null == filterMatch && match) { filterMatch = notificationMatch.get(value); } return match; }</code><technical_language>Packages UML elements refactored ..</technical_language>

Target:
public boolean matches(final Notification notification) { boolean match = false; ResourceChangeMatcher matchNotification = handleNotification(notification); match = null != matchNotification && matchNotification.isMatch(); if (null == filterMatch && match) { filterMatch = matchNotification; } return match; }
Source:
<code>public List<String> generateStatisticsForEachRecipient(String recipientEmail, Map<String, Integer> recipientResponses, FeedbackSessionResultsBundle bundle) { <START> Assumption.assertTrue(hasAssignedWeights); <END> List<String> recipientStats = new ArrayList<>(); DecimalFormat df = new DecimalFormat("0.00"); String recipientName = bundle.getNameForEmail(recipientEmail); String recipientTeam = bundle.getTeamNameForEmail(recipientEmail); double total = 0; double average = 0; int numOfResponsesForThisRecipient = 0; recipientStats.add(recipientTeam); recipientStats.add(recipientName); for (Map.Entry<String, Integer> countPerChoice : recipientResponses.entrySet()) { String choice = countPerChoice.getKey(); int responseCount = countPerChoice.getValue(); double weight = 0; recipientStats.add(Integer.toString(responseCount)); if ("Other".equals(choice)) { weight = mcqOtherWeight; } else { weight = mcqWeights.get(mcqChoices.indexOf(choice)); } total += responseCount * weight; numOfResponsesForThisRecipient += responseCount; } recipientStats.add(df.format(total)); average = numOfResponsesForThisRecipient == 0 ? 0 : total / numOfResponsesForThisRecipient; recipientStats.add(df.format(average)); return recipientStats; }</code><technical_language>add some message Assumption.assertTrue(hasAssignedWeights, "weights enabled calling function");</technical_language>

Target:
public List<String> generateStatisticsForEachRecipient(String recipientEmail, Map<String, Integer> recipientResponses, FeedbackSessionResultsBundle bundle) { Assumption.assertTrue("Weights should be enabled when calling the function", hasAssignedWeights); List<String> recipientStats = new ArrayList<>(); DecimalFormat df = new DecimalFormat("0.00"); String recipientName = bundle.getNameForEmail(recipientEmail); String recipientTeam = bundle.getTeamNameForEmail(recipientEmail); double total = 0; double average = 0; int numOfResponsesForThisRecipient = 0; recipientStats.add(recipientTeam); recipientStats.add(recipientName); for (Map.Entry<String, Integer> countPerChoice : recipientResponses.entrySet()) { String choice = countPerChoice.getKey(); int responseCount = countPerChoice.getValue(); double weight = 0; recipientStats.add(Integer.toString(responseCount)); if ("Other".equals(choice)) { weight = mcqOtherWeight; } else { weight = mcqWeights.get(mcqChoices.indexOf(choice)); } total += responseCount * weight; numOfResponsesForThisRecipient += responseCount; } recipientStats.add(df.format(total)); average = numOfResponsesForThisRecipient == 0 ? 0 : total / numOfResponsesForThisRecipient; recipientStats.add(df.format(average)); return recipientStats; }
Source:
<code>public void registerAttributes(ManagementResourceRegistration registry) { for (AttributeDefinition attr : ATTRIBUTES) { if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) { <START> registry.registerReadWriteAttribute(attr, null, new ReloadRequiredWriteAttributeHandler(ATTRIBUTES)); <END> } } BridgeControlHandler.INSTANCE.registerAttributes(registry); }</code><technical_language>create new ReloadRequiredWriteAttributeHandler(ATTRIBUTES) loop, memory footprint of GC pressure boot</technical_language>

Target:
public void registerAttributes(ManagementResourceRegistration registry) { ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(ATTRIBUTES); for (AttributeDefinition attr : ATTRIBUTES) { if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) { registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler); } } BridgeControlHandler.INSTANCE.registerAttributes(registry); }
Source:
<code>public List<Appointment> getAppointmentsByDate(long date) { DateTime dateTime = new DateTime(date); DateTime startOfDay = dateTime.withTime(0, 0, 0, 0); DateTime endOfDay = dateTime.withTime(23, 59, 59, 999); <START> return appointmentDAO.getAppointmentByDate(startOfDay.getMillis(), endOfDay.getMillis()); <END> }</code><technical_language>I understand, want couple joda time DAO module. well... well, great, allow appointments month, year decade (!) adding service method leaving dao alone</technical_language>

Target:
public List<Appointment> getAppointmentsByDate(long date) { DateTime dateTime = new DateTime(date); DateTime startOfDay = dateTime.withTime(0, 0, 0, 0); DateTime endOfDay = dateTime.withTime(23, 59, 59, 999); return appointmentDAO.getAppointmentsByDate(startOfDay.getMillis(), endOfDay.getMillis()); }
Source:
<code>private UserEntity getUserEntityById(final Long userId) throws EntityRetrievalException { UserEntity user = null; Query query = entityManager.createQuery( "from UserEntity where (NOT deleted = true) " + "AND (user_id = :userid) ", UserEntity.class); query.setParameter("userid", userId); List<UserEntity> result = query.getResultList(); if (result == null || result.size() == 0) { <START> String msg = String.format(messageSource.getMessage(new DefaultMessageSourceResolvable("user.notFound"), <END> LocaleContextHolder.getLocale())); throw new EntityRetrievalException(msg); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate user id in database."); } if (result.size() == 0) { return null; } return result.get(0); }</code><technical_language>notice this before.. double check errorMessageUtil is in this class messageSource.getMessage is anywhere</technical_language>

Target:
private UserEntity getUserEntityById(final Long userId) throws EntityRetrievalException { UserEntity user = null; Query query = entityManager.createQuery( "from UserEntity where (NOT deleted = true) " + "AND (user_id = :userid) ", UserEntity.class); query.setParameter("userid", userId); List<UserEntity> result = query.getResultList(); if (result == null || result.size() == 0) { String msg = errorMessageUtil.getMessage("user.notFound"); throw new EntityRetrievalException(msg); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate user id in database."); } if (result.size() == 0) { return null; } return result.get(0); }
Source:
<code>protected Object getValue(String choice) throws IllegalArgumentException { <START> return Enum.valueOf(this.type, choice); <END> }</code><technical_language>This is fail if user input match enum constant name. A choice populate a Map<String, T> argument creation, String key *lowercased*, simply get keySet for choices, a simple get here</technical_language>

Target:
protected Object getValue(String choice) throws IllegalArgumentException { T value = this.values.get(choice.toLowerCase()); if (value == null) { throw new IllegalArgumentException("No enum constant " + this.type.getCanonicalName() + "." + choice); } return value; }
Source:
<code>private void mockGetAllForImage() <START> { <END> Map<Boolean, VmTemplate> map = new HashMap<Boolean, VmTemplate>(); map.put(true, new VmTemplate()); doReturn(map).when(vmTemplateDao).getAllForImage(any(Guid.class)); }</code><technical_language>singletonMap</technical_language>

Target:
private void mockGetAllForImage() { Map<Boolean, VmTemplate> map = Collections.singletonMap(true, new VmTemplate()); doReturn(map).when(vmTemplateDao).getAllForImage(any(Guid.class)); }
Source:
<code>public DecoratableResourceAdapter(IndexDiffData indexDiffData, IResource resourceToWrap) throws IOException { super(resourceToWrap); this.indexDiffData = indexDiffData; trace = GitTraceLocation.DECORATION.isActive(); long start = 0; if (trace) { GitTraceLocation.getTrace().trace( GitTraceLocation.DECORATION.getLocation(), "Decorate " + resource.getFullPath()); start = System.currentTimeMillis(); } try { mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { repository = null; return; } repository = mapping.getRepository(); if (repository == null) return; <START> if (resource.getType() == IResource.PROJECT) { <END> repositoryName = DecoratableResourceHelper .getRepositoryName(repository); branch = DecoratableResourceHelper.getShortBranch(repository); branchStatus = DecoratableResourceHelper.getBranchStatus(repository); } switch (resource.getType()) { case IResource.FILE: extractResourceProperties(); break; case IResource.PROJECT: tracked = true; case IResource.FOLDER: extractContainerProperties(); break; } } finally { if (trace) GitTraceLocation .getTrace() .trace(GitTraceLocation.DECORATION.getLocation(), "Decoration took " + (System.currentTimeMillis() - start) + " ms"); } }</code><technical_language>I this moved case clause of switch statement extracted a new private method extractProjectProperties</technical_language>

Target:
public DecoratableResourceAdapter(IndexDiffData indexDiffData, IResource resourceToWrap) throws IOException { super(resourceToWrap); this.indexDiffData = indexDiffData; trace = GitTraceLocation.DECORATION.isActive(); long start = 0; if (trace) { GitTraceLocation.getTrace().trace( GitTraceLocation.DECORATION.getLocation(), "Decorate " + resource.getFullPath()); start = System.currentTimeMillis(); } try { mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { repository = null; return; } repository = mapping.getRepository(); if (repository == null) return; switch (resource.getType()) { case IResource.FILE: extractResourceProperties(); break; case IResource.PROJECT: repositoryName = DecoratableResourceHelper .getRepositoryName(repository); branch = DecoratableResourceHelper.getShortBranch(repository); branchStatus = DecoratableResourceHelper.getBranchStatus(repository); tracked = true; case IResource.FOLDER: extractContainerProperties(); break; } } finally { if (trace) GitTraceLocation .getTrace() .trace(GitTraceLocation.DECORATION.getLocation(), "Decoration took " + (System.currentTimeMillis() - start) + " ms"); } }
Source:
<code>@Nullable @Override public <T> T deserialize(@Nullable ClassLoader ldr) throws BinaryObjectException { if (ldr == null) return deserialize(); <START> GridBinaryMarshaller.USE_CACHE.set(Boolean.FALSE); <END> return (T)reader(null, ldr, true).deserialize(); }</code><technical_language>change true in finaly block</technical_language>

Target:
@Nullable @Override public <T> T deserialize(@Nullable ClassLoader ldr) throws BinaryObjectException { if (ldr == null) return deserialize(); GridBinaryMarshaller.USE_CACHE.set(Boolean.FALSE); try { return (T)reader(null, ldr, true).deserialize(); } finally { GridBinaryMarshaller.USE_CACHE.set(Boolean.TRUE); } }
Source:
<code>public void testScopesAreCreated() { parseCode(TEST1); <START> ASTBlock n = acu.findDescendantsOfType(ASTIfStatement.class).get(0) <END> .getFirstDescendantOfType(ASTBlock.class); assertTrue(n.getScope() instanceof LocalScope); }</code><technical_language>This a getFirstDescendantOfType</technical_language>

Target:
public void testScopesAreCreated() { parseCode(TEST1); ASTBlock n = acu.getFirstDescendantOfType(ASTIfStatement.class) .getFirstDescendantOfType(ASTBlock.class); assertTrue(n.getScope() instanceof LocalScope); }
Source:
<code>public List<Node> getMembers() { <START> List<Node> list = new ArrayList<>(); <END> for (Address address : this.addresses) { Node node = this.factory.createNode(address); list.add(node); } return list; }</code><technical_language>ArrayList constructed fixed capacity</technical_language>

Target:
public List<Node> getMembers() { List<Node> list = new ArrayList<>(this.addresses.size()); for (Address address : this.addresses) { Node node = this.factory.createNode(address); list.add(node); } return list; }
Source:
<code>private int loadAndRunTests(Object operations, String testDir) throws Exception { int failedTestCnt = 0; try { Class classToRun = operations.getClass(); Method[] tests = classToRun.getDeclaredMethods(); for (Method test : tests) { String testName = test.getName(); if (testName.endsWith("Test")) { System.out.printf("Running test: %s...", testName); boolean passed = false; <START> try { <END> test.invoke(operations); passed = true; cleanupUfs(testDir); } catch (Exception e) { if (mUfs.getUnderFSType().equals(S3_IDENTIFIER)) { logRelatedS3Operations(test); } System.err.format("Test %s.%s aborted%n%s", test.getClass(), test.getName(), e); } finally { RunTestUtils.printPassInfo(passed); if (!passed) { failedTestCnt++; } } } } } finally { mUfs.deleteDirectory(testDir, DeleteOptions.defaults().setRecursive(true)); mUfs.close(); return failedTestCnt; } }</code><technical_language>remove this</technical_language>

Target:
private int loadAndRunTests(Object operations, String testDir) throws Exception { int failedTestCnt = 0; try { Class classToRun = operations.getClass(); Field[] fields = classToRun.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); } Method[] tests = classToRun.getDeclaredMethods(); for (Method test : tests) { String testName = test.getName(); if (testName.endsWith("Test")) { System.out.printf("Running test: %s...", testName); boolean passed = false; try { test.invoke(operations); passed = true; } catch (Exception e) { if (mUfs.getUnderFSType().equals(S3_IDENTIFIER)) { logRelatedS3Operations(test); } System.err.format("Test %s.%s aborted%n%s", test.getClass(), test.getName(), e); } finally { cleanupUfs(testDir); RunTestUtils.printPassInfo(passed); if (!passed) { failedTestCnt++; } } } } } finally { mUfs.deleteDirectory(testDir, DeleteOptions.defaults().setRecursive(true)); mUfs.close(); return failedTestCnt; } }