auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<String> getOverwriteUserAttributesListFromExtSource(ExtSource membersSource) throws InternalErrorException { Map<String, String> membersSourceAttributes = getPerunBl().getExtSourcesManagerBl().getAttributes(membersSource); List<String> overwriteUserAttributesList = new ArrayList<>(); String overwriteUserAttributes = membersSourceAttributes.get("overwriteUserAttributes"); if(overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty()) { overwriteUserAttributes = overwriteUserAttributes.replaceAll("\\s", ""); overwriteUserAttributesList = asList(overwriteUserAttributes.split(",")); } return overwriteUserAttributesList; }

Target:
private List<String> getOverwriteUserAttributesListFromExtSource(ExtSource membersSource) throws InternalErrorException { Map<String, String> membersSourceAttributes = getPerunBl().getExtSourcesManagerBl().getAttributes(membersSource); List<String> overwriteUserAttributesList = new ArrayList<>(); String overwriteUserAttributes = membersSourceAttributes.get("overwriteUserAttributes"); if(overwriteUserAttributes != null && !overwriteUserAttributes.isEmpty()) { overwriteUserAttributes = overwriteUserAttributes.replaceAll("\\s", ""); overwriteUserAttributesList = Arrays.asList(overwriteUserAttributes.split(",")); } return overwriteUserAttributesList; }
Source:
public void stop() throws ConnectException { try { running.set(false); if (cachedConnectionProvider != null) { cachedConnectionProvider.close(); } } finally { cachedConnectionProvider = null; try { if (dialect != null) { dialect.close(); } } finally { dialect = null; } } }

Target:
public void stop() throws ConnectException { try { running.set(false); if (cachedConnectionProvider != null) { cachedConnectionProvider.close(); } } finally { cachedConnectionProvider = null; try { if (dialect != null) { dialect.close(); } } catch (Throwable t) { log.warn("Error while closing the dialect: ", dialect, t); } finally { dialect = null; } } }
Source:
public CompletableFuture<JobClient> execute(final Pipeline pipeline, final Configuration configuration) { requireNonNull(pipeline); requireNonNull(configuration); final JobGraph jobGraph = PipelineExecutorUtils.getJobGraph(pipeline, configuration); final JobID actualJobId = jobGraph.getJobID(); this.applicationJobIds.add(actualJobId); LOG.info("Job is submitted.", actualJobId); final EmbeddedClient embeddedClient = new EmbeddedClient(actualJobId, configuration, dispatcherGateway); return embeddedClient .submitJob(jobGraph) .thenApplyAsync(jobID -> embeddedClient); }

Target:
public CompletableFuture<JobClient> execute(final Pipeline pipeline, final Configuration configuration) { checkNotNull(pipeline); checkNotNull(configuration); final JobGraph jobGraph = PipelineExecutorUtils.getJobGraph(pipeline, configuration); final JobID actualJobId = jobGraph.getJobID(); this.submittedJobIds.add(actualJobId); LOG.info("Job is submitted.", actualJobId); final Time timeout = Time.milliseconds(configuration.getLong(WebOptions.TIMEOUT)); final CompletableFuture<JobID> jobSubmissionFuture = submitJob( dispatcherGateway, blobServerAddress -> new BlobClient(blobServerAddress, configuration), jobGraph, timeout); final EmbeddedJobClient embeddedClient = new EmbeddedJobClient( actualJobId, dispatcherGateway, timeout); return jobSubmissionFuture .thenApplyAsync(jobID -> embeddedClient); }
Source:
public Collection<Partition<AbstractCouchBaseInputOperator<T>>> definePartitions(Collection<Partition<AbstractCouchBaseInputOperator<T>>> partitions, PartitioningContext incrementalCapacity) { conf = store.getConf(); int numPartitions = conf.getServers().size(); List<String> list = conf.getServers(); Collection<Partition<AbstractCouchBaseInputOperator<T>>> newPartitions = Lists.newArrayListWithExpectedSize(numPartitions); for (int i = 0; i < numPartitions; i++) { AbstractCouchBaseInputOperator<T> oper = PartitionerUtils.cloneOperatorByKryo(this); oper.setServerIndex(i); oper.setServerURIString(list.get(i)); logger.debug("oper urlstring is {}", i, oper.getServerURIString()); newPartitions.add(new DefaultPartition<AbstractCouchBaseInputOperator<T>>(oper)); } return newPartitions; }

Target:
public Collection<Partition<AbstractCouchBaseInputOperator<T>>> definePartitions(Collection<Partition<AbstractCouchBaseInputOperator<T>>> partitions, PartitioningContext incrementalCapacity) { conf = store.getConf(); int numPartitions = conf.getServers().size(); List<String> list = conf.getServers(); Collection<Partition<AbstractCouchBaseInputOperator<T>>> newPartitions = Lists.newArrayListWithExpectedSize(numPartitions); KryoCloneUtils<AbstractCouchBaseInputOperator<T>> cloneUtils = KryoCloneUtils.createCloneUtils(this); for (int i = 0; i < numPartitions; i++) { AbstractCouchBaseInputOperator<T> oper = cloneUtils.getClone(); oper.setServerIndex(i); oper.setServerURIString(list.get(i)); logger.debug("oper urlstring is {}", i, oper.getServerURIString()); newPartitions.add(new DefaultPartition<>(oper)); } return newPartitions; }
Source:
public <T> Query<T> mapTo(Type resultType) { return this.map(new RegisteredRowMapper<>(resultType, config.mappingRegistry)); }

