auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean shouldRemoveMostRecentTombstone() { switch (purgeConfig.getPurgeLatestTombstone()) { case ALWAYS: return true; case IF_DELETE_FOLLOWS_FIRST_WRITE: return firstWriteToken && deleteRightAfterFirstWriteTimestamp == maxTombstoneTimestamp; case IF_FIRST_WRITE_PRESENT: return firstWriteToken; } assert false: "Developer error"; return false; }

Target:
private boolean shouldRemoveMostRecentTombstone() { switch (purgeConfig.getPurgeLatestTombstone()) { case ALWAYS: return true; case IF_DELETE_FOLLOWS_FIRST_WRITE: return firstWriteToken && deleteRightAfterFirstWriteTimestamp == maxTombstoneTimestamp; case IF_FIRST_WRITE_PRESENT: return firstWriteToken; } assert false; return false; }
Source:
protected Iterable<List<Object>> computeNext() { if (updateType == null) { warningsManager.clearWarnings(); } while (client.isRunning()) { checkInterruption(null); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(e); throw e; } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }

Target:
protected Iterable<List<Object>> computeNext() { if (isQuery) { warningsManager.clearWarnings(); } while (client.isRunning()) { checkInterruption(null); QueryStatusInfo results = client.currentStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); Iterable<List<Object>> data = client.currentData().getData(); try { client.advance(); } catch (RuntimeException e) { checkInterruption(e); throw e; } if (data != null) { return data; } } verify(client.isFinished()); QueryStatusInfo results = client.finalStatusInfo(); progressCallback.accept(QueryStats.create(results.getId(), results.getStats())); warningsManager.addWarnings(results.getWarnings()); if (results.getError() != null) { throw new RuntimeException(resultsException(results)); } return endOfData(); }
Source:
private boolean returnsNullOnGivenInputTypes(ApplicableFunction applicableFunction, List<Type> parameterTypes) { Signature boundSignature = applicableFunction.getBoundSignature(); FunctionKind functionKind = boundSignature.getKind(); if (functionKind != SCALAR) { return true; } for (int i = 0; i < parameterTypes.size(); i++) { Type parameterType = parameterTypes.get(i); if (parameterType.equals(UNKNOWN)) { ScalarFunctionImplementation implementation = getScalarFunctionImplementation(new FunctionHandle(boundSignature)); if (implementation.getArgumentProperty(i).getNullConvention() != RETURN_NULL_ON_NULL) { return false; } } } return true; }

Target:
private boolean returnsNullOnGivenInputTypes(ApplicableFunction applicableFunction, List<Type> parameterTypes) { Signature boundSignature = applicableFunction.getBoundSignature(); FunctionKind functionKind = boundSignature.getKind(); if (functionKind != SCALAR) { return true; } for (int i = 0; i < parameterTypes.size(); i++) { Type parameterType = parameterTypes.get(i); if (parameterType.equals(UNKNOWN)) { ScalarFunctionImplementation implementation = getScalarFunctionImplementation(boundSignature); if (implementation.getArgumentProperty(i).getNullConvention() != RETURN_NULL_ON_NULL) { return false; } } } return true; }
Source:
private boolean applyAddTablePartitions(@Nullable JournalContext context, Journal.JournalEntry entry) { alluxio.proto.journal.Table.AddTablePartitionsEntry addTablePartitions = entry.getAddTablePartitions(); if (!addTablePartitions.getDbName().equals(mName)) { return false; } mTables.compute(addTablePartitions.getTableName(), (key, existingTable) -> { if (existingTable != null) { if (addTablePartitions.getVersion() == existingTable.getVersion()) { LOG.info("Adding partitions to table {}.{}", mName, addTablePartitions.getTableName()); if (context != null) { context.append(entry); } existingTable.addPartitions(addTablePartitions); return existingTable; } LOG.info("Will not add partitions to table {}.{}, because of mismatched versions. " + "version-to-delete: existing-version: {}", mName, addTablePartitions.getTableName(), addTablePartitions.getVersion(), existingTable.getVersion()); } LOG.debug("Cannot add partitions to table {}.{}, because it does not exist.", mName, addTablePartitions.getTableName()); return existingTable; }); return true; }

Target:
private boolean applyAddTablePartitions(@Nullable JournalContext context, Journal.JournalEntry entry) { alluxio.proto.journal.Table.AddTablePartitionsEntry addTablePartitions = entry.getAddTablePartitions(); if (!addTablePartitions.getDbName().equals(mName)) { return false; } mTables.compute(addTablePartitions.getTableName(), (key, existingTable) -> { if (existingTable != null) { if (addTablePartitions.getVersion() == existingTable.getVersion()) { LOG.info("Adding partitions to table {}.{}", addTablePartitions.getPartitionsCount(), mName, addTablePartitions.getTableName()); if (context != null) { context.append(entry); } existingTable.addPartitions(addTablePartitions); return existingTable; } LOG.info("Will not add partitions to table {}.{}, because of mismatched versions. " + "version-to-add-partitions: existing-version: {}", mName, addTablePartitions.getTableName(), addTablePartitions.getVersion(), existingTable.getVersion()); } LOG.debug("Cannot add partitions to table {}.{}, because it does not exist.", mName, addTablePartitions.getTableName()); return existingTable; }); return true; }
Source:
public void testMetaDataProtocolVersion() { long serversTimstamp = System.currentTimeMillis(); String version = MetaDataProtocol.getVersion(serversTimstamp); assertEquals("4.16.x", version); assertEquals(String.format("%d.%d.%s", PHOENIX_MAJOR_VERSION, PHOENIX_MINOR_VERSION, "x"), version); }

