auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run() { super.run(); EObject target; DTreeItemContainer lineContainer; if (getTreeItem() != null) { target = getTreeItem().getTarget(); lineContainer = (DTreeItemContainer) getTreeItem().eContainer(); } else { target = tree.getTarget(); lineContainer = tree; } CompoundCommand compoundCommand = new CompoundCommand(getText()); Command cmd = treeCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreationTool()); compoundCommand.append(cmd); getEditingDomain().getCommandStack().execute(compoundCommand); }

Target:
public void run() { super.run(); EObject target; DTreeItemContainer lineContainer; DTreeItem dTreeItem = getTreeItem(); if (dTreeItem != null) { target = dTreeItem.getTarget(); lineContainer = (DTreeItemContainer) dTreeItem.eContainer(); } else { target = tree.getTarget(); lineContainer = tree; } Command cmd = treeCommandFactory.buildCreateLineCommandFromTool(lineContainer, target, getCreationTool()); String label = getText(); cmd = new CommandWrapper(label, label, cmd); getEditingDomain().getCommandStack().execute(cmd); }
Source:
public PoissonEventsArrival(double events, TimeUnit perUnit) { _nanosToNextEventMean = perUnit.toNanos(1) / events; }

Target:
public PoissonEventsArrival(double events, TimeUnit perUnit) { if (events <= 0) { throw new IllegalArgumentException("events must be a positive number"); } _nanosToNextEventMean = perUnit.toNanos(1) / events; }
Source:
protected <C extends FlagAffectedCommand & TopologyAffectedCommand> CompletableFuture<Void> remoteGet(InvocationContext ctx, C command, Object key, boolean isWrite) { CompletableFuture<Void> cf = super.remoteGet(ctx, command, key, isWrite); if (!ctx.isOriginLocal() || !ctx.isInTxScope()) { return cf; } List<Mutation> mutationsOnKey = getMutationsOnKey((TxInvocationContext) ctx, key); if (mutationsOnKey.isEmpty()) { return cf; } return cf.thenRun(() -> { entryFactory.wrapEntryForWriting(ctx, key, false, true); MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(key); EntryView.ReadWriteEntryView readWriteEntryView = EntryViews.readWrite(cacheEntry, null, null); for (Mutation mutation : mutationsOnKey) { mutation.apply(readWriteEntryView); cacheEntry.updatePreviousValue(); } }); }

Target:
protected <C extends FlagAffectedCommand & TopologyAffectedCommand> CompletableFuture<Void> remoteGet(InvocationContext ctx, C command, Object key, boolean isWrite) { CompletableFuture<Void> cf = super.remoteGet(ctx, command, key, isWrite); if (!ctx.isOriginLocal() || !ctx.isInTxScope()) { return cf; } List<Mutation> mutationsOnKey = getMutationsOnKey((TxInvocationContext) ctx, key); if (mutationsOnKey.isEmpty()) { return cf; } return cf.thenRun(() -> { entryFactory.wrapEntryForWriting(ctx, key, false, true); MVCCEntry cacheEntry = (MVCCEntry) ctx.lookupEntry(key); EntryView.ReadWriteEntryView readWriteEntryView = EntryViews.readWrite(cacheEntry, DataConversion.DEFAULT, DataConversion.DEFAULT); for (Mutation mutation : mutationsOnKey) { mutation.apply(readWriteEntryView); cacheEntry.updatePreviousValue(); } }); }
Source:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; this.executionMask = ChannelHandlerMask.mask(handler.getClass()); this.handler = handler; }

Target:
DefaultChannelHandlerContext(DefaultChannelPipeline pipeline, String name, ChannelHandler handler) { this.name = requireNonNull(name, "name"); this.pipeline = pipeline; this.executionMask = mask(handler.getClass()); this.handler = handler; }
Source:
public void start() { this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); startDiscovery(); }

Target:
public void start() { this.eventQueue.add(new DiscoveryServiceEvent(DISCOVER_INIT_TOPOLOGY)); this.executorService.submit(this::run); }
Source:
public static boolean isRecoverableException(final Throwable t) { if( t instanceof FailedRequestException || t instanceof Ds3NoMoreRetriesException || t instanceof IOException ) { return true; } return false; }

Target:
public static boolean isRecoverableException(final Throwable t) { if(t instanceof IOException) { return true; } return false; }
Source:
public void appendRows(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { if (positionCount == 0) { return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < decodedBlocks.length; i++) { blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); } calculateRowSizes(fixedWidthRowSize, variableWidthChannels); int offset = 0; do { int positionsFit = calculateNumberRowsFitInBuffers(variableWidthChannels, fixedWidthRowSize, offset); assert positionsFit > 0; assert positionsFit <= positionCount - offset; for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, positionsFit); blockEncodingBuffers[i].copyValues(); } bufferedRowCount += positionsFit; offset += positionsFit; if (bufferFull) { flush(outputBuffer); bufferFull = false; for (int i = 0; i < blockEncodingBuffers.length; i++) { blockEncodingBuffers[i].resetBuffers(); } } } while (offset < positionCount); }

Target:
public void appendRows(DecodedBlockNode[] decodedBlocks, int fixedWidthRowSize, List<Integer> variableWidthChannels, OutputBuffer outputBuffer) { checkArgument(decodedBlocks.length == channelCount, "Unexpected number of blocks"); if (positionCount == 0) { return; } if (channelCount == 0) { bufferedRowCount += positionCount; return; } initializeBlockEncodingBuffers(decodedBlocks); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setupDecodedBlocksAndPositions(decodedBlocks[i], positions, positionCount); } calculateRowSizes(fixedWidthRowSize, variableWidthChannels); int offset = 0; do { int batchSize = calculateNextBatchSize(fixedWidthRowSize, variableWidthChannels, offset); for (int i = 0; i < channelCount; i++) { blockEncodingBuffers[i].setNextBatch(offset, batchSize); blockEncodingBuffers[i].copyValues(); } bufferedRowCount += batchSize; offset += batchSize; if (bufferFull) { flush(outputBuffer); bufferFull = false; } } while (offset < positionCount); }
Source:
public <T> int readFieldNumber(Schema<T> schema) throws IOException { if (offset == limit) { lastTag = 0; return 0; } final int tag; if (currentPacked()) { if (packed_limit < offset) throw ProtobufException.misreportedSize(); return lastTag >>> TAG_TYPE_BITS; } else { tag = readRawVarint32(); packed_limit = 0; } final int fieldNumber = tag >>> TAG_TYPE_BITS; if (fieldNumber == 0) { if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } throw ProtobufException.invalidTag(); } if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } lastTag = tag; return fieldNumber; }