Target:
public Query<?> mapTo(Type resultType) { return this.map(new RegisteredRowMapper<>(resultType, config.mappingRegistry)); }
Source:
private void startDownloadTask() { downloading = true; bukkitService.runTaskAsynchronously(() -> { try { Path tempFile = Files.createTempFile(ARCHIVE_FILE, null); try (OutputStream out = Files.newOutputStream(tempFile)) { Resources.copy(new URL(ARCHIVE_URL), out); } String targetChecksum = Resources.toString(new URL(CHECKSUM_URL), StandardCharsets.UTF_8); if (!verifyChecksum(Hashing.md5(), tempFile, targetChecksum)) { return; } if (!extractDatabase(tempFile, dataFile)) { ConsoleLogger.warning("Cannot find database inside downloaded GEO IP file at " + tempFile); } downloading = false; } catch (IOException ioEx) { ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); } }); }

Target:
private void startDownloadTask() { downloading = true; bukkitService.runTaskAsynchronously(() -> { ConsoleLogger.info("Downloading GEO IP database, because the old database is outdated or doesn't exist"); Path tempFile = null; try { tempFile = Files.createTempFile(ARCHIVE_FILE, null); try (OutputStream out = Files.newOutputStream(tempFile)) { Resources.copy(new URL(ARCHIVE_URL), out); } String targetChecksum = Resources.toString(new URL(CHECKSUM_URL), StandardCharsets.UTF_8); if (!verifyChecksum(Hashing.md5(), tempFile, targetChecksum)) { return; } if (!extractDatabase(tempFile, dataFile)) { ConsoleLogger.warning("Cannot find database inside downloaded GEO IP file at " + tempFile); return; } ConsoleLogger.info("Successfully downloaded new GEO IP database to " + dataFile); downloading = false; } catch (IOException ioEx) { ConsoleLogger.logException("Could not download GeoLiteAPI database", ioEx); } finally { if (tempFile != null) { FileUtils.delete(tempFile.toFile()); } } }); }
Source:
private List<EnricherSpec<?>> buildEnricherSpecs(Object enrichers) { List<EnricherSpec<?>> enricherSpecs = new ArrayList<EnricherSpec<? extends Enricher>>(); if (enrichers instanceof Iterable) { for (Object enricher : (Iterable<Object>)enrichers) { if (enricher instanceof Map) { String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString(); Class<? extends Enricher> enricherType = null; try { enricherType = ((Class<? extends Enricher>) Class.forName(enricherTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config"))); } else { throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass()); } } } else if (enrichers != null) { throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass()); } return enricherSpecs; }

Target:
private List<EnricherSpec<?>> buildEnricherSpecs(Object enrichers) { List<EnricherSpec<?>> enricherSpecs = Lists.newArrayList(); if (enrichers instanceof Iterable) { for (Object enricher : (Iterable<Object>)enrichers) { if (enricher instanceof Map) { String enricherTypeName = ((Map<?, ?>) enricher).get("enricherType").toString(); Class<? extends Enricher> enricherType = null; try { enricherType = ((Class<? extends Enricher>) Class.forName(enricherTypeName)); } catch (ClassNotFoundException e) { throw Exceptions.propagate(e); } enricherSpecs.add(toCoreEnricherSpec(enricherType, (Map<?, ?>) ((Map<?, ?>) enricher).get("brooklyn.config"))); } else { throw new IllegalArgumentException("enricher should be map, not " + enricher.getClass()); } } } else if (enrichers != null) { throw new IllegalArgumentException("enrichers body should be iterable, not " + enrichers.getClass()); } return enricherSpecs; }
Source:
public String[] getLocations(InputSplit split) throws IOException { if (!(split instanceof FileSplit)) { if (isDebugEnabled) { LOG.debug("Split: " + split + " is not a FileSplit. Using default locations"); } return split.getLocations(); } FileSplit fsplit = (FileSplit) split; String splitDesc = "Split at " + fsplit.getPath() + " with offset= " + fsplit.getStart() + ", length=" + fsplit.getLength(); List<String> preferredLocations = new ArrayList<>(preferLocations(fsplit)); List<String> finalLocations = new ArrayList<>(numberOfLocations); while (finalLocations.size() < numberOfLocations && preferredLocations.size() > 0) { String nextLocation = preferredLocations.get(determineLocation(preferredLocations, fsplit.getPath().toString(), fsplit.getStart(), splitDesc)); finalLocations.add(nextLocation); preferredLocations.remove(nextLocation); } return finalLocations.toArray(new String[0]); }

Target:
public String[] getLocations(InputSplit split) throws IOException { if (!(split instanceof FileSplit)) { if (isDebugEnabled) { LOG.debug("Split: " + split + " is not a FileSplit. Using default locations"); } return split.getLocations(); } FileSplit fsplit = (FileSplit) split; String splitDesc = "Split at " + fsplit.getPath() + " with offset= " + fsplit.getStart() + ", length=" + fsplit.getLength(); List<String> locationsToCheck = (useLocality ? preferLocations(fsplit) : locations); return determineLocation(locationsToCheck, numberOfLocations, fsplit.getPath().toString(), fsplit.getStart(), splitDesc); }
Source:
public static void main(String[] args) { var data1 = new Data(1, "data1", Data.DataType.type1); var data2 = new Data(2, "data2", Data.DataType.type2); var data3 = new Data(3, "data3", Data.DataType.type3); var data4 = new Data(4, "data4", Data.DataType.type1); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); ShardManager manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new RangeShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new HashShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); return; }

Target:
public static void main(String[] args) { var data1 = new Data(1, "data1", Data.DataType.type1); var data2 = new Data(2, "data2", Data.DataType.type2); var data3 = new Data(3, "data3", Data.DataType.type3); var data4 = new Data(4, "data4", Data.DataType.type1); var shard1 = new Shard(1); var shard2 = new Shard(2); var shard3 = new Shard(3); ShardManager manager = new LookupShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new RangeShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); manager = new HashShardManager(); manager.addNewShard(shard1); manager.addNewShard(shard2); manager.addNewShard(shard3); manager.storeData(data1); manager.storeData(data2); manager.storeData(data3); manager.storeData(data4); shard1.clearData(); shard2.clearData(); shard3.clearData(); }
Source:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); Collections.addAll(this.injectionPoints, injectionPoints.toArray(new InjectionPoint[injectionPoints.size()])); return this; }

Target:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); this.injectionPoints.addAll(injectionPoints); return this; }
Source:
public ResteasyProviderFactory getProviderFactory() { return providerFactory; }