Target:
public void testMetaDataProtocolVersion() { assertEquals(String.format("%d.%d.%s", PHOENIX_MAJOR_VERSION, PHOENIX_MINOR_VERSION, "x"), MetaDataProtocol.getVersion(System.currentTimeMillis())); }
Source:
private void scheduleRefresh(Duration delay) { if (executor.isShutdown()) { return; } executor.schedule((Runnable) this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }

Target:
private void scheduleRefresh(Duration delay) { if (executor.isShutdown()) { return; } executor.schedule(this::refresh, delay.toMillis(), TimeUnit.MILLISECONDS); }
Source:
private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { registerStatistic(pageSource, poolName, "allocatedMemory", STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, new Callable<Number>() { @Override public Number call() throws Exception { return pageSource.delegatePageSource.getAllocatedSizeUnSync(); } }); }

Target:
private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { STAT_POOL_METHOD_REFERENCES.entrySet().stream().forEach((entry)-> registerStatistic(pageSource, poolName, entry.getKey(), STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, () -> entry.getValue().apply(pageSource)) ); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexSpec indexSpec = (IndexSpec) o; if (bitmapSerdeFactory != null ? !bitmapSerdeFactory.equals(indexSpec.bitmapSerdeFactory) : indexSpec.bitmapSerdeFactory != null) { return false; } if (dimensionCompression != null ? !dimensionCompression.equals(indexSpec.dimensionCompression) : indexSpec.dimensionCompression != null) { return false; } if (!Objects.equals(spatialDimensionDelimiter, indexSpec.spatialDimensionDelimiter)) { return false; } return !(metricCompression != null ? !metricCompression.equals(indexSpec.metricCompression) : indexSpec.metricCompression != null); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexSpec indexSpec = (IndexSpec) o; if (!bitmapSerdeFactory.equals(indexSpec.bitmapSerdeFactory)) { return false; } if (!dimensionCompression.equals(indexSpec.dimensionCompression)) { return false; } if (!longEncoding.equals(indexSpec.longEncoding)) { return false; } if (!spatialDimensionDelimiter.equals(indexSpec.spatialDimensionDelimiter)) { return false; } return metricCompression.equals(indexSpec.metricCompression); }
Source:
private DatumReader<Object> buildDatumReader(Schema schema, Schema writtenSchema) { if (specific) { return new SpecificDatumReader<Object>(unwrapNull(writtenSchema), unwrapNull(schema)); } else { return new GenericDatumReader<Object>(unwrapNull(writtenSchema), unwrapNull(schema)); } }

Target:
private DatumReader<Object> buildDatumReader(Schema schema, Schema writtenSchema) { if (specific) { return new SpecificDatumReader<Object>(unwrapNullable(writtenSchema), unwrapNullable(schema)); } else { return new GenericDatumReader<Object>(unwrapNullable(writtenSchema), unwrapNullable(schema)); } }
Source:
public void setUp() throws Exception { super.setUp(); iProject = project.project; testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); new Git(repo).commit().setAuthor("JUnit", "junit@jgit.org") .setMessage("Initial commit").call(); }

Target:
public void setUp() throws Exception { super.setUp(); iProject = project.project; testRepo = new TestRepository(gitDir); testRepo.connect(iProject); repo = RepositoryMapping.getMapping(iProject).getRepository(); try (Git git = new Git(repo)) { git.commit().setAuthor("JUnit", "junit@jgit.org") .setMessage("Initial commit").call(); } }
Source:
private List<?> getRelatedArticles() { Map<String, Map<String, ?>> relationshipsByDoi = new HashMap<>(); for (Map<String, ?> relatedArticle : readRelatedArticles()) { relationshipsByDoi.put((String) relatedArticle.get("doi"), relatedArticle); } return relationshipsByDoi.values().stream() .sorted(BY_DESCENDING_PUB_DATE) .collect(Collectors.toList()); }

Target:
private List<Map<String, ?>> getRelatedArticles() { Map<String, Map<String, ?>> relationshipsByDoi = new HashMap<>(); for (String direction : RELATIONSHIP_DIRECTIONS) { for (Map<String, ?> relatedArticle : relationships.get(direction)) { String relatedArticleDoi = (String) relatedArticle.get("doi"); Map<String, ?> previous = relationshipsByDoi.put(relatedArticleDoi, relatedArticle); if (previous != null) { Preconditions.checkState(Objects.equals(relatedArticle.get("revisionNumber"), previous.get("revisionNumber")) && Objects.equals(relatedArticle.get("title"), previous.get("title")) && Objects.equals(relatedArticle.get("publicationDate"), previous.get("publicationDate"))); } } } return relationshipsByDoi.values().stream() .filter(ArticleMetadata::isPublished) .sorted(BY_DESCENDING_PUB_DATE) .collect(Collectors.toList()); }
Source:
public Weighting getWeightingForCH( WeightingMap weightingMap, FlagEncoder encoder ) { String weightingStr = weightingMap.getWeighting().toLowerCase(); if (weightingStr.isEmpty()) weightingStr = getCHWeighting().get(0); for (Weighting w : algoFactories.keySet()) { if (w.matches(weightingStr, encoder)) return w; } throw new IllegalStateException("No weighting found for request " + weightingMap + ", encoder:" + encoder + ", " + algoFactories); }

Target:
public Weighting getWeightingForCH( WeightingMap weightingMap, FlagEncoder encoder ) { String weightingStr = weightingMap.getWeighting().toLowerCase(); if (weightingStr.isEmpty()) weightingStr = getCHWeightings().get(0); for (Weighting w : algoFactories.keySet()) { if (w.matches(weightingStr, encoder)) return w; } throw new IllegalStateException("No weighting found for request " + weightingMap + ", encoder:" + encoder + ", " + algoFactories); }
Source:
public InsightsResource(final AccountDAO accountDAO, final TrendsDAO trendsDAO, final AggregateSleepScoreDAODynamoDB scoreDAODynamoDB, final TrackerMotionDAO trackerMotionDAO) { this.accountDAO = accountDAO; this.trendGraphProcessor = new TrendGraphProcessor(trendsDAO, scoreDAODynamoDB, trackerMotionDAO); }