Target:
public <T> int readFieldNumber(Schema<T> schema) throws IOException { if (offset == limit) { lastTag = 0; return 0; } if (isCurrentFieldPacked()) { if (packedLimit < offset) throw ProtobufException.misreportedSize(); return lastTag >>> TAG_TYPE_BITS; } packedLimit = 0; final int tag = readRawVarint32(); final int fieldNumber = tag >>> TAG_TYPE_BITS; if (fieldNumber == 0) { if (decodeNestedMessageAsGroup && WIRETYPE_TAIL_DELIMITER == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } throw ProtobufException.invalidTag(); } if (decodeNestedMessageAsGroup && WIRETYPE_END_GROUP == (tag & TAG_TYPE_MASK)) { lastTag = 0; return 0; } lastTag = tag; return fieldNumber; }
Source:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); final int[] RECENT_NEW_YORK_TEMPS = { 46, 45, 50, 46, 45, 27, 30, 48, 55, 54, 45, 41, 45, 43, 46 }; histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }

Target:
public Histogram getTemperatures() { Metadata metadata = new Metadata("temperatures", MetricType.HISTOGRAM, "degrees F"); metadata.setDescription("A histogram of recent New York temperatures."); histogram = registry.histogram(metadata); for(int temp : RECENT_NEW_YORK_TEMPS) { histogram.update(temp); } return histogram; }
Source:
void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.vaultUrl = (tokens.length >= 1 ? tokens[1] : null); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } }

Target:
void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.vaultUrl = (tokens.length >= 2 ? tokens[1] : null); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalArgumentException("The Azure Key Vault endpoint url is malformed.", e)); } } }
Source:
private void internalClientProviderRemoved(Class<? extends IInternalClientProvider<?, ?>> clazz) { Set<IInternalClientProvider<?, ?>> internalClientProvidersToBeRemoved = new HashSet<IInternalClientProvider<?, ?>>(); for (IInternalClientProvider<?, ?> internalClientProvider : internalClientProviders) { if (internalClientProvider.getClass().isAssignableFrom(clazz)) { internalClientProvidersToBeRemoved.add(internalClientProvider); } } internalClientProviders.remove(internalClientProvidersToBeRemoved); }