Target:
protected ResteasyProviderFactory getProviderFactory() { return providerFactory; }
Source:
public void testSerialization() throws IOException, ClassNotFoundException{ byte[] startRow = "aa".getBytes(); byte[] stopRow = "zz".getBytes(); String projectId = "project"; String zone = "zone"; String cluster = "cluster"; String table = "table"; CloudBigtableScanConfiguration config = new CloudBigtableScanConfiguration.Builder() .withProjectId(projectId) .withZone(zone) .withCluster(cluster) .withTable(table) .withScan(new Scan(startRow, stopRow)) .build(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(config); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); CloudBigtableScanConfiguration serialized = (CloudBigtableScanConfiguration) ois.readObject(); Assert.assertEquals(projectId, serialized.getProjectId()); Assert.assertEquals(zone, serialized.getZone()); Assert.assertEquals(cluster, serialized.getCluster()); Assert.assertEquals(table, serialized.getTable()); Scan scan = serialized.getScan(); Assert.assertArrayEquals(startRow, scan.getStartRow()); Assert.assertArrayEquals(stopRow, scan.getStopRow()); }

Target:
public void testSerialization() throws IOException, ClassNotFoundException{ byte[] startRow = "aa".getBytes(); byte[] stopRow = "zz".getBytes(); String projectId = "project"; String zone = "zone"; String cluster = "cluster"; String table = "table"; CloudBigtableScanConfiguration config = new CloudBigtableScanConfiguration.Builder() .withProjectId(projectId) .withZoneId(zone) .withClusterId(cluster) .withTableId(table) .withScan(new Scan(startRow, stopRow)) .build(); CloudBigtableScanConfiguration serialized = SerializableUtils.ensureSerializable(config); Assert.assertEquals(projectId, serialized.getProjectId()); Assert.assertEquals(zone, serialized.getZoneId()); Assert.assertEquals(cluster, serialized.getClusterId()); Assert.assertEquals(table, serialized.getTableId()); Scan scan = serialized.getScan(); Assert.assertArrayEquals(startRow, scan.getStartRow()); Assert.assertArrayEquals(stopRow, scan.getStopRow()); }
Source:
public static IResource convertToResource( @NotNull VirtualFile virtualFile, @NotNull IProject project) { IntelliJProjectImplV2 module = (IntelliJProjectImplV2) project .getAdapter(IntelliJProjectImplV2.class); return module.getResource(virtualFile); }

Target:
public static IResource convertToResource( @NotNull VirtualFile virtualFile, @NotNull IProject project) { IntelliJProjectImplV2 wrappedModule = (IntelliJProjectImplV2) project .getAdapter(IntelliJProjectImplV2.class); return wrappedModule.getResource(virtualFile); }
Source:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject configurationObject = json.getAsJsonObject(); JsonObject propertiesObject = configurationObject.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) { JsonElement value = entry.getValue(); String key = entry.getKey(); if (value.isJsonPrimitive()) { JsonPrimitive primitive = value.getAsJsonPrimitive(); configuration.put(key, deserialize(primitive)); } else if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); configuration.put(key, deserialize(array)); } else { throw new IllegalArgumentException( "Configuration parameters must be primitives or arrays of primities only but was " + value); } } return configuration; }

Target:
public Configuration deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Configuration configuration = new Configuration(); JsonObject configurationObject = json.getAsJsonObject(); if (configurationObject.get("properties") != null) { JsonObject propertiesObject = configurationObject.get("properties").getAsJsonObject(); for (Entry<String, JsonElement> entry : propertiesObject.entrySet()) { JsonElement value = entry.getValue(); String key = entry.getKey(); if (value.isJsonPrimitive()) { JsonPrimitive primitive = value.getAsJsonPrimitive(); configuration.put(key, deserialize(primitive)); } else if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); configuration.put(key, deserialize(array)); } else { throw new IllegalArgumentException( "Configuration parameters must be primitives or arrays of primities only but was " + value); } } } return configuration; }
Source:
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { String vepOutput = getVepOutput(jobExecution); if (getFileSize(vepOutput) <= 0) { logger.info("File is empty so following steps will not run", vepOutput); return new FlowExecutionStatus(STOP_FLOW); } return new FlowExecutionStatus(CONTINUE_FLOW); }