Target:
public InsightsResource(final AccountDAO accountDAO, final TrendsDAO trendsDAO, final AggregateSleepScoreDAODynamoDB scoreDAODynamoDB, final TrackerMotionDAO trackerMotionDAO) { this.accountDAO = accountDAO; this.trendsDAO = trendsDAO; this.scoreDAODynamoDB = scoreDAODynamoDB; this.trackerMotionDAO = trackerMotionDAO; }
Source:
public void appendRows(Page page) { if (tempFiles.size() == maxTempFiles) { throw new PrestoException(HIVE_TOO_MANY_BUCKET_SORT_FILES, "Too many temporary files for sorted bucket writer"); } if (!sortBuffer.canAdd(page)) { flushBuffer(); } sortBuffer.add(page); }

Target:
public void appendRows(Page page) { if (!sortBuffer.canAdd(page)) { flushToTempFile(); } sortBuffer.add(page); }
Source:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (classCache.containsKey(name)) { return classCache.get(name); } for (WeakReference<Bundle> bundle : bundles) { try { final Class clazz = bundle.get().loadClass(name); if (clazz != null) { classCache.put(name, clazz); return clazz; } } catch (Exception ignore) { } } throw new ClassNotFoundException("Could not load requested class : " + name); }

Target:
protected Class<?> findClass(String name) throws ClassNotFoundException { if (classCache.containsKey(name)) { return classCache.get(name); } for (WeakReference<Bundle> ref : bundles) { final Bundle bundle = ref.get(); if (bundle.getState() == Bundle.ACTIVE) { try { final Class clazz = bundle.loadClass(name); if (clazz != null) { classCache.put(name, clazz); return clazz; } } catch (Exception ignore) { } } } throw new ClassNotFoundException("Could not load requested class : " + name); }
Source:
public void close() throws IOException { if (closed) { return; } try { if (errorCount == 0) { if (blkInProgress) { throw new IllegalStateException("Close() called with active block appender."); } try (BlockAppender appender = prepareMetaBlock(DataIndex.BLOCK_NAME, getDefaultCompressionAlgorithm())) { dataIndex.write(appender); } long offsetIndexMeta = out.position(); metaIndex.write(out); long offsetCryptoParameter = out.position(); String es = this.encryptionStrategy.getClass().getName(); out.writeUTF(es); out.writeLong(offsetIndexMeta); out.writeLong(offsetCryptoParameter); API_VERSION_3.write(out); Magic.write(out); out.flush(); length = out.position(); out.close(); } } finally { closed = true; } }

Target:
public void close() throws IOException { if (closed) { return; } try { if (errorCount == 0) { if (blkInProgress) { throw new IllegalStateException("Close() called with active block appender."); } try (BlockAppender appender = prepareMetaBlock(DataIndex.BLOCK_NAME, getDefaultCompressionAlgorithm())) { dataIndex.write(appender); } long offsetIndexMeta = out.position(); metaIndex.write(out); long offsetCryptoParameter = out.position(); out.writeUTF(this.encrypter.getParameters()); out.writeLong(offsetIndexMeta); out.writeLong(offsetCryptoParameter); API_VERSION_3.write(out); Magic.write(out); out.flush(); length = out.position(); out.close(); } } finally { closed = true; } }
Source:
private void testWithConfiguration(LogLevel level, LogFileConfiguration config, Runnable r) { LogFileConfiguration old = Database.log.getFile().getConfig(); EnumSet<LogDomain> domains = Database.log.getConsole().getDomains(); Database.log.getFile().setConfig(config); Database.log.getFile().setLevel(level); try { r.run(); } finally { Database.log.getFile().setLevel(LogLevel.INFO); Database.log.getFile().setConfig(old); Database.log.getConsole().setDomains(domains); Database.log.getConsole().setLevel(LogLevel.INFO); } }

Target:
private void testWithConfiguration(LogLevel level, LogFileConfiguration config, Runnable r) { LogFileConfiguration old = Database.log.getFile().getConfig(); EnumSet<LogDomain> domains = Database.log.getConsole().getDomains(); Database.log.getFile().setConfig(config); Database.log.getFile().setLevel(level); try { r.run(); } finally { Database.log.getFile().setLevel(LogLevel.INFO); Database.log.getFile().setConfig(old); Database.log.getConsole().setDomains(domains); Database.log.getConsole().setLevel(LogLevel.WARNING); } }
Source:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { e.printStackTrace(); } return properties; }

Target:
private Properties loadStringProperties(String body) { Properties properties = new Properties(); try { properties.load(new StringReader(body)); } catch (IOException e) { } return properties; }
Source:
void addAll(List<Cell> hbaseCells, List<RowCell> familyCells) { if (!familyCells.isEmpty()) { Collections.sort(familyCells, QUALIFIER_COMPARATOR); hbaseCells.addAll(familyCells); familyCells.clear(); } }