Target:
private void internalClientProviderRemoved(Class<? extends IInternalClientProvider<?, ?>> clazz) { internalClientProviders.remove(clazz); }
Source:
public void stop() { LOGGER.debug("Shutting down PooledExecutionService"); running = false; scheduledExecutor.shutdownNow(); for (Iterator<Entry<String, ThreadPoolExecutor>> it = pools.entrySet().iterator(); it.hasNext(); ) { Entry<String, ThreadPoolExecutor> e = it.next(); try { destroyPool(e.getKey(), e.getValue()); } finally { it.remove(); } } try { scheduledExecutor.awaitTermination(30, SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }

Target:
public void stop() { LOGGER.debug("Shutting down PooledExecutionService"); running = false; scheduledExecutor.shutdownNow(); for (Iterator<Entry<String, ThreadPoolExecutor>> it = pools.entrySet().iterator(); it.hasNext(); ) { Entry<String, ThreadPoolExecutor> e = it.next(); try { destroyPool(e.getKey(), e.getValue()); } finally { it.remove(); } } try { if(!scheduledExecutor.awaitTermination(30, SECONDS)) { LOGGER.warn("Timeout while waiting on scheduler to finish"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
Source:
public void testVersionMergeReplaceStrategy() { ContentMerger contentMerger = new ContentMerger(MergeStrategy.REPLACE, MergeStrategy.KEEP); Item current = new Item(); Item extracted = new Item(); Version version1 = new Version(); version1.setCanonicalUri("<LINK_1>"); current.setVersions(ImmutableSet.of(version1)); Restriction restriction = new Restriction(); restriction.setRestricted(true); Version version2 = new Version(); version2.setCanonicalUri("<LINK_0>"); version2.setRestriction(restriction); extracted.setVersions(ImmutableSet.of(version2)); Item merged = contentMerger.merge(current, extracted); Version mergetVersion = Iterables.getOnlyElement(merged.getVersions()); assertEquals("<LINK_0>", mergetVersion.getCanonicalUri()); assertTrue(mergetVersion.getRestriction().isRestricted()); }

Target:
public void testVersionMergeReplaceStrategy() { ContentMerger contentMerger = new ContentMerger(MergeStrategy.REPLACE, MergeStrategy.KEEP); Item current = new Item(); Item extracted = new Item(); Version version1 = new Version(); version1.setCanonicalUri("<LINK_1>"); current.setVersions(ImmutableSet.of(version1)); Restriction restriction = new Restriction(); restriction.setRestricted(true); Version version2 = new Version(); version2.setCanonicalUri("<LINK_0>"); version2.setRestriction(restriction); extracted.setVersions(ImmutableSet.of(version2)); Item merged = contentMerger.merge(current, extracted); Version mergedVersion = Iterables.getOnlyElement(merged.getVersions()); assertEquals("<LINK_0>", mergedVersion.getCanonicalUri()); assertTrue(mergedVersion.getRestriction().isRestricted()); }
Source:
public void perform(@Observes PostStartup event) { boolean isDependencies = event.getAddon().getId().toString().contains("org.jboss.windup.ui:windup-ui"); if(isDependencies) { Furnace furnace = FurnaceHolder.getFurnace(); Imported<DependencyResolver> exportedTypes = furnace.getAddonRegistry().getServices(DependencyResolver.class); if(!exportedTypes.isUnsatisfied() && rulesetNeedUpdate(exportedTypes.get())) { System.out.println(""); System.out.println("Your ruleset is obsolete. Consider running windup-update-ruleset or windup-update-distribution command. Press ENTER to continue."); System.out.println(""); } } }

Target:
public void perform(@Observes PostStartup event) { boolean isDependencies = event.getAddon().getId().toString().contains("org.jboss.windup.ui:windup-ui"); if (isDependencies) { Imported<DependencyResolver> exportedTypes = furnace.getAddonRegistry().getServices(DependencyResolver.class); if (!exportedTypes.isUnsatisfied() && rulesetNeedUpdate(exportedTypes.get())) { System.out.println(""); System.out.println("Your ruleset is obsolete. Consider running windup-update-ruleset or windup-update-distribution command. Press ENTER to continue."); System.out.println(""); } } }
Source:
protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create() .ofTypes( "org.junit.Assert", "org.junit.jupiter.api.Assertions", "junit.framework.Assert", "junit.framework.TestCase") .name(name -> name.startsWith(ASSERT)) .withAnyParameters() .build(), MethodMatchers.create() .ofTypes("org.fest.assertions.Assertions") .names(ASSERT_THAT) .withAnyParameters() .build(), MethodMatchers.create() .ofSubTypes("org.fest.assertions.GenericAssert") .name(name -> name.startsWith(IS)) .withAnyParameters() .build() ); }

Target:
protected MethodMatchers getMethodInvocationMatchers() { return MethodMatchers.or( MethodMatchers.create() .ofTypes( "org.junit.Assert", "org.junit.jupiter.api.Assertions", "junit.framework.Assert", "junit.framework.TestCase") .name(name -> name.startsWith(ASSERT)) .withAnyParameters() .build(), MethodMatchers.create() .ofSubTypes("org.fest.assertions.GenericAssert") .name(name -> name.startsWith(IS)) .withAnyParameters() .build() ); }
Source:
private TypeSpec(Builder builder) { checkArgument(builder.name != null ^ builder.anonymousTypeArguments != null, "types must have either a name or anonymous type arguments"); boolean isInterface = builder.type == Type.INTERFACE; boolean typeIsAbstract = builder.modifiers.contains(Modifier.ABSTRACT) || isInterface; for (MethodSpec methodSpec : builder.methodSpecs) { checkArgument(typeIsAbstract || !methodSpec.hasModifier(Modifier.ABSTRACT), "non-abstract type %s cannot declare abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.ABSTRACT), "interface %s cannot declare non-abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.PUBLIC), "interface %s cannot declare non-public method %s", builder.name, methodSpec.name); } this.annotations = ImmutableList.copyOf(builder.annotations); this.modifiers = ImmutableSet.copyOf(builder.modifiers); this.type = checkNotNull(builder.type); this.name = builder.name; this.supertype = builder.supertype; this.anonymousTypeArguments = builder.anonymousTypeArguments; this.fieldSpecs = ImmutableList.copyOf(builder.fieldSpecs); this.methodSpecs = ImmutableList.copyOf(builder.methodSpecs); }

Target:
private TypeSpec(Builder builder) { checkArgument(builder.name != null ^ builder.anonymousTypeArguments != null, "types must have either a name or anonymous type arguments"); boolean isInterface = builder.type == Type.INTERFACE; boolean typeIsAbstract = builder.modifiers.contains(Modifier.ABSTRACT) || isInterface; for (MethodSpec methodSpec : builder.methodSpecs) { checkArgument(typeIsAbstract || !methodSpec.hasModifier(Modifier.ABSTRACT), "non-abstract type %s cannot declare abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.ABSTRACT), "interface %s cannot declare non-abstract method %s", builder.name, methodSpec.name); checkArgument(!isInterface || methodSpec.hasModifier(Modifier.PUBLIC), "interface %s cannot declare non-public method %s", builder.name, methodSpec.name); } for (FieldSpec fieldSpec : builder.fieldSpecs) { if (isInterface) { checkArgument(fieldSpec.hasModifier(Modifier.PUBLIC) && fieldSpec.hasModifier(Modifier.STATIC) && fieldSpec.hasModifier(Modifier.FINAL), "interface %s field %s must be public static final", builder.name, fieldSpec.name); } } this.annotations = ImmutableList.copyOf(builder.annotations); this.modifiers = ImmutableSet.copyOf(builder.modifiers); this.type = checkNotNull(builder.type); this.name = builder.name; this.supertype = builder.supertype; this.anonymousTypeArguments = builder.anonymousTypeArguments; this.fieldSpecs = ImmutableList.copyOf(builder.fieldSpecs); this.methodSpecs = ImmutableList.copyOf(builder.methodSpecs); }
Source:
public void testGetNoMappingExists() { ServerStore store = newStore(); Chain chain = store.get(1); assertThat(chain.isEmpty(), is(true)); }

Target:
public void testGetNoMappingExists() { ServerStore store = newStore(); Chain chain = store.get(1); assertThat(chain.isEmpty(), is(true)); assertThat(chain.iterator().hasNext(), is(false)); }
Source:
public void onCatch(Throwable caught) { if (Utils.throwableContainsSpecificType(caught, SSLException.class) && WikipediaApp.getInstance().incSslFailCount() < 2) { WikipediaApp.getInstance().setSslFallback(true); NetworkUtils.toastFail(); cancel(); return; } throw new RuntimeException(caught); }

Target:
public void onCatch(Throwable caught) { }
Source:
private Container decorateMainContainer(Container container) { VolumeMount[] volumeMounts = kubernetesComponentConf .getSecretNamesToMountPaths() .entrySet() .stream() .map(secretNameToPath -> new VolumeMountBuilder() .withName(secretVolumeName(secretNameToPath.getKey())) .withMountPath(secretNameToPath.getValue()) .build() ).toArray(VolumeMount[]::new); return new ContainerBuilder(container) .addToVolumeMounts(volumeMounts) .build(); }

Target:
private Container decorateMainContainer(Container container) { final VolumeMount[] volumeMounts = kubernetesComponentConf.getSecretNamesToMountPaths().entrySet().stream() .map(secretNameToPath -> new VolumeMountBuilder() .withName(secretVolumeName(secretNameToPath.getKey())) .withMountPath(secretNameToPath.getValue()) .build() ) .toArray(VolumeMount[]::new); return new ContainerBuilder(container) .addToVolumeMounts(volumeMounts) .build(); }
Source:
public FileHandler getFileHandler(ConnectionConfiguration connectionConfig) throws IOException { FileHandler handler = null; boolean isLocal = isLocal(connectionConfig.getHostname()); if (isLocal) { handler = new LocalFileHandler(); } else { handler = new RemoteFileHandler(); ((RemoteFileHandler) handler).setConnectionConfiguration(connectionConfig); } return handler; }

Target:
public FileHandler getFileHandler(ConnectionConfiguration connectionConfig) throws IOException { FileHandler handler = null; boolean isLocal = isLocal(connectionConfig.getAuthorization().getHostname()); if (isLocal) { handler = new LocalFileHandler(); } else { RemoteFileHandler remoteHandler = new RemoteFileHandler(); remoteHandler.setConnectionConfiguration(connectionConfig); handler = remoteHandler; } return handler; }
Source:
public void updateAuthenticationItems(AuthenticationItems items) throws IOException { MergePropertiesContext mergePropertiesContext = authenticationProvidersRegistry.mergeProperties(); for (AuthenticationItem item : items.getAuthenticationItemList()) { Map<String, Object> properties = authenticationProvidersRegistry.getAuthenticationProperties(item.getName()); properties.put("order", item.getOrder()); properties.put(Properties.ENABLED, Boolean.TRUE.equals(item.getEnabled())); mergePropertiesContext = mergePropertiesContext.merge(item.getName(), properties); } boolean result = mergePropertiesContext.apply(); if (!result) { return; } reloadAuthenticationItems(); }

Target:
public void updateAuthenticationItems(AuthenticationItems items) throws IOException { MergePropertiesContext mergePropertiesContext = authenticationProvidersRegistry.mergeProperties(); for (AuthenticationItem item : items.getAuthenticationItemList()) { Map<String, Object> properties = authenticationProvidersRegistry.getAuthenticationProperties(item.getName()); properties.put("order", item.getOrder()); properties.put("enabled", Boolean.TRUE.equals(item.getEnabled())); mergePropertiesContext = mergePropertiesContext.merge(item.getName(), properties); } boolean result = mergePropertiesContext.apply(); if (!result) { return; } reloadAuthenticationItems(); }
Source:
private ReflectionUtil ()

Target:
private ReflectionUtil() { throw new UnsupportedOperationException("no instantiation"); }
Source:
private void tryInitialize() { TableMetadata scrubTableMeta = TableMetadata.internal() .rowMetadata(NameMetadataDescription.create("row", ValueType.BLOB)) .columns(new ColumnMetadataDescription(new DynamicColumnDescription( NameMetadataDescription.create( ImmutableList.of( NameComponentDescription.of("table", ValueType.VAR_STRING), NameComponentDescription.of("col", ValueType.BLOB))), ColumnValueDescription.forType(ValueType.VAR_LONG)))) .build(); keyValueService.createTable(AtlasDbConstants.SCRUB_TABLE, scrubTableMeta.persistToBytes()); }

Target:
private void tryInitialize() { TableMetadata scrubTableMeta = TableMetadata.internal() .singleRowComponent("row", ValueType.BLOB) .dynamicColumns(ImmutableList.of( NameComponentDescription.of("table", ValueType.VAR_STRING), NameComponentDescription.of("col", ValueType.BLOB)), ValueType.VAR_LONG) .build(); keyValueService.createTable(AtlasDbConstants.SCRUB_TABLE, scrubTableMeta.persistToBytes()); }
Source:
public void listNamespaces() { try { System.out.println("Listing all default namespaces..."); String nss = client.listNamespaces(storename, true); Assert.assertNotNull(nss); for (String ns : nss) { System.out.println("Namespace (global): " + ns); listNamespaceKeys(storename, ns, true); client.fetchAllNSKeys(storename,ns,true); } nss = client.listNamespaces(storename, false); Assert.assertNotNull(nss); for (String ns : nss) { System.out.println("Namespace (user): " + ns); listNamespaceKeys(storename, ns, false); client.fetchAllNSKeys(storename, ns,false); } } catch (Exception e) { Assert.fail(e.getLocalizedMessage()); } catch (ArrayOfEspExceptionWrapper e) { e.toString(); Assert.fail(); } }

Target:
public void listNamespaces() { try { System.out.println("Listing all default namespaces..."); String nss = client.listNamespaces(storename, true); Assert.assertNotNull(nss); for (String ns : nss) { System.out.println("Namespace (global): " + ns); listNamespaceKeys(storename, ns, true); client.fetchAllNSKeys(storename,ns,true); } nss = client.listNamespaces(storename, false); Assert.assertNotNull(nss); for (String ns : nss) { System.out.println("Namespace (user): " + ns); listNamespaceKeys(storename, ns, false); client.fetchAllNSKeys(storename, ns,false); } } catch (Exception e) { Assert.fail(e.getLocalizedMessage()); } catch (ArrayOfEspExceptionWrapper e) { Assert.fail(e.toString()); } }
Source:
public static boolean hasContentType(IFile resource, String contentTypeId) { IContentTypeManager ctManager = Platform.getContentTypeManager(); IContentType expected = ctManager.getContentType(contentTypeId); if (expected == null) { return false; } InputStream resourceContent = null; IContentType[] contentTypes = null; try { resourceContent = resource.getContents(); contentTypes = ctManager.findContentTypesFor(resourceContent, resource.getName()); } catch (CoreException e) { ctManager.findContentTypesFor(resource.getName()); } catch (IOException e) { ctManager.findContentTypesFor(resource.getName()); } finally { if (resourceContent != null) { try { resourceContent.close(); } catch (IOException e) { } } } boolean hasContentType = false; if (contentTypes != null) { for (int i = 0; i < contentTypes.length && !hasContentType; i++) { if (contentTypes[i].isKindOf(expected)) { hasContentType = true; } } } return hasContentType; }

Target:
public static boolean hasContentType(IFile resource, String contentTypeId) { IContentTypeManager ctManager = Platform.getContentTypeManager(); IContentType expected = ctManager.getContentType(contentTypeId); if (expected == null) { return false; } final IContentType[] contentTypes = getContentTypes(resource); boolean hasContentType = false; for (int i = 0; i < contentTypes.length && !hasContentType; i++) { if (contentTypes[i].isKindOf(expected)) { hasContentType = true; } } return hasContentType; }
Source:
public void reportStageProgress(String stageName, String metricName, long count) throws SemanticException { if (isEnabled) { Progress progress = replicationMetric.getProgress(); Stage stage = progress.getStageByName(stageName); Metric metric = stage.getMetricByName(metricName); metric.setCurrentCount(metric.getCurrentCount() + count); if (metric.getCurrentCount() > metric.getTotalCount()) { metric.setTotalCount(metric.getCurrentCount()); } stage.addMetric(metric); progress.addStage(stage); replicationMetric.setProgress(progress); metricCollector.addMetric(replicationMetric); } }

Target:
public void reportStageProgress(String stageName, String metricName, long count) throws SemanticException { if (isEnabled) { Progress progress = replicationMetric.getProgress(); Stage stage = progress.getStageByName(stageName); Metric metric = stage.getMetricByName(metricName); metric.setCurrentCount(metric.getCurrentCount() + count); if (metric.getCurrentCount() > metric.getTotalCount()) { metric.setTotalCount(metric.getCurrentCount()); } stage.addMetric(metric); replicationMetric.setProgress(progress); metricCollector.addMetric(replicationMetric); } }
Source:
public int setTabIndexes(int nextTabIndex) { certificateAuthority.setTabIndex(++nextTabIndex); prometheusUrl.setTabIndex(++nextTabIndex); prometheusCertificateAuthority.setTabIndex(++nextTabIndex); return nextTabIndex; }

Target:
public int setTabIndexes(int nextTabIndex) { certificateAuthority.setTabIndex(nextTabIndex++); prometheusUrl.setTabIndex(nextTabIndex++); prometheusCertificateAuthority.setTabIndex(nextTabIndex++); return nextTabIndex; }
Source:
public static void closeInputStream(InputStream inputStream) { if (inputStream == null) return; try { inputStream.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
public static void closeInputStream(InputStream inputStream) { try { inputStream.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public void shutdown_should_deregister_mbean_when_enabled() throws Exception { options.setJmx(true); Agent agent = createAgent(); agent.startup(); agent.shutdown(); ObjectName objectName = new ObjectName("org.jacoco:type=Runtime"); ManagementFactory.getPlatformMBeanServer().getMBeanInfo(objectName); }

Target:
public void shutdown_should_deregister_mbean_when_enabled() throws Exception { options.setJmx(true); Agent agent = createAgent(); agent.startup(); agent.shutdown(); ObjectName objectName = new ObjectName("org.jacoco:type=Runtime"); try { ManagementFactory.getPlatformMBeanServer().getMBeanInfo(objectName); fail("InstanceNotFoundException expected"); } catch (InstanceNotFoundException e) { } }
Source:
private GlusterBrickEntity getBrick(List<GlusterBrickEntity> bricksList, String qualifiedBrickName) { String[] pathElements = qualifiedBrickName.split(StorageConstants.GLUSTER_VOL_SEPARATOR); String hostName = pathElements[0]; String hostAddress; try { hostAddress = InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return null; } for (GlusterBrickEntity brick : bricksList) { VDS vds = getVdsDao().get(brick.getServerId()); for (VdsNetworkInterface vdsNi : getInterfaceDao().getAllInterfacesForVds(vds.getId())) { if (vdsNi.getIpv4Address().equals(hostAddress) || vdsNi.getIpv6Address().equals(hostAddress)) { return brick; } } } return null; }

Target:
private GlusterBrickEntity getBrick(List<GlusterBrickEntity> bricksList, String qualifiedBrickName) { GlusterBrickEntity brick = GlusterCoreUtil.getBrickByQualifiedName(bricksList, qualifiedBrickName); if (brick == null) { String[] pathElements = qualifiedBrickName.split(StorageConstants.GLUSTER_VOL_SEPARATOR); String hostName = pathElements[0]; String hostAddress; try { hostAddress = InetAddress.getByName(hostName).getHostAddress(); } catch (UnknownHostException e) { return null; } qualifiedBrickName = hostAddress + StorageConstants.GLUSTER_VOL_SEPARATOR + pathElements[1]; return GlusterCoreUtil.getBrickByQualifiedName(bricksList, qualifiedBrickName); } return brick; }
Source:
private Change.Id insertPatchSet(Repository git, RevWalk revWalk, Change change, PatchSet.Id patchSetId, RevCommit cherryPickCommit, RefControl refControl) throws InvalidChangeOperationException, IOException, OrmException, NoSuchChangeException { final PatchSetInserter inserter = patchSetInserterFactory .create(git, revWalk, refControl, currentUser, change, cherryPickCommit); final PatchSet.Id newPatchSetId = inserter.getPatchSetId(); ChangeMessage cmsg = new ChangeMessage(new ChangeMessage.Key(patchSetId.getParentKey(), ChangeUtil.messageUUID(db)), currentUser.getAccountId(), newPatchSetId); cmsg.setMessage("Uploaded patch set " + newPatchSetId.get() + "."); inserter .setMessage(cmsg) .insert(); return change.getId(); }

Target:
private Change.Id insertPatchSet(Repository git, RevWalk revWalk, Change change, PatchSet.Id patchSetId, RevCommit cherryPickCommit, RefControl refControl) throws InvalidChangeOperationException, IOException, OrmException, NoSuchChangeException { final PatchSetInserter inserter = patchSetInserterFactory .create(git, revWalk, refControl, currentUser, change, cherryPickCommit); final PatchSet.Id newPatchSetId = inserter.getPatchSetId(); inserter .setMessage("Uploaded patch set " + newPatchSetId.get() + ".") .insert(); return change.getId(); }
Source:
public void onSaveInstanceState(Bundle outState) { Log_OC.d(SAML_DIALOG_TAG, "onSaveInstanceState being CALLED"); super.onSaveInstanceState(outState); outState.putString(ARG_INITIAL_URL, mInitialUrl); outState.putString(ARG_TARGET_URL, mTargetUrl); Bundle webviewState = new Bundle(); ((WebView) getDialog().findViewById(R.id.sso_webview)).saveState(webviewState); outState.putBundle(KEY_WEBVIEW_STATE, webviewState); }

Target:
public void onSaveInstanceState(Bundle outState) { Log_OC.d(SAML_DIALOG_TAG, "onSaveInstanceState being CALLED"); super.onSaveInstanceState(outState); outState.putString(ARG_INITIAL_URL, mInitialUrl); outState.putString(ARG_TARGET_URL, mTargetUrl); Bundle webviewState = new Bundle(); mSsoWebView.saveState(webviewState); outState.putBundle(KEY_WEBVIEW_STATE, webviewState); }
Source:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = null; assertNull(instance.getUserPage()); }

Target:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = "<LINK_0>"; assertNull(instance.getUserPage()); instance.setUserPage(page); assertEquals(page, instance.getUserPage()); }
Source:
private static Directive parseLine(String line, int lineNumber) { int equalSignIndex = 0; boolean insideString = false; boolean afterBackSlash = false; int i = 0; for (; i < line.length(); i++) { char c = line.charAt(i); if (c == '=') { equalSignIndex = i; } if (c == ';' && !insideString) { break; } if (c == '"' && !afterBackSlash) { insideString = !insideString; } afterBackSlash = c == '\\'; } String name = line.substring(0, equalSignIndex); if (name.isEmpty()) { return null; } String value = line.substring(equalSignIndex + 1, i); return new DirectiveImpl(lineNumber, name, value); }

Target:
private static Directive parseLine(String line, int lineNumber) { int equalSignIndex = -1; boolean insideString = false; boolean afterBackSlash = false; int currentCharIndex = 0; while (currentCharIndex < line.length()) { char currentChar = line.charAt(currentCharIndex); if (!insideString) { if (currentChar == '=') { checkState(equalSignIndex < 0, lineNumber, line); equalSignIndex = currentCharIndex; } if (currentChar == ';') { break; } } if (currentChar == '"' && !afterBackSlash) { insideString = !insideString; } afterBackSlash = currentChar == '\\'; currentCharIndex++; } return createDirective(line, lineNumber, equalSignIndex, currentCharIndex); }
Source:
public static String getWarningMessages(String filename){ String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }

Target:
public static String getWarningMessages(String filename) { String warningMessage = ""; if (getErrorMessage(filename).length() == 0 && filename.trim().length() > 0) { if (!filename.matches("[A-Za-z][A-Za-z0-9_]*")) { String errorMessage = MESSAGES.whitespaceProjectNameError(); filename = filename.trim().replaceAll("( )+", " ").replace(" ","_"); warningMessage = errorMessage + ". \n '" + filename + "' will be used if continued."; } } return warningMessage; }
Source:
protected void setUp() throws Exception { refreshPolicy(Policy.getPolicy()); System.setSecurityManager(new SecurityManager()); Appender appender = new WriterAppender( new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), errorOutputWriter); org.apache.log4j.Logger.getRootLogger().addAppender(appender); super.setUp(); }

Target:
public void setUp() throws Exception { refreshPolicy(Policy.getPolicy()); System.setSecurityManager(new SecurityManager()); appender = new WriterAppender( new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN), errorOutputWriter); org.apache.log4j.Logger.getRootLogger().addAppender(appender); super.setUp(); }
Source:
public ArchiveCommand setTree(ObjectId tree) throws IOException { final RevWalk rw = new RevWalk(repo); walk.reset(rw.parseTree(tree)); return this; }

Target:
public ArchiveCommand setTree(ObjectId tree) throws IOException { final RevWalk rw = new RevWalk(repo); try { walk.reset(rw.parseTree(tree)); } finally { rw.release(); } return this; }
Source:
public static void addToVisitedProcessors(String item) { visitedProcessors.add(item); }

Target:
public static synchronized void addToVisitedProcessors(String item) { visitedProcessors.add(item); }
Source:
public IntermediateResultPartitionID() { this.partitionNum = -1; this.intermediateDataSetID = new IntermediateDataSetID(new AbstractID()); }

Target:
public IntermediateResultPartitionID() { this.partitionNum = -1; this.intermediateDataSetID = new IntermediateDataSetID(); }
Source:
private Double interpretOperatorCompare(Object left, Object right) { try { Double tempLeft = Double.valueOf(String.valueOf(left)); Double tempRight = Double.valueOf(String.valueOf(right)); int compareResult = getCompareResult(tempLeft, tempRight); if (compareResult < 0) { return 1d; } else if (compareResult > 0) { return 2d; } return 0d; } catch (NumberFormatException numberFormatException) { int compareResult = String.valueOf(left).toLowerCase().compareTo(String.valueOf(right).toLowerCase()); if (compareResult < 0) { return 1d; } else if (compareResult >0){ return 2d; } return 0d; } }

Target:
private int interpretOperatorCompare(Object left, Object right) { try { if(Math.abs(Double.valueOf(String.valueOf(left))) == 0 && Math.abs(Double.valueOf(String.valueOf(right))) == 0) return 0; return (Double.valueOf(String.valueOf(left))).compareTo(Double.valueOf(String.valueOf(right))); } catch (NumberFormatException numberFormatException) { return String.valueOf(left).toLowerCase().compareTo(String.valueOf(right).toLowerCase()); } }
Source:
public static TLSSocketChannel create( ByteChannel channel, Logger logger, SSLEngine sslEngine ) throws IOException { TLSSocketChannel tlsChannel = new TLSSocketChannel( channel, logger, sslEngine ); try { tlsChannel.runHandshake(); } catch ( SSLHandshakeException e ) { throw new UnauthorizedException( "Failed to establish secured connection with the server: " + e.getMessage(), e ); } return tlsChannel; }

Target:
public static TLSSocketChannel create( ByteChannel channel, Logger logger, SSLEngine sslEngine ) throws IOException { TLSSocketChannel tlsChannel = new TLSSocketChannel( channel, logger, sslEngine ); try { tlsChannel.runHandshake(); } catch ( SSLHandshakeException e ) { throw new SecurityException( "Failed to establish secured connection with the server: " + e.getMessage(), e ); } return tlsChannel; }
Source:
private void refreshExecutors() { synchronized (activeExecutors) { ExecutorService taskExecutors = Executors.newFixedThreadPool(activeExecutors.size()); for (final Executor executor : activeExecutors) { taskExecutors.execute(new Runnable() { @Override public void run() { try { String jsonResponse = callExecutorForJsonString(executor.getHost(), executor.getPort(), "/serverstastics", null); executor.setExecutorInfo(ExecutorInfo .fromJSONString(jsonResponse)); } catch (Exception e) { logger.error("Failed to update ExecutorInfo executorId :" + executor, e); } } }); } taskExecutors.shutdown(); try { taskExecutors.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { logger.error("Timed out while waiting for executorInfo refresh", e); } } }

Target:
private void refreshExecutors() { synchronized (activeExecutors) { List<Pair<Executor, Future<String>>> futures = new ArrayList<Pair<Executor, Future<String>>>(); for (final Executor executor : activeExecutors) { Future<String> fetchExecutionInfo = executorInforRefresherService.submit(new Callable<String>() { @Override public String call() throws Exception { return callExecutorForJsonString(executor.getHost(), executor.getPort(), "/serverstastics", null); } }); futures.add(new Pair<Executor, Future<String>>(executor, fetchExecutionInfo)); } boolean wasSuccess = true; for (Pair<Executor, Future<String>> refreshPair : futures) { Executor executor = refreshPair.getFirst(); try { String jsonString = refreshPair.getSecond().get(5, TimeUnit.SECONDS); executor.setExecutorInfo(ExecutorInfo.fromJSONString(jsonString)); logger.info("Successfully refreshed ExecutorInfo for executor: " + executor); } catch (TimeoutException e) { wasSuccess = false; logger.error("Timed out while waiting for ExecutorInfo refresh" + executor, e); } catch (Exception e) { wasSuccess = false; logger.error("Failed to update ExecutorInfo for executor : " + executor, e); } } if (wasSuccess) { lastSuccessfulExecutorInfoRefresh = System.currentTimeMillis(); } } }
Source:
public void unhandledTypeMismatchExceptionCallbackSeverity() throws IllegalAccessException, NoSuchFieldException { Report report; Callback callback = new Callback() { @Override public void beforeNotify(Report report) { report.setSeverity(Severity.WARNING); } }; try { bugsnag.addCallback(callback); callUnhandledTypeMismatchExceptionEndpoint(); report = verifyAndGetReport(delivery); } finally { Field callbacksField = Configuration.class.getDeclaredField("callbacks"); callbacksField.setAccessible(true); @SuppressWarnings(value = "unchecked") Collection<Callback> callbacks = (Collection<Callback>) callbacksField.get(bugsnag.getConfig()); callbacks.remove(callback); } assertTrue(report.getUnhandled()); assertEquals("warning", report.getSeverity()); assertEquals("userCallbackSetSeverity", report.getSeverityReason().getType()); }

Target:
public void unhandledTypeMismatchExceptionCallbackSeverity() throws IllegalAccessException, NoSuchFieldException { Report report; Callback callback = new Callback() { @Override public void beforeNotify(Report report) { report.setSeverity(Severity.WARNING); } }; try { bugsnag.addCallback(callback); callUnhandledTypeMismatchExceptionEndpoint(); report = verifyAndGetReport(delivery); } finally { Field callbacksField = Configuration.class.getDeclaredField("callbacks"); @SuppressWarnings(value = "unchecked") Collection<Callback> callbacks = (Collection<Callback>) callbacksField.get(bugsnag.getConfig()); callbacks.remove(callback); } assertTrue(report.getUnhandled()); assertEquals("warning", report.getSeverity()); assertEquals("userCallbackSetSeverity", report.getSeverityReason().getType()); }
Source:
private Subscription.State getEffectiveState(TopicName topicName, String subscriptionName) { Set<Subscription.State> states = loadSubscriptionStatesFromAllDc(topicName, subscriptionName); if (states.contains(Subscription.State.ACTIVE)) { return Subscription.State.ACTIVE; } else if (states.contains(Subscription.State.SUSPENDED)) { return Subscription.State.SUSPENDED; } else { return Subscription.State.PENDING; } }

Target:
private Subscription.State getEffectiveState(TopicName topicName, String subscriptionName) { Set<Subscription.State> states = loadSubscriptionStatesFromAllDc(topicName, subscriptionName); if (states.size() > 1) { logger.warn("Some states are out of sync: {}", states); } if (states.contains(Subscription.State.ACTIVE)) { return Subscription.State.ACTIVE; } else if (states.contains(Subscription.State.SUSPENDED)) { return Subscription.State.SUSPENDED; } else { return Subscription.State.PENDING; } }
Source:
public void testLastModifiedTime() throws IOException { AzureBlobFileSystem fs = this.getFileSystem(); Path testFilePath = new Path("childfile1.txt"); long createStartTime = System.currentTimeMillis(); fs.create(testFilePath); long createEndTime = System.currentTimeMillis(); FileStatus fStat = fs.getFileStatus(testFilePath); long lastModifiedTime = fStat.getModificationTime(); assertTrue((createStartTime / 1000) * 1000 - 1 < lastModifiedTime); assertTrue(createEndTime > lastModifiedTime); }

Target:
public void testLastModifiedTime() throws IOException { AzureBlobFileSystem fs = this.getFileSystem(); Path testFilePath = new Path("childfile1.txt"); long createStartTime = System.currentTimeMillis(); long minCreateStartTime = (createStartTime / 1000) * 1000 - 1; fs.create(testFilePath); long createEndTime = System.currentTimeMillis(); FileStatus fStat = fs.getFileStatus(testFilePath); long lastModifiedTime = fStat.getModificationTime(); assertTrue("lastModifiedTime should be after minCreateStartTime", minCreateStartTime < lastModifiedTime); assertTrue("lastModifiedTime should be before createEndTime", createEndTime > lastModifiedTime); }
Source:
private void loadLabels() throws OrmException { final ResultSet<ChangeLabel> changeLabels = db.changeLabels().byChange(changeId); final Set<ChangeLabel.LabelKey> labels = new HashSet<ChangeLabel.LabelKey>(); for (ChangeLabel cl : changeLabels) { labels.add(cl.getLabel()); } detail.setLabels(labels); }

Target:
private void loadLabels() throws OrmException { final List<ChangeLabel> changeLabels = db.changeLabels().byChange(changeId).toList(); final Set<ChangeLabel.LabelKey> labels = new HashSet<ChangeLabel.LabelKey>(changeLabels.size()); for (ChangeLabel cl : changeLabels) { labels.add(cl.getLabel()); } detail.setLabels(labels); }
Source:
protected static Blob replaceURLsByAbsolutePaths(Blob blob, Path tempDirectory, Function<String, Blob> blobResolver) throws IOException { String initialBlobContent = blob.getString(); Pattern pattern = Pattern.compile("(src=\")(.*?)(\")"); Matcher matcher = pattern.matcher(initialBlobContent); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String url = matcher.group(2); Blob imageBlob = blobResolver.apply(url); if (imageBlob == null) { break; } String safeFilename = FileUtils.getSafeFilename(imageBlob.getFilename()); File imageFile = tempDirectory.resolve(safeFilename).toFile(); imageBlob.transferTo(imageFile); matcher.appendReplacement(sb, "$1" + Matcher.quoteReplacement(imageFile.toPath().toString()) + "$3"); } matcher.appendTail(sb); String blobContentWithAbsolutePaths = sb.toString(); if (blobContentWithAbsolutePaths.equals(initialBlobContent)) { return blob; } Blob newBlob = new StringBlob(blobContentWithAbsolutePaths, blob.getMimeType(), blob.getEncoding()); newBlob.setFilename(blob.getFilename()); return newBlob; }

Target:
protected static Blob replaceURLsByAbsolutePaths(Blob blob, Path tempDirectory, Function<String, Blob> blobResolver) throws IOException { String initialBlobContent = blob.getString(); Pattern pattern = Pattern.compile("(src=([\"']))(.*?)(\\2)"); Matcher matcher = pattern.matcher(initialBlobContent); StringBuffer sb = new StringBuffer(); while (matcher.find()) { String url = matcher.group(3); Blob imageBlob = blobResolver.apply(url); if (imageBlob == null) { break; } String safeFilename = FileUtils.getSafeFilename(imageBlob.getFilename()); File imageFile = tempDirectory.resolve(safeFilename).toFile(); imageBlob.transferTo(imageFile); matcher.appendReplacement(sb, "$1" + Matcher.quoteReplacement(imageFile.toPath().toString()) + "$4"); } matcher.appendTail(sb); String blobContentWithAbsolutePaths = sb.toString(); if (blobContentWithAbsolutePaths.equals(initialBlobContent)) { return blob; } Blob newBlob = new StringBlob(blobContentWithAbsolutePaths, blob.getMimeType(), blob.getEncoding()); newBlob.setFilename(blob.getFilename()); return newBlob; }
Source:
protected void onCreate() { FirebaseApp app = FirebaseApp.getInstance(getArguments().appName); mAuth = FirebaseAuth.getInstance(app); mPhoneAuth = PhoneAuthProvider.getInstance(mAuth); mCredentialsClient = Credentials.getClient(this.getApplication()); }

Target:
protected void onCreate() { FirebaseApp app = FirebaseApp.getInstance(getArguments().appName); mAuth = FirebaseAuth.getInstance(app); mPhoneAuth = PhoneAuthProvider.getInstance(mAuth); mCredentialsClient = Credentials.getClient(getApplication()); }
Source:
public IObservableMap<K, V> getObservableMap() { return typedSource; }

Target:
public IObservableMap<K, V> getObservableMap() { return (IObservableMap<K, V>) getSource(); }