Target:
public FlowExecutionStatus decide(JobExecution jobExecution, StepExecution stepExecution) { String vepOutput = getVepOutput(jobExecution); if (getFileSize(vepOutput) > 0) { return new FlowExecutionStatus(CONTINUE_FLOW); } logger.info("File is empty so subsequent steps will not run", vepOutput); return new FlowExecutionStatus(STOP_FLOW); }
Source:
private void createWarning(final Level level, final ModelNode warning){ final ModelNode warningEntry = new ModelNode(); warningEntry.get(WARNING).set(warning); warningEntry.get(LEVEL).set(level.toString()); final ModelNode operation = activeStep.operation; if(operation != null){ final ModelNode operationEntry = warningEntry.get(OP); operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR)); operationEntry.get(OP).set(operation.get(OP)); } final ModelNode warnings = getResponseHeaders().get(WARNINGS); boolean unique = true; if (warnings.isDefined()) { for (ModelNode existing : warnings.asList()) { if (existing.equals(warning)) { unique = false; break; } } } if (unique) { warnings.add(warningEntry); } }

Target:
private void createWarning(final Level level, final ModelNode warning){ final ModelNode warningEntry = new ModelNode(); warningEntry.get(WARNING).set(warning); warningEntry.get(LEVEL).set(level.toString()); final ModelNode operation = activeStep.operation; if(operation != null){ final ModelNode operationEntry = warningEntry.get(OP); operationEntry.get(OP_ADDR).set(operation.get(OP_ADDR)); operationEntry.get(OP).set(operation.get(OP)); } final ModelNode warnings = getResponseHeaders().get(WARNINGS); boolean unique = true; if (warnings.isDefined()) { for (ModelNode existing : warnings.asList()) { if (existing.equals(warningEntry)) { unique = false; break; } } } if (unique) { warnings.add(warningEntry); } }
Source:
public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Void>.TaskCompletionSource allFinished = Task.create(); final ArrayList<Throwable> causes = new ArrayList<Throwable>(); final Object errorLock = new Object(); final AtomicInteger count = new AtomicInteger(tasks.size()); final AtomicBoolean isCancelled = new AtomicBoolean(false); for (Task<?> task : tasks) { @SuppressWarnings("unchecked") Task<Object> t = (Task<Object>) task; t.continueWith(new Continuation<Object, Void>() { @Override public Void then(Task<Object> task) { if (task.isFaulted()) { synchronized (errorLock) { causes.add(task.getError()); } } if (task.isCancelled()) { isCancelled.set(true); } if (count.decrementAndGet() == 0) { if (causes.size() != 0) { if (causes.size() == 1) { allFinished.setError((Exception) causes.get(0)); } else { Exception error = new AggregateException( String.format("There were %d exceptions.", causes.size()), causes); allFinished.setError(error); } } else if (isCancelled.get()) { allFinished.setCancelled(); } else { allFinished.setResult(null); } } return null; } }); } return allFinished.getTask(); }

Target:
public static Task<Void> whenAll(Collection<? extends Task<?>> tasks) { if (tasks.size() == 0) { return Task.forResult(null); } final Task<Void>.TaskCompletionSource allFinished = Task.create(); final ArrayList<Exception> causes = new ArrayList<Exception>(); final Object errorLock = new Object(); final AtomicInteger count = new AtomicInteger(tasks.size()); final AtomicBoolean isCancelled = new AtomicBoolean(false); for (Task<?> task : tasks) { @SuppressWarnings("unchecked") Task<Object> t = (Task<Object>) task; t.continueWith(new Continuation<Object, Void>() { @Override public Void then(Task<Object> task) { if (task.isFaulted()) { synchronized (errorLock) { causes.add(task.getError()); } } if (task.isCancelled()) { isCancelled.set(true); } if (count.decrementAndGet() == 0) { if (causes.size() != 0) { if (causes.size() == 1) { allFinished.setError(causes.get(0)); } else { Exception error = new AggregateException( String.format("There were %d exceptions.", causes.size()), causes); allFinished.setError(error); } } else if (isCancelled.get()) { allFinished.setCancelled(); } else { allFinished.setResult(null); } } return null; } }); } return allFinished.getTask(); }
Source:
private void runPushOperation() { pool.notifyStarting(this); if (!canceled) { try { git = gitManager.openRepository(projectName); runImpl(); } catch (RepositoryNotFoundException e) { log.error("Cannot replicate " + projectName + "; " + e.getMessage()); } catch (NoRemoteRepositoryException e) { log.error("Cannot replicate to " + uri + "; repository not found"); } catch (NotSupportedException e) { log.error("Cannot replicate to " + uri, e); } catch (TransportException e) { Throwable cause = e.getCause(); if (cause instanceof JSchException && cause.getMessage().startsWith("UnknownHostKey:")) { log.error("Cannot replicate to " + uri + ": " + cause.getMessage()); } else if (e instanceof LockFailureException) { lockRetry++; log.error("Cannot replicate to " + e.getMessage()); } else { log.error("Cannot replicate to " + uri, e); } if (lockRetry < 10) { pool.reschedule(this); } } catch (IOException e) { log.error("Cannot replicate to " + uri, e); } catch (RuntimeException e) { log.error("Unexpected error during replication to " + uri, e); } catch (Error e) { log.error("Unexpected error during replication to " + uri, e); } finally { if (git != null) { git.close(); } } } }