Target:
private static void addAll(List<Cell> hbaseCells, List<RowCell> familyCells) { Collections.sort(familyCells, QUALIFIER_AND_TIMESTAMP_COMPARATOR); hbaseCells.addAll(familyCells); familyCells.clear(); }
Source:
public DiscoveryResult createResult(ServiceInfo info) { DiscoveryResult result = null; ThingUID uid = getThingUID(info); if (uid != null) { InetAddress[] addrs = info.getInetAddresses(); Map<String, Object> properties = new HashMap<>(2); String label = null; if (BST_10_THING_TYPE_UID.equals(uid.getThingTypeUID())) { try { String group = DiscoveryUtil .executeUrl("http://" + addrs[0].getHostAddress() + ":8090/getGroup"); label = DiscoveryUtil.getContentOfFirstElement(group, "name"); } catch (IOException e) { logger.debug("Can't obtain label for group. Will use the default one"); } } if (label == null || label.isEmpty()) { label = info.getName(); } if (label == null || label.isEmpty()) { label = "Bose SoundTouch"; } if (addrs.length > 1) { logger.warn("Bose SoundTouch device ({}) reports multiple addresses - using the first one: {}", info.getName(), label, Arrays.toString(addrs)); } properties.put(BoseSoundTouchConfiguration.HOST, addrs[0].getHostAddress()); if (getMacAddress(info) != null) { properties.put(BoseSoundTouchConfiguration.MAC_ADDRESS, new String(getMacAddress(info))); } byte[] manufacturer = info.getPropertyBytes("MANUFACTURER"); if (manufacturer != null) { properties.put(Thing.PROPERTY_VENDOR, new String(manufacturer)); } return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(label).withTTL(600).build(); } return result; }

Target:
public DiscoveryResult createResult(ServiceInfo info) { DiscoveryResult result = null; ThingUID uid = getThingUID(info); if (uid != null) { InetAddress[] addrs = info.getInetAddresses(); Map<String, Object> properties = new HashMap<>(2); String label = null; if (BST_10_THING_TYPE_UID.equals(uid.getThingTypeUID())) { try { String group = DiscoveryUtil .executeUrl("http://" + addrs[0].getHostAddress() + ":8090/getGroup"); label = DiscoveryUtil.getContentOfFirstElement(group, "name"); } catch (IOException e) { logger.debug("Can't obtain label for group. Will use the default one"); } } if (label == null || label.isEmpty()) { label = info.getName(); } if (label == null || label.isEmpty()) { label = "Bose SoundTouch"; } if (addrs.length > 1) { logger.warn("Bose SoundTouch device ({}) reports multiple addresses - using the first one: {}", info.getName(), label, Arrays.toString(addrs)); } properties.put(BoseSoundTouchConfiguration.HOST, addrs[0].getHostAddress()); if (getMacAddress(info) != null) { properties.put(BoseSoundTouchConfiguration.MAC_ADDRESS, new String(getMacAddress(info), StandardCharsets.UTF_8)); } byte[] manufacturer = info.getPropertyBytes("MANUFACTURER"); if (manufacturer != null) { properties.put(Thing.PROPERTY_VENDOR, new String(manufacturer, StandardCharsets.UTF_8)); } return DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(label).withTTL(600).build(); } return result; }
Source:
private boolean couldCreateVersion(final IPublishOperationConfiguration configuration) { return !newHashSet(transform(getAllVersions(getParentBranchPath()), new Function<ICodeSystemVersion, String>() { @Override public String apply(final ICodeSystemVersion version) { return checkNotNull(version).getVersionId(); } })).contains(configuration.getVersionId()); }

Target:
private boolean couldCreateVersion(final IPublishOperationConfiguration configuration) { return new CodeSystemRequests(getRepositoryUuid()) .prepareSearchCodeSystemVersion() .setCodeSystemShortName(configuration.getCodeSystemShortName()) .setVersionId(configuration.getVersionId()) .build(IBranchPath.MAIN_BRANCH) .executeSync(getEventBus()) .getItems() .isEmpty(); }
Source:
public <T extends RunConfigurationBase> void updateJavaParameters( T configuration, JavaParameters params, RunnerSettings runnerSettings ) throws ExecutionException { final Module module = findPantsModule(configuration); if (module == null) { return; } params.setUseDynamicClasspath(true); String homePath = PathManager.getHomePath(); String jdkPath = params.getJdkPath(); String pluginPath = PathManager.getPluginsPath(); Set<String> pathsAllowed = Sets.newHashSet(jdkPath, homePath, pluginPath); if (ApplicationManager.getApplication().isUnitTestMode()) { pathsAllowed.add( Optional.ofNullable(PluginManager.getPlugin(PluginId.getId("com.intellij"))) .map(s -> s.getPath().getParentFile().getParentFile().getParentFile().getAbsolutePath()).get() ); pathsAllowed.add( Optional.ofNullable(PluginManager.getPlugin(PluginId.getId("JUnit"))) .map(s -> s.getPath().getParentFile().getParentFile().getParentFile().getAbsolutePath()).get() ); } final PathsList classpath = params.getClassPath(); List<String> classpathToKeep = classpath.getPathList().stream() .filter(p -> pathsAllowed.stream().anyMatch(p::contains)).collect(Collectors.toList()); classpath.clear(); classpath.addAll(classpathToKeep); VirtualFile manifestJar = PantsUtil.findProjectManifestJar(configuration.getProject()) .orElseThrow(() -> new ExecutionException("Pants supports manifest jar, but it is not found.")); classpath.add(manifestJar.getPath()); PantsExternalMetricsListenerManager.getInstance().logTestRunner(configuration); }