Target:
private void runPushOperation() { pool.notifyStarting(this); if (!canceled) { try { git = gitManager.openRepository(projectName); runImpl(); } catch (RepositoryNotFoundException e) { log.error("Cannot replicate " + projectName + "; " + e.getMessage()); } catch (NoRemoteRepositoryException e) { log.error("Cannot replicate to " + uri + "; repository not found"); } catch (NotSupportedException e) { log.error("Cannot replicate to " + uri, e); } catch (TransportException e) { Throwable cause = e.getCause(); if (cause instanceof JSchException && cause.getMessage().startsWith("UnknownHostKey:")) { log.error("Cannot replicate to " + uri + ": " + cause.getMessage()); } else if (e instanceof LockFailureException) { lockRetry++; log.error("Cannot replicate to " + e.getMessage()); } else { log.error("Cannot replicate to " + uri, e); } if (lockRetry < MAX_LOCK_TRIES) { pool.reschedule(this); } else { log.error("Giving up after " + MAX_LOCK_TRIES + " attempts to replicate, but still failing due to: " + e.getMessage()); } } catch (IOException e) { log.error("Cannot replicate to " + uri, e); } catch (RuntimeException e) { log.error("Unexpected error during replication to " + uri, e); } catch (Error e) { log.error("Unexpected error during replication to " + uri, e); } finally { if (git != null) { git.close(); } } } }
Source:
protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { return Collections.asSet( conversionContext.getTypeFactory().getType( dateTimeFormatterClass() ) ); }

Target:
protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { return Collections.asSet( conversionContext.getTypeFactory().getType( JavaTimeConstants.DATE_TIME_FORMATTER ) ); }
Source:
public static Pair<? extends UndoAction, TheHashinator> updateHashinator( Class<? extends TheHashinator> hashinatorImplementation, long version, byte configBytes[], boolean cooked) { TheHashinator existingHashinator = m_cachedHashinators.get(version); if (existingHashinator == null) { existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked); TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator); if (tempVal != null) existingHashinator = tempVal; } while (true) { final Pair<Long, ? extends TheHashinator> snapshot = instance.get(); if (version > snapshot.getFirst()) { final Pair<Long, ? extends TheHashinator> update = Pair.of(version, existingHashinator); if (instance.compareAndSet(snapshot, update)) { if (!m_elasticallyModified) { if (!update.getSecond().pIsPrestine()) { hostLogger.debug("The Hashinator has been elastically modified. " + "This cluster can no longer operate in DR same-size-cluster mode."); m_elasticallyModified = true; } } return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() { boolean rolledBack = instance.compareAndSet(update, snapshot); if (!rolledBack) { hostLogger.info( "Didn't roll back hashinator because it wasn't set to expected hashinator"); } } }, existingHashinator); } } else { return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() }, existingHashinator); } } }

Target:
public static Pair<? extends UndoAction, TheHashinator> updateHashinator( Class<? extends TheHashinator> hashinatorImplementation, long version, byte configBytes[], boolean cooked) { TheHashinator existingHashinator = m_cachedHashinators.get(version); if (existingHashinator == null) { existingHashinator = constructHashinator(hashinatorImplementation, configBytes, cooked); TheHashinator tempVal = m_cachedHashinators.putIfAbsent( version, existingHashinator); if (tempVal != null) existingHashinator = tempVal; } while (true) { final Pair<Long, ? extends TheHashinator> snapshot = instance.get(); if (version > snapshot.getFirst()) { final Pair<Long, ? extends TheHashinator> update = Pair.of(version, existingHashinator); if (instance.compareAndSet(snapshot, update)) { if (!m_elasticallyModified) { if (!update.getSecond().pIsPristine()) { hostLogger.debug("The Hashinator has been elastically modified. " + "This cluster can no longer operate in DR same-size-cluster mode."); m_elasticallyModified = true; } } return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() { boolean rolledBack = instance.compareAndSet(update, snapshot); if (!rolledBack) { hostLogger.info( "Didn't roll back hashinator because it wasn't set to expected hashinator"); } } }, existingHashinator); } } else { return Pair.of(new UndoAction() { @Override public void release() @Override public void undo() }, existingHashinator); } } }
Source:
private String checkURL(String url) { url = url.replace("\\", "/"); if (url.startsWith("file:")) { return url; } File file = new File(url); if (file.exists()) { try { return file.toURL().toExternalForm(); } catch (MalformedURLException e) { return url; } } return url; }

Target:
private String checkURL(String url) { url = url.replace("\\", "/"); if (url.startsWith("file:")) { return url; } File file = new File(url); if (file.exists()) { try { return file.toURI().toURL().toExternalForm(); } catch (MalformedURLException e) { return url; } } return url; }
Source:
public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); if (caps.getSucceeded()) { getHardwareInfo(vds); } continueRefreshCapabilities(new AtomicBoolean(), vds, oldVDS, caps); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }

Target:
public void onResponse(Map<String, Object> response) { try { VDSReturnValue caps = (VDSReturnValue) response.get("result"); invokeGetHardwareInfo(vds, caps); processRefreshCapabilitiesResponse(new AtomicBoolean(), vds, vds.clone(), caps); } catch (Throwable t) { onFailure(t); } finally { if (vds != null) { updateDynamicData(vds.getDynamicData()); updateNumaData(vds); monitoringStrategy.processHardwareCapabilities(vds); resourceManager.getEventListener().handleVdsVersion(vds.getId()); } } }
Source:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); String i18nCommitEncoding = rc.getString( ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); if (i18nCommitEncoding != null) { commitMessageEncoding = Charset.forName(i18nCommitEncoding); } }

Target:
private CommitConfig(Config rc) { commitTemplatePath = rc.getString(ConfigConstants.CONFIG_COMMIT_SECTION, null, ConfigConstants.CONFIG_KEY_COMMIT_TEMPLATE); i18nCommitEncoding = rc.getString(ConfigConstants.CONFIG_SECTION_I18N, null, ConfigConstants.CONFIG_KEY_COMMIT_ENCODING); }
Source:
private boolean isFileNameAccepted( String name ) { if ( name != null && name.trim().length() > 0 ) { Set<String> exts = getExtensionsAccepted(); for ( String ext : exts ) { if ( name.endsWith( "." + ext ) ) { return true; } } } return null != name && name.endsWith( "." + METADATA_EXTENSION ); }