Target:
public <T extends RunConfigurationBase> void updateJavaParameters( T configuration, JavaParameters params, RunnerSettings runnerSettings ) throws ExecutionException { final Module module = findPantsModule(configuration); if (module == null) { return; } Set<String> pathsAllowed = calculatePathsAllowed(params); final PathsList classpath = params.getClassPath(); List<String> classpathToKeep = classpath.getPathList().stream() .filter(cp -> pathsAllowed.stream().anyMatch(cp::contains)).collect(Collectors.toList()); classpath.clear(); classpath.addAll(classpathToKeep); VirtualFile manifestJar = PantsUtil.findProjectManifestJar(configuration.getProject()) .orElseThrow(() -> new ExecutionException("manifest.jar is not found. It should be generated by `./pants export-classpath ...`")); classpath.add(manifestJar.getPath()); PantsExternalMetricsListenerManager.getInstance().logTestRunner(configuration); }
Source:
protected Collection<String> getTableDefinitions() { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("CREATE TABLE indexing (" + "id int," + "id2 int," + "map_values map<text, int>," + "map_keys map<text, int>," + "map_entries map<text, int>," + "map_all map<text, int>," + "text_column text, " + "\"MixedCaseColumn\" list<text>," + (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0 ? ", map_full frozen<map<text, int>>," + "set_full frozen<set<text>>," + "list_full frozen<list<text>>," : "") + "PRIMARY KEY (id, id2));" ); if(cassandraVersion.compareTo(VersionNumber.parse("3.0.0-rc1")) >= 0) { builder.add("CREATE MATERIALIZED VIEW mv1 AS " + "SELECT id2, id, map_values, text_column " + "FROM indexing " + "WHERE id2 IS NOT NULL AND id IS NOT NULL AND text_column IS NOT NULL " + "PRIMARY KEY (id2, id);" ); } return builder.build(); }

Target:
protected Collection<String> getTableDefinitions() { ImmutableList.Builder<String> builder = ImmutableList.builder(); builder.add("CREATE TABLE indexing (" + "id int," + "id2 int," + "map_values map<text, int>," + "map_keys map<text, int>," + "map_entries map<text, int>," + "map_all map<text, int>," + "text_column text, " + "\"MixedCaseColumn\" list<text>," + (cassandraVersion.compareTo(VersionNumber.parse("2.1.3")) >= 0 ? ", map_full frozen<map<text, int>>," + "set_full frozen<set<text>>," + "list_full frozen<list<text>>," : "") + "PRIMARY KEY (id, id2));" ); return builder.build(); }
Source:
public void onPartitionBecomeStandbyFromLeader(String partitionName) { logger.info("Partition state change notification from Leader to Standby received for partition {}", partitionName); rwlock1.writeLock().lock(); try { if (peerLeaderReplicasByPartition.containsKey(partitionName)) { peerLeaderReplicasByPartition.remove((partitionName)); } } finally { rwlock1.writeLock().unlock(); } }

Target:
public void onPartitionBecomeStandbyFromLeader(String partitionName) { logger.info("Partition state change notification from Leader to Standby received for partition {}", partitionName); partitionLeaderInfo.removePartition(partitionName); }
Source:
private void checkRepresentation(EObject target, DRepresentation representation, boolean expected) { Collection<DRepresentation> representations = DialectManager.INSTANCE.getRepresentations(target, session); assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with sirius cross referencer", expected, representations.contains(representation)); }

Target:
private void checkRepresentation(EObject target, DRepresentation representation, boolean expected) { Collection<DRepresentation> representations = Lists.newArrayList(); ECrossReferenceAdapter xref = session.getSemanticCrossReferencer(); for (EStructuralFeature.Setting setting : xref.getInverseReferences(target)) { if (ViewpointPackage.Literals.DREPRESENTATION.isInstance(setting.getEObject()) && setting.getEStructuralFeature() == ViewpointPackage.Literals.DSEMANTIC_DECORATOR__TARGET) { representations.add((DRepresentation) setting.getEObject()); } } assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with sirius cross referencer", expected, representations.contains(representation)); representations = DialectManager.INSTANCE.getRepresentations(target, session); assertEquals("Can " + (expected ? "not " : "") + "find " + DIAGRAM_NAME + " DRepresentation with DialectManager.INSTANCE.getRepresentations", expected, representations.contains(representation)); }
Source:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal(name.textContent, value.textContent);; }

Target:
public void onEditButtonClicked(final ClickEvent ignore) { presenter.openEditModal();; }
Source:
public static long bitCount(@SqlType(StandardTypes.BIGINT) long num, @SqlType(StandardTypes.BIGINT) long bits) { if (bits == 64) { return Long.bitCount(num); } if (bits <= 1 || bits > 64) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Bits specified in bit_count must be between 2 and 64, got " + bits); } long lowBitsMask = (1L << (bits - 1)) - 1; if (num > lowBitsMask || num < ~lowBitsMask) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Number must be representable with the bits specified. " + num + " can not be represented with " + bits + " bits"); } long mask = lowBitsMask | 0x8000_0000_0000_0000L; return Long.bitCount(num & mask); }

Target:
public static long bitCount(@SqlType(StandardTypes.BIGINT) long num, @SqlType(StandardTypes.BIGINT) long bits) { if (bits == 64) { return Long.bitCount(num); } if (bits <= 1 || bits > 64) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Bits specified in bit_count must be between 2 and 64, got " + bits); } long lowBitsMask = (1L << (bits - 1)) - 1; if (num > lowBitsMask || num < ~lowBitsMask) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "Number must be representable with the bits specified. " + num + " can not be represented with " + bits + " bits"); } long mask = (1L << bits) - 1; return Long.bitCount(num & mask); }
Source:
@Override public void deactivate(ComponentContext context) { handlers = null; super.deactivate(context); }

Target:
public void deactivate(ComponentContext context) { handlers = null; super.deactivate(context); }
Source:
private void startLockMonitoring() { logger.debug("Starting the lock monitor"); Thread monitorThread = new Thread(new MonitorLock()); monitorThread.setDaemon(true); monitorThread.start(); }

Target:
private synchronized void startLockMonitoring() { logger.debug("Starting the lock monitor"); if (scheduledLockMonitor == null) { MonitorLock monitorLock = new MonitorLock(); scheduledLockMonitor = scheduledPool.scheduleAtFixedRate(monitorLock, LOCK_MONITOR_TIMEOUT_MILLIES, LOCK_MONITOR_TIMEOUT_MILLIES, TimeUnit.MILLISECONDS); } else { logger.debug("Lock monitor was already started"); } }
Source:
public @ResponseBody ExperimentDto get(@PathVariable Long experimentId) throws IOException { return Dtos.asDto(experimentService.get(experimentId)); }

Target:
public @ResponseBody ExperimentDto get(@PathVariable Long experimentId) throws IOException { Experiment experiment = experimentService.get(experimentId); if (experiment == null) { throw new RestException("No such experiment.", Status.NOT_FOUND); } return Dtos.asDto(experiment); }
Source:
static void sendKey(View view, String keyName) { int keyCode = 0; String chars = null; switch (keyName) { case "ESC": keyCode = KeyEvent.KEYCODE_ESCAPE; break; case "TAB": keyCode = KeyEvent.KEYCODE_TAB; break; case "HOME": keyCode = KeyEvent.KEYCODE_MOVE_HOME; break; case "END": keyCode = KeyEvent.KEYCODE_MOVE_END; break; case "PGUP": keyCode = KeyEvent.KEYCODE_PAGE_UP; break; case "PGDN": keyCode = KeyEvent.KEYCODE_PAGE_DOWN; break; case "INS": keyCode = KeyEvent.KEYCODE_INSERT; break; case "DEL": keyCode = KeyEvent.KEYCODE_FORWARD_DEL; break; case "↑": keyCode = KeyEvent.KEYCODE_DPAD_UP; break; case "←": keyCode = KeyEvent.KEYCODE_DPAD_LEFT; break; case "→": keyCode = KeyEvent.KEYCODE_DPAD_RIGHT; break; case "↓": keyCode = KeyEvent.KEYCODE_DPAD_DOWN; break; case "↲": keyCode = KeyEvent.KEYCODE_ENTER; break; case "―": chars = "-"; break; case "-": chars = "-"; break; default: chars = keyName; } TerminalView terminalView = view.findViewById(R.id.terminal_view); if (keyCode > 0) { terminalView.onKeyDown(keyCode, new KeyEvent(KeyEvent.ACTION_UP, keyCode)); } else { TerminalSession session = terminalView.getCurrentSession(); if (session != null) session.write(chars); } }

Target:
static void sendKey(View view, String keyName) { TerminalView terminalView = view.findViewById(R.id.terminal_view); if (keyCodesForString.containsKey(keyName)) { int keyCode = keyCodesForString.get(keyName); terminalView.onKeyDown(keyCode, new KeyEvent(KeyEvent.ACTION_UP, keyCode)); } else { TerminalSession session = terminalView.getCurrentSession(); if (session != null) session.write(keyName); } }
Source:
public void streamData(PID pid, String dsName, AccessGroupSet principals, boolean asAttachment, HttpServletResponse response) throws IOException, ResourceNotFoundException { DatastreamType derivType = getByIdentifier(dsName); if (derivType == null || !derivativeService.listDerivativeTypes().contains(derivType)) { throw new IllegalArgumentException(dsName + " is not a valid derivative type."); } accessControlService.assertHasAccess("Insufficient permissions to access derivative " + dsName + " for object " + pid, pid, principals, getPermissionForDatastream(derivType)); Derivative deriv = derivativeService.getDerivative(pid, derivType); if (deriv == null) { throw new ResourceNotFoundException("Deriviatve " + dsName + " does not exist for object " + pid); } File derivFile = deriv.getFile(); response.setHeader(CONTENT_LENGTH, Long.toString(derivFile.length())); response.setHeader(CONTENT_TYPE, derivType.getMimetype()); String filename = derivFile.getName(); if (asAttachment) { response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); } else { response.setHeader(CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); } OutputStream outStream = response.getOutputStream(); IOUtils.copy(new FileInputStream(derivFile), outStream, BUFFER_SIZE); }

Target:
public void streamData(PID pid, String dsName, AccessGroupSet principals, boolean asAttachment, HttpServletResponse response) throws IOException, ResourceNotFoundException { DatastreamType derivType = getByIdentifier(dsName); if (derivType == null || !listDerivativeTypes().contains(derivType)) { throw new IllegalArgumentException(dsName + " is not a valid derivative type."); } accessControlService.assertHasAccess("Insufficient permissions to access derivative " + dsName + " for object " + pid, pid, principals, getPermissionForDatastream(derivType)); Derivative deriv = derivativeService.getDerivative(pid, derivType); if (deriv == null) { throw new ResourceNotFoundException("Deriviatve " + dsName + " does not exist for object " + pid); } File derivFile = deriv.getFile(); response.setHeader(CONTENT_LENGTH, Long.toString(derivFile.length())); response.setHeader(CONTENT_TYPE, derivType.getMimetype()); String filename = derivFile.getName(); if (asAttachment) { response.setHeader(CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); } else { response.setHeader(CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\""); } OutputStream outStream = response.getOutputStream(); IOUtils.copy(new FileInputStream(derivFile), outStream, BUFFER_SIZE); }
Source:
public void runBadCollectionSizeTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("bad-collection-size"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("collections.BadCollection"); options.setOption("generated_limit", "5"); options.setOption("output_limit", "5"); CoverageChecker coverageChecker = new CoverageChecker( options, "collections.BadCollection.add(java.lang.Object) exclude", "collections.BadCollection.addAll(java.util.Collection) exclude", "collections.BadCollection.clear() exclude", "collections.BadCollection.contains(java.lang.Object) exclude", "collections.BadCollection.containsAll(java.util.Collection) exclude", "collections.BadCollection.isEmpty() exclude", "collections.BadCollection.iterator() exclude", "collections.BadCollection.remove(java.lang.Object) exclude", "collections.BadCollection.removeAll(java.util.Collection) exclude", "collections.BadCollection.retainAll(java.util.Collection) exclude", "collections.BadCollection.toArray(java.lang.Object[]) exclude"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.SOME, coverageChecker); }