Target:
private boolean isFileNameAccepted( String name ) { if ( name != null && name.trim().length() > 0 ) { return getExtensionsAccepted().stream().anyMatch( s -> name.endsWith( "." + s ) ); } return null != name && name.endsWith( "." + METADATA_EXTENSION ); }
Source:
public ValueProcessor<?, ?> getDelegate(Key<?> key) { if (this.tempRegistry != null) { if (this.tempRegistry.valueProcessorMap.containsKey(key)) { return new ValueProcessorDelegate(key, ImmutableList.copyOf(this.tempRegistry.valueProcessorMap.get(key))); } else { return null; } } return this.valueDelegates.get(key); }

Target:
public ValueProcessor<?, ?> getDelegate(Key<?> key) { if (this.tempRegistry != null) { List<ValueProcessor<?, ?>> list = this.tempRegistry.valueProcessorMap.get(key); if (list == null) { return null; } return new ValueProcessorDelegate(key, ImmutableList.copyOf(list)); } return this.valueDelegates.get(key); }
Source:
public void testOverrideBundleAnnotationsInstruction_success() throws Exception { try (Builder b = new Builder()) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.attrs.std.activator"); b.setProperty(Constants.BUNDLE_ACTIVATOR, "test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); b.setProperty("-bundleannotations", "!test.annotationheaders.attrs.std.activator.TypeInVersionedPackage"); b.build(); assertTrue(b.check()); Manifest manifest = b.getJar() .getManifest(); manifest.write(System.out); Attributes mainAttributes = manifest.getMainAttributes(); Header repeated = Header.parseHeader(mainAttributes.getValue(Constants.BUNDLE_ACTIVATOR)); assertThat(repeated).containsOnlyKeys("test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); } }

Target:
public void testOverrideBundleAnnotationsInstruction_success() throws Exception { try (Builder b = new Builder()) { b.addClasspath(IO.getFile("bin_test")); b.setPrivatePackage("test.annotationheaders.attrs.std.activator"); b.setProperty(Constants.BUNDLE_ACTIVATOR, "test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); b.setProperty("-bundleannotations", "!test.annotationheaders.attrs.std.activator.TypeInVersionedPackage,*"); b.build(); assertTrue(b.check()); Manifest manifest = b.getJar() .getManifest(); manifest.write(System.out); Attributes mainAttributes = manifest.getMainAttributes(); Header repeated = Header.parseHeader(mainAttributes.getValue(Constants.BUNDLE_ACTIVATOR)); assertThat(repeated).containsOnlyKeys("test.annotationheaders.attrs.std.activator.TypeInVersionedPackage2"); } }
Source:
public void testAverageSince() { item.setState(new DecimalType(3025)); DateMidnight startStored = new DateMidnight(2003, 1, 1); DateMidnight endStored = new DateMidnight(2012, 1, 1); long storedInterval = endStored.getMillis() - startStored.getMillis(); long recentInterval = DateTime.now().getMillis() - endStored.getMillis(); double expected = (2007.4994 * storedInterval + 2518.5 * recentInterval) / (storedInterval + recentInterval); DecimalType average = PersistenceExtensions.averageSince(item, startStored, "test"); assertEquals(expected, average.doubleValue(), 0.001); }

Target:
public void testAverageSince() { item.setState(new DecimalType(3025)); DateMidnight startStored = new DateMidnight(2003, 1, 1); DateMidnight endStored = new DateMidnight(2012, 1, 1); long storedInterval = endStored.getMillis() - startStored.getMillis(); long recentInterval = DateTime.now().getMillis() - endStored.getMillis(); double expected = (2007.4994 * storedInterval + 2518.5 * recentInterval) / (storedInterval + recentInterval); DecimalType average = PersistenceExtensions.averageSince(item, startStored, "test"); assertEquals(expected, average.doubleValue(), 0.01); }
Source:
public void listenerOnLogout(L2PcInstance player) { if (_currentEvent == null) { if (_state == EventEngineState.REGISTER || _state == EventEngineState.VOTING) { L2GameClient client = player.getClient(); DualBoxProtection.getInstance().removeConnection(client); removeVote(player); unRegisterPlayer(player); return; } } else { try { _currentEvent.listenerOnLogout(player); } catch (Exception e) { LOGGER.warning(EventEngineManager.class.getSimpleName() + ": -> listenerOnLogout() " + e); e.printStackTrace(); } } }

Target:
public void listenerOnLogout(L2PcInstance player) { if (_currentEvent == null) { if (_state == EventEngineState.REGISTER || _state == EventEngineState.VOTING) { DualBoxProtection.getInstance().removeConnection(player.getClient()); removeVote(player); unRegisterPlayer(player); return; } } else { try { _currentEvent.listenerOnLogout(player); } catch (Exception e) { LOGGER.warning(EventEngineManager.class.getSimpleName() + ": -> listenerOnLogout() " + e); e.printStackTrace(); } } }
Source:
public static int getOrdinalFromId(final Activity activity, final Resources res, final int id) { int ordinal = 0; for (NavigationApp app : getNavigationApps(res)) { if (app.isInstalled(activity)) { if (app.getId() == id) { return ordinal; } ordinal++; } } return 0; }

Target:
public static int getOrdinalFromId(final Activity activity, final Resources res, final int id) { int ordinal = 0; for (NavigationApp app : getInstalledNavigationApps(activity, res)) { if (app.getId() == id) { return ordinal; } ordinal++; } return 0; }
Source:
public void writeToLog(String subDir,String orginalFileName, String headerLine,String msg,UserAccountBean userBean) { BufferedWriter bw = null; FileWriter fw = null; boolean isNewFile = false; String logFileName; if(orginalFileName == null) { ; }else { try { int count =1; File logFile; String importFileDir = this.getPersonalLogFileDir(userBean,subDir); logFileName = importFileDir + orginalFileName; logFile = new File(logFileName); if(!logFile.exists()) { logFile.createNewFile(); isNewFile = true; } fw = new FileWriter(logFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); if(isNewFile) { bw.write(headerLine); bw.write("\n"); } if(msg != null) { bw.write(msg); bw.write("\n"); } bw.close(); } catch (Exception e) { e.printStackTrace(); }finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }

Target:
public void writeToLog(String subDir,String orginalFileName, String headerLine,String msg,UserAccountBean userBean) throws OpenClinicaException { BufferedWriter bw = null; FileWriter fw = null; boolean isNewFile = false; String logFileName; if(orginalFileName == null) { logger.info("errorCode.emptyFile -- The file is null "); }else { try { int count =1; File logFile; String importFileDir = this.getPersonalLogFileDir(userBean,subDir); logFileName = importFileDir + orginalFileName; logFile = new File(logFileName); if(!logFile.exists()) { logFile.createNewFile(); isNewFile = true; } fw = new FileWriter(logFile.getAbsoluteFile(), true); bw = new BufferedWriter(fw); if(isNewFile) { bw.write(headerLine); bw.write("\n"); } if(msg != null) { bw.write(msg); bw.write("\n"); } bw.close(); } catch (Exception e) { logger.error("Log File error " + e.getMessage()); throw new OpenClinicaException("Write to log file error", ErrorConstants.ERR_LOG_FILE); }finally { try { if (bw != null) bw.close(); if (fw != null) fw.close(); } catch (IOException ex) { logger.error("Log File error " + ex.getMessage()); throw new OpenClinicaException("Write to log file error", ErrorConstants.ERR_LOG_FILE); } } } }
Source:
public static String getResponseFromServer(final URL constructedUrl, final String encoding) { return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), null, encoding); }

Target:
public static String getResponseFromServer(final URL constructedUrl, final String encoding) { return getResponseFromServer(constructedUrl, HttpsURLConnection.getDefaultHostnameVerifier(), new Properties(), encoding); }
Source:
public void start(BundleContext bc) throws Exception { bc.registerService(DockingPanel.class, new GroovyConsolePanel(), null); }

Target:
public void start(BundleContext bc) throws Exception { LOGGER.info(I18N.tr("Groovy console starting...")); bc.registerService(DockingPanel.class, new GroovyConsolePanel(), null); }
Source:
private void processUpdates(List<ClusterMember> updates, boolean spreadGossip) { if (updates.isEmpty()) { return; } Collection<Address> members = membership.getTrustedOrSuspectedMembers(); failureDetector.setMembers(members); gossipProtocol.setMembers(members); if (spreadGossip) { gossipProtocol.spread(Message.fromData(new ClusterMembershipData(updates, syncGroup))); } for (ClusterMember update : updates) { subject.onNext(update); } for (final ClusterMember member : updates) { LOGGER.debug("Member became {}", member.address(), member.status()); switch (member.status()) { case SUSPECTED: { failureDetector.suspect(member.address()); suspectedMembersSchedule.get(member.id(), new ComputableSuspectedMembersSchedule()); break; } case TRUSTED: { failureDetector.trust(member.address()); ScheduledFuture<?> future = suspectedMembersSchedule.remove(member.id()); if (future != null) { future.cancel(true); } break; } case SHUTDOWN: { suspectedMembersTimer.schedule(new Runnable() { @Override public void run() { LOGGER.debug("Time to remove SHUTDOWN member={} from membership table", member.address()); membership.remove(member.id()); } }, maxShutdownTime, TimeUnit.MILLISECONDS); break; } default: } } }

Target:
private void processUpdates(List<ClusterMember> updates, boolean spreadGossip) { if (updates.isEmpty()) { return; } Collection<Address> members = membership.getTrustedOrSuspectedMembers(); failureDetector.setMembers(members); gossipProtocol.setMembers(members); if (spreadGossip) { gossipProtocol.spread(Message.fromData(new ClusterMembershipData(updates, syncGroup))); } for (ClusterMember update : updates) { subject.onNext(update); } for (final ClusterMember member : updates) { LOGGER.debug("Member became {}", member.address(), member.status()); switch (member.status()) { case SUSPECTED: failureDetector.suspect(member.address()); suspectedMembersSchedule.get(member.id(), new ComputableSuspectedMembersSchedule()); break; case TRUSTED: ScheduledFuture<?> future = suspectedMembersSchedule.remove(member.id()); if (future == null || future.cancel(true)) { failureDetector.trust(member.address()); } break; case SHUTDOWN: executor.schedule(new Runnable() { @Override public void run() { LOGGER.debug("Time to remove SHUTDOWN member={} from membership table", member.address()); membership.remove(member.id()); } }, maxShutdownTime, TimeUnit.MILLISECONDS); break; default: } } }
Source:
private String generateData(){ StringBuilder data = new StringBuilder(); for(int i =0; i< 200; i++) { String uuid = UUID.randomUUID().toString(); Random random = new Random(); int value = random.nextInt(50); data.append(uuid).append(":").append(Integer.toString(value)).append("_"); } return StringUtils.chop(data.toString()); }

Target:
private String generateData() { StringBuilder data = new StringBuilder(); Random random = new Random(); for (int i = 0; i < 200; i++) { String uuid = RandomStringUtils.randomAlphanumeric(10); int value = random.nextInt(50); data.append(uuid).append(":").append(value).append("_"); } return StringUtils.chop(data.toString()); }
Source:
public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { InputStream inputStream = response.getContent(); if (inputStream != null) { content = ByteStreams.toByteArray(response.getContent()); } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { try { charset = response.getContentCharset(); String strContent = getContent(); if (strContent != null) { builder.append(StringUtils.LINE_SEPARATOR).append(strContent); } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } } message = builder.toString(); }

Target:
public Builder(HttpResponse response) { this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); try { InputStream inputStream = response.getContent(); if (inputStream != null) { content = ByteStreams.toByteArray(inputStream); } } catch (IOException exception) { exception.printStackTrace(); } catch (IllegalArgumentException exception) { exception.printStackTrace(); } StringBuilder builder = computeMessageBuffer(response); if (content != null) { try { charset = response.getContentCharset(); String strContent = getContent(); if (strContent != null) { builder.append(StringUtils.LINE_SEPARATOR).append(strContent); } } catch (IOException exception) { builder .append(StringUtils.LINE_SEPARATOR) .append("Content could not be retrieved") .append(StringUtils.LINE_SEPARATOR) .append(exception.getMessage()); } catch (IllegalArgumentException exception) { builder .append(StringUtils.LINE_SEPARATOR) .append("Content could not be retrieved") .append(StringUtils.LINE_SEPARATOR) .append(exception.getMessage()); } } message = builder.toString(); }
Source:
public static CharSequence getRelativeDateTimeString ( Context c, long time, long minResolution, long transitionResolution, int flags ){ CharSequence dateString = ""; if (time > System.currentTimeMillis()){ return DisplayUtils.unixTimeToHumanReadable(time); } else if ((System.currentTimeMillis() - time) < 60 * 1000) { return c.getString(R.string.file_list_seconds_ago); } else { if ( Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB && (System.currentTimeMillis() - time) > 24 * 60 * 60 * 1000 ) { Date date = new Date(time); date.setHours(0); date.setMinutes(0); date.setSeconds(0); dateString = DateUtils.getRelativeDateTimeString( c, date.getTime(), minResolution, transitionResolution, flags ); } else { dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags); } } String[] parts = dateString.toString().split(","); if (parts.length == 2) { if(parts[0].contains(":") && !parts[1].contains(":")) { return parts[1]; } else if(parts[1].contains(":") && !parts[0].contains(":")) { return parts[0]; } } return DisplayUtils.unixTimeToHumanReadable(time); }

Target:
public static CharSequence getRelativeDateTimeString ( Context c, long time, long minResolution, long transitionResolution, int flags ){ CharSequence dateString = ""; if (time > System.currentTimeMillis()){ return DisplayUtils.unixTimeToHumanReadable(time); } else if ((System.currentTimeMillis() - time) < 60 * 1000) { return c.getString(R.string.file_list_seconds_ago); } else { dateString = DateUtils.getRelativeDateTimeString(c, time, minResolution, transitionResolution, flags); } String[] parts = dateString.toString().split(","); if (parts.length == 2) { if (parts[1].contains(":") && !parts[0].contains(":")) { return parts[0]; } else if (parts[0].contains(":") && !parts[1].contains(":")) { return parts[1]; } } return dateString.toString(); }
Source:
public String removeProtocol(String hdfsUrl) { String newUrl = hdfsUrl.replaceAll("/$", ""); if (newUrl.startsWith("hdfs://")) { return "/" + newUrl.replaceAll("^hdfs://", "").split("/", 2)[1]; } else return newUrl; }

Target:
public String removeProtocol(String hdfsUrl) { String newUrl = hdfsUrl.replaceAll("/$", ""); if (newUrl.startsWith("hdfs://")) { return "/" + newUrl.replaceAll("^hdfs://", "").split("/", 2)[1]; } else { return newUrl; } }
Source:
public String toString() { if (parent != null && parent.getResource() instanceof IProject) { return resource.getProjectRelativePath().toString(); } return resource.getName(); }

Target:
public String toString() { if (parent != null && parent.getResource() instanceof IProject) return resource.getProjectRelativePath().toString(); return resource.getName(); }
Source:
public void peekOneMessage() { final int numberOfEvents = 1; String connectionString = System.getenv("AZURE_SERVICEBUS_CONNECTION_STRING") + ";EntityPath=hemant-test1"; log(connectionString); ServiceBusReceiverAsyncClient queueReceiverAsyncClient = new ServiceBusClientBuilder() .connectionString(connectionString) .scheduler(Schedulers.parallel()) .buildAsyncReceiverClient(); queueReceiverAsyncClient.peek() .doOnNext(receivedMessage -> { System.out.println("!!!!!! doOnNext Got message from queue: " + receivedMessage.getBodyAsString()); }) .subscribe(receivedMessage -> { System.out.println("!!!!!! subscribe Got message from queue: " + receivedMessage.getBodyAsString()); }, error -> { System.err.println("!!!!!! Error occurred while consuming messages: " + error); }); try { Thread.sleep(90000); } catch (Exception ex) { } System.out.println("!!!!!! Completed."); }

Target:
public void peekOneMessage() { final int numberOfEvents = 1; StepVerifier.create(consumer.peek()) .then(() -> sendMessages(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, times(1)); }