Target:
public void runBadCollectionSizeTest() { SystemTestEnvironment testEnvironment = systemTestEnvironmentManager.createTestEnvironment("bad-collection-size"); RandoopOptions options = createRandoopOptions(testEnvironment); options.addTestClass("collections.BadCollection"); options.setOption("generated_limit", "10"); options.setOption("output_limit", "10"); CoverageChecker coverageChecker = new CoverageChecker( options, "collections.BadCollection.add(java.lang.Object) exclude", "collections.BadCollection.addAll(java.util.Collection) exclude", "collections.BadCollection.clear() exclude", "collections.BadCollection.contains(java.lang.Object) exclude", "collections.BadCollection.containsAll(java.util.Collection) exclude", "collections.BadCollection.isEmpty() exclude", "collections.BadCollection.iterator() exclude", "collections.BadCollection.remove(java.lang.Object) exclude", "collections.BadCollection.removeAll(java.util.Collection) exclude", "collections.BadCollection.retainAll(java.util.Collection) exclude", "collections.BadCollection.toArray(java.lang.Object[]) exclude"); generateAndTest( testEnvironment, options, ExpectedTests.DONT_CARE, ExpectedTests.SOME, coverageChecker); }
Source:
public DynamicConfigValidator(String configDir) { File config = new File(configDir); if (config.exists()) { this.setConfigDir(DynamicConfigHelpers.formatFilePath(config.getAbsolutePath())); } else { this.setConfigDir(DynamicConfigHelpers.formatFilePath(formatClassPath(configDir))); this.setConfigInClassPath(true); } }

Target:
public DynamicConfigValidator(String configDir) { File config = new File(configDir); if (config.exists()) { this.setConfigDir(FILEPATH_PATTERN + DynamicConfigHelpers.formatFilePath(config.getAbsolutePath()) + HJSON_EXTN); } else { this.setConfigDir(CLASSPATH_PATTERN + DynamicConfigHelpers.formatFilePath(formatClassPath(configDir)) + HJSON_EXTN); } }
Source:
private void checkAndUpdateBlacklist() { for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) { long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds()); if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) { InetSocketAddress host = blacklistedEntry.getKey(); if (isHostHealthy(host)) { blacklistedHosts.remove(host); log.error("Added host back into the pool after a waiting period and successful health check.", SafeArg.of("host", host)); } } } }

Target:
private void checkAndUpdateBlacklist() { for (Map.Entry<InetSocketAddress, Long> blacklistedEntry : blacklistedHosts.entrySet()) { long backoffTimeMillis = TimeUnit.SECONDS.toMillis(config.unresponsiveHostBackoffTimeSeconds()); if (blacklistedEntry.getValue() + backoffTimeMillis < System.currentTimeMillis()) { InetSocketAddress host = blacklistedEntry.getKey(); if (isHostHealthy(host)) { blacklistedHosts.remove(host); log.info("Added host back into the pool after a waiting period and successful health check.", SafeArg.of("host", host)); } } } }
Source:
private void validateURL(HttpServletRequest request, String url) { String proxyBase = GeoServerExtensions.getProperty(PROXY_BASE_URL); if(proxyBase != null) { if(!url.startsWith(proxyBase)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + proxyBase); } } String requestedUrl = request.getRequestURL().toString(); if(!requestedUrl.endsWith(TEST_WFS_POST_PATH)) { throw new IllegalStateException("Unepected, the TestWfsPost was accessed by a path not ending with TestWfsPost: " + requestedUrl); } String base = requestedUrl.substring(0, requestedUrl.lastIndexOf(TEST_WFS_POST_PATH)); if(!url.startsWith(base)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + base); } }

Target:
private void validateURL(HttpServletRequest request, String url) { String proxyBase = GeoServerExtensions.getProperty(PROXY_BASE_URL); if(proxyBase != null) { if(!url.startsWith(proxyBase)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + proxyBase); } } else { String requestedUrl = request.getRequestURL().toString(); if(!requestedUrl.endsWith(TEST_WFS_POST_PATH)) { throw new IllegalStateException("Unepected, the TestWfsPost was accessed by a path not ending with TestWfsPost: " + requestedUrl); } String base = requestedUrl.substring(0, requestedUrl.lastIndexOf(TEST_WFS_POST_PATH)); if(!url.startsWith(base)) { throw new IllegalArgumentException("Invalid url requested, the demo requests should be hitting: " + base); } } }
Source:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); String topicId = ((DiscussionBlockModel)getArguments().getSerializable( Router.EXTRA_COURSE_UNIT)).getData().topicId; Bundle args = new Bundle(); args.putString(Router.EXTRA_DISCUSSION_TOPIC_ID, topicId); args.putSerializable(Router.EXTRA_ENROLLMENT_COURSE_DATA, getArguments().getSerializable(Router.EXTRA_ENROLLMENT_COURSE_DATA)); Fragment fragment = new CourseDiscussionPostsThreadFragment(); fragment.setArguments(args); FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.content, fragment, FRAG_TAG); fragmentTransaction.disallowAddToBackStack(); fragmentTransaction.commit(); }

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (savedInstanceState == null) { String topicId = ((DiscussionBlockModel) unit).getData().topicId; Fragment fragment = CourseDiscussionPostsThreadFragment.newInstance(topicId, getArguments().getSerializable(Router.EXTRA_COURSE_DATA), !TextUtils.isEmpty(unit.getDisplayName())); FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction(); fragmentTransaction.add(R.id.content, fragment); fragmentTransaction.commit(); } }
Source:
public void canRemoveHook() throws Exception { final Repos repos = RtHooksITCase.github().repos(); final Repo repo = repos.create( Json.createObjectBuilder().add( "name", RandomStringUtils.randomNumeric(5) ).build() ); try { final Hooks hooks = repo.hooks(); final Hook hook = hooks.create( "geocommit", Collections.<String, String>emptyMap() ); hooks.remove(hook.number()); MatcherAssert.assertThat( hooks.iterate(), Matchers.not(Matchers.hasItem(hook)) ); } finally { repos.remove(repo.coordinates()); } }

Target:
public void canRemoveHook() throws Exception { final Repos repos = RtHooksITCase.repos(); final Repo repo = RtHooksITCase.repo(repos); try { final Hooks hooks = repo.hooks(); final Hook hook = hooks.create( "geocommit", Collections.<String, String>emptyMap() ); hooks.remove(hook.number()); MatcherAssert.assertThat( hooks.iterate(), Matchers.not(Matchers.hasItem(hook)) ); } finally { repos.remove(repo.coordinates()); } }
Source:
private void changeNameListener() { final EditText editTextUsername = new EditText(UserSettingsActivity.this); editTextUsername.setId(R.id.editText); editTextUsername.setText(mUser.getName()); editTextUsername.setSelection(editTextUsername.length()); final int minimumSize = getResources().getInteger(R.integer.minimumNameSize); final AlertDialog dialog = new AlertDialog.Builder(UserSettingsActivity.this) .setTitle("Change your username") .setMessage("Your new username must be at least " + minimumSize + " characters long.") .setView(editTextUsername) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String newName = editTextUsername.getText().toString(); if (newName.length() < minimumSize) { YieldsApplication.showToast(getApplicationContext(), "The username is too short"); } else { YieldsApplication.showToast(getApplicationContext(), "Username changed to \"" + newName + "\" !"); mUser.setName(newName); ServiceRequest request = new UserUpdateRequest(mUser); YieldsApplication.getBinder().sendRequest(request); dialog.dismiss(); } } }); }

Target:
private void changeNameListener() { final EditText editTextUsername = new EditText(UserSettingsActivity.this); editTextUsername.setId(R.id.editText); editTextUsername.setText(mUser.getName()); editTextUsername.setSelection(editTextUsername.length()); final int minimumSize = getResources().getInteger(R.integer.minimumNameSize); DialogInterface.OnClickListener emptyListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }; final AlertDialog dialog = new AlertDialog.Builder(UserSettingsActivity.this) .setTitle("Change your username") .setMessage("Your new username must be at least " + minimumSize + " characters long.") .setView(editTextUsername) .setPositiveButton("Ok", emptyListener) .setNegativeButton("Cancel", emptyListener) .create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String newName = editTextUsername.getText().toString(); if (newName.length() < minimumSize) { YieldsApplication.showToast(getApplicationContext(), "The username is too short"); } else { YieldsApplication.showToast(getApplicationContext(), "Username changed to \"" + newName + "\" !"); mUser.setName(newName); ServiceRequest request = new UserUpdateRequest(mUser); YieldsApplication.getBinder().sendRequest(request); dialog.dismiss(); } } }); }
Source:
boolean hasRestoringTasks() { if (restoring.isEmpty()) { restoredPartitions.clear(); restoringByPartition.clear(); } return !restoring.isEmpty(); }

Target:
boolean hasRestoringTasks() { return !restoring.isEmpty(); }
Source:
public List<MappingFileData> build(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { List<MappingFileData> answer = new ArrayList<MappingFileData>(); for (MappingsDefinition mappingsDefinition : mappingsDefinitions) { Configuration configuration = null; if (mappingsDefinition.getConfiguration() != null) { configuration = mappingsDefinition.getConfiguration().build(beanContainer); } MappingFileData data = new MappingFileData(); data.setConfiguration(configuration); data.getClassMaps().addAll(mappingsDefinition.build(configuration, beanContainer, destBeanCreator, propertyDescriptorFactory)); answer.add(data); } return answer; }

Target:
public List<MappingFileData> build(BeanContainer beanContainer, DestBeanCreator destBeanCreator, PropertyDescriptorFactory propertyDescriptorFactory) { List<MappingFileData> answer = new ArrayList<>(); for (MappingsDefinition mappingsDefinition : mappingsDefinitions) { Configuration configuration = null; if (mappingsDefinition.getConfiguration() != null) { configuration = mappingsDefinition.getConfiguration().build(beanContainer); } MappingFileData data = new MappingFileData(); data.setConfiguration(configuration); data.getClassMaps().addAll(mappingsDefinition.build(configuration, beanContainer, destBeanCreator, propertyDescriptorFactory)); answer.add(data); } return answer; }
Source:
public void verifyInputExpand(String comment) { showCommentsSection(); String inputHeight = commentInputArea.getCssValue("height"); commentInputArea.sendKeys(comment); String inputExpandedHeight = commentInputArea.getCssValue("height"); Assertion.assertTrue(Integer.parseInt(inputExpandedHeight.substring(0, 1)) > Integer.parseInt(inputHeight.substring(0, 1)), "input is not bigger" ); }

Target:
public void verifyInputExpand(String comment) { showCommentsSection(); int inputHeight = Integer.parseInt(commentInputArea.getCssValue("height").substring(0, 1)); commentInputArea.sendKeys(comment); int inputExpandedHeight = Integer.parseInt(commentInputArea.getCssValue("height").substring(0, 1)); Assertion.assertTrue(inputExpandedHeight > inputHeight, "input is not bigger"); }