auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void readsInboxPeriodically() throws Exception { final GreenMail mail = new GreenMail(ServerSetupTest.POP3); mail.start(); final ServerSetup setup = mail.getPop3().getServerSetup(); final String mailUser = "to"; final String from = "from@localhost.com"; final String to = "to@localhost.com"; final String password = "soooosecret"; final String subject = GreenMailUtil.random(); final String body = GreenMailUtil.random(); final GreenMailUser user = mail.setUser(mailUser, password); new EmCatch( new EmCatch.Action() { @Override public void run(final Message msg) { MatcherAssert.assertThat(msg, Matchers.notNullValue()); try { MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo(subject) ); MatcherAssert.assertThat( msg.getFrom()[0].toString(), Matchers.equalTo(from) ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(to) ); } catch (final MessagingException ex) { throw new IllegalStateException(ex); } } }, mailUser, password, setup.getBindAddress(), setup.getPort(), 500L ); final MimeMessage message = GreenMailUtil.createTextEmail( to, from, subject, body, setup ); user.deliver(message); MatcherAssert.assertThat( mail.getReceivedMessages().length, Matchers.equalTo(1) ); Thread.sleep(1000); mail.stop(); }

Target:
public void readsInboxPeriodically() throws Exception { final Ports ports = new Ports(); final GreenMail mail = new GreenMail( new ServerSetup(ports.allocate(), null, "pop3") ); mail.start(); final ServerSetup setup = mail.getPop3().getServerSetup(); final String mailUser = "to"; final String from = "from@localhost.com"; final String to = "to@localhost.com"; final String password = "soooosecret"; final String subject = GreenMailUtil.random(); final String body = GreenMailUtil.random(); final GreenMailUser user = mail.setUser(mailUser, password); new EmCatch( new EmCatch.Action() { @Override public void run(final Message msg) { MatcherAssert.assertThat(msg, Matchers.notNullValue()); try { MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo(subject) ); MatcherAssert.assertThat( msg.getFrom()[0].toString(), Matchers.equalTo(from) ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(to) ); } catch (final MessagingException ex) { throw new IllegalStateException(ex); } } }, mailUser, password, setup.getBindAddress(), setup.getPort(), 500L ); final MimeMessage message = GreenMailUtil.createTextEmail( to, from, subject, body, setup ); user.deliver(message); MatcherAssert.assertThat( mail.getReceivedMessages().length, Matchers.equalTo(1) ); Thread.sleep(1000); ports.release(setup.getPort()); mail.stop(); }
Source:
public String toString() { return new StringBuilder() .append("EvaluatedGatewayRefundRequest[\n") .append("transactionId: ") .append(transactionId) .append("\nrefundExternalId: ") .append(refundExternalId) .append("\nchargeExternalId:") .append("]") .toString(); }

Target:
public String toString() { return new StringBuilder() .append("RefundGatewayRequest[\n") .append("transactionId: ") .append(transactionId) .append("\nrefundExternalId: ") .append(refundExternalId) .append("]") .toString(); }
Source:
private EventTypeStatistics validateStatisticsUpdate( final EventTypeStatistics existing, final EventTypeStatistics newStatistics) throws InvalidEventTypeException { if (existing != null && newStatistics == null) { return existing; } if (existing == null && newStatistics == null) { return null; } final int newMaxPartitions = Math.max(newStatistics.getReadParallelism(), newStatistics.getWriteParallelism()); final int oldMaxPartitions = Math.max(existing.getReadParallelism(), existing.getWriteParallelism()); if (newMaxPartitions > nakadiSettings.getMaxTopicPartitionCount()) { throw new InvalidEventTypeException("Number of partitions should not be more than " + nakadiSettings.getMaxTopicPartitionCount()); } if (newMaxPartitions < oldMaxPartitions) { throw new InvalidEventTypeException("Read and write parallelism should be greater " + "than existing values."); } if (newMaxPartitions == oldMaxPartitions) { if ((existing.getReadParallelism() != newStatistics.getReadParallelism()) || (existing.getWriteParallelism() != newStatistics.getWriteParallelism())) { throw new InvalidEventTypeException("Read and write parallelism can be changed only to change" + "the number of partition (max of read and write parallelism)"); } } return newStatistics; }

Target:
private EventTypeStatistics validateStatisticsUpdate( final EventTypeStatistics existing, final EventTypeStatistics newStatistics) throws InvalidEventTypeException { if (existing != null && newStatistics == null) { return existing; } if ((existing == null && newStatistics == null) || (existing.equals(newStatistics))) { return existing; } final int newMaxPartitions = Math.max(newStatistics.getReadParallelism(), newStatistics.getWriteParallelism()); final int oldMaxPartitions = Math.max(existing.getReadParallelism(), existing.getWriteParallelism()); if (newMaxPartitions > nakadiSettings.getMaxTopicPartitionCount()) { throw new InvalidEventTypeException("Number of partitions should not be more than " + nakadiSettings.getMaxTopicPartitionCount()); } if (newMaxPartitions < oldMaxPartitions) { throw new InvalidEventTypeException("Read and write parallelism should be greater " + "than existing values."); } if (newMaxPartitions == oldMaxPartitions) { if ((existing.getReadParallelism() != newStatistics.getReadParallelism()) || (existing.getWriteParallelism() != newStatistics.getWriteParallelism())) { throw new InvalidEventTypeException("Read and write parallelism can be changed only to change" + "the number of partition (max of read and write parallelism)"); } } return newStatistics; }
Source:
public InfluxDBImpl(final String url, final String username, final String password, final OkHttpClient.Builder okHttpBuilder, final Retrofit.Builder retrofitBuilder, final ResponseFormat responseFormat) { this.messagePack = ResponseFormat.MSGPACK.equals(responseFormat); this.hostAddress = parseHostAddress(url); this.loggingInterceptor = new HttpLoggingInterceptor(); setLogLevel(LOG_LEVEL); this.gzipRequestInterceptor = new GzipRequestInterceptor(); OkHttpClient.Builder clonedBuilder = okHttpBuilder.build().newBuilder(); clonedBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor). addInterceptor(new BasicAuthInterceptor(username, password)); Factory converterFactory = null; switch (responseFormat) { case MSGPACK: clonedBuilder.addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("Accept", APPLICATION_MSGPACK).build(); return chain.proceed(request); }); converterFactory = MessagePackConverterFactory.create(); chunkProccesor = new MessagePackChunkProccesor(); break; case JSON: default: converterFactory = MoshiConverterFactory.create(); Moshi moshi = new Moshi.Builder().build(); JsonAdapter<QueryResult> adapter = moshi.adapter(QueryResult.class); chunkProccesor = new JSONChunkProccesor(adapter); break; } this.retrofit = retrofitBuilder.baseUrl(url).client( clonedBuilder.build()).addConverterFactory(converterFactory).build(); this.influxDBService = this.retrofit.create(InfluxDBService.class); }

Target:
public InfluxDBImpl(final String url, final String username, final String password, final OkHttpClient.Builder okHttpBuilder, final Retrofit.Builder retrofitBuilder, final ResponseFormat responseFormat) { this.messagePack = ResponseFormat.MSGPACK.equals(responseFormat); this.hostAddress = parseHostAddress(url); this.loggingInterceptor = new HttpLoggingInterceptor(); setLogLevel(LOG_LEVEL); this.gzipRequestInterceptor = new GzipRequestInterceptor(); OkHttpClient.Builder clonedOkHttpBuilder = okHttpBuilder.build().newBuilder(); clonedOkHttpBuilder.addInterceptor(loggingInterceptor).addInterceptor(gzipRequestInterceptor). addInterceptor(new BasicAuthInterceptor(username, password)); Factory converterFactory = null; switch (responseFormat) { case MSGPACK: clonedOkHttpBuilder.addInterceptor(chain -> { Request request = chain.request().newBuilder().addHeader("Accept", APPLICATION_MSGPACK).build(); return chain.proceed(request); }); converterFactory = MessagePackConverterFactory.create(); chunkProccesor = new MessagePackChunkProccesor(); break; case JSON: default: converterFactory = MoshiConverterFactory.create(); Moshi moshi = new Moshi.Builder().build(); JsonAdapter<QueryResult> adapter = moshi.adapter(QueryResult.class); chunkProccesor = new JSONChunkProccesor(adapter); break; } Retrofit.Builder clonedRetrofitBuilder = retrofitBuilder.baseUrl(url).build().newBuilder(); this.retrofit = clonedRetrofitBuilder.client(clonedOkHttpBuilder.build()) .addConverterFactory(converterFactory).build(); this.influxDBService = this.retrofit.create(InfluxDBService.class); }
Source:
public Page<RelationshipRest> findByLabel(@Parameter(value = "label", required = true) String label, @Parameter(value = "dso", required = false) UUID dsoId, Pageable pageable) throws SQLException { Context context = obtainContext(); List<RelationshipType> relationshipTypeList = relationshipTypeService.findByLeftwardOrRightwardTypeName(context, label); List<Relationship> relationships = new LinkedList<>(); int total = 0; if (dsoId != null) { Item item = itemService.find(context, dsoId); if (item == null) { throw new ResourceNotFoundException("The request DSO with id: " + dsoId + " was not found"); } for (RelationshipType relationshipType : relationshipTypeList) { total = relationshipService.countByItemAndRelationshipType(context, relationshipType, item); relationships.addAll(relationshipService.findByItemAndRelationshipType(context, item, relationshipType, pageable.getPageSize(), pageable.getOffset())); } } else { for (RelationshipType relationshipType : relationshipTypeList) { total = relationshipService.countByRelationshipType(context, relationshipType); relationships.addAll(relationshipService.findByRelationshipType(context, relationshipType, pageable.getPageSize(), pageable.getOffset())); } } Page<RelationshipRest> page = new PageImpl<Relationship>(relationships, pageable, total).map(relationshipConverter);; return page; }

Target:
public Page<RelationshipRest> findByLabel(@Parameter(value = "label", required = true) String label, @Parameter(value = "dso", required = false) UUID dsoId, Pageable pageable) throws SQLException { Context context = obtainContext(); List<RelationshipType> relationshipTypeList = relationshipTypeService.findByLeftwardOrRightwardTypeName(context, label); List<Relationship> relationships = new LinkedList<>(); int total = 0; if (dsoId != null) { Item item = itemService.find(context, dsoId); if (item == null) { throw new ResourceNotFoundException("The request DSO with id: " + dsoId + " was not found"); } for (RelationshipType relationshipType : relationshipTypeList) { total = relationshipService.countByItemAndRelationshipType(context, item, relationshipType); relationships.addAll(relationshipService.findByItemAndRelationshipType(context, item, relationshipType, pageable.getPageSize(), pageable.getOffset())); } } else { for (RelationshipType relationshipType : relationshipTypeList) { total = relationshipService.countByRelationshipType(context, relationshipType); relationships.addAll(relationshipService.findByRelationshipType(context, relationshipType, pageable.getPageSize(), pageable.getOffset())); } } Page<RelationshipRest> page = new PageImpl<Relationship>(relationships, pageable, total).map(relationshipConverter); return page; }
Source:
private String buildMetric(String metric) { final String sanitized = sanitize(metric); if (Strings.isNullOrEmpty(namespacePrefix)) { return sanitized; } else { return StringUtils.format("%s.%s", sanitize(namespacePrefix), sanitized); } }

Target:
private String buildMetric(String metric) { final String sanitized = sanitize(metric); if (namespacePrefix == null) { return sanitized; } else { return StringUtils.format("%s.%s", sanitize(namespacePrefix), sanitized); } }
Source:
public RootPredicate<BooleanExpr> getRootPredicate(String entityType) { if (propertyHelper.getEntityNamesResolver().getClassFromName(entityType) == null) { throw new IllegalStateException("Unknown entity name " + entityType); } return new FilterRootPredicate(); }

Target:
public RootPredicate<BooleanExpr> getRootPredicate(String entityType) { if (propertyHelper.getEntityNamesResolver().getClassFromName(entityType) == null) { throw log.getUnknownEntity(entityType); } return new FilterRootPredicate(); }
Source:
private static long getOperationId(int transactionId, long logId) { DataUtils.checkArgument(transactionId >= 0 && transactionId < (1 << (64 - LOG_ID_BITS)), "Transaction id out of range: {0}", transactionId); DataUtils.checkArgument(logId >= 0 && logId <= LOG_ID_MASK, "Transaction log id out of range: {0}", logId); return ((long) transactionId << LOG_ID_BITS) | logId; }

Target:
static long getOperationId(int transactionId, long logId) { DataUtils.checkArgument(transactionId >= 0 && transactionId < (1 << (64 - LOG_ID_BITS)), "Transaction id out of range: {0}", transactionId); DataUtils.checkArgument(logId >= 0 && logId <= LOG_ID_MASK, "Transaction log id out of range: {0}", logId); return ((long) transactionId << LOG_ID_BITS) | logId; }
Source:
public void setup() { when(review1.getUrl()).thenReturn(reviewUrl1); when(review2.getUrl()).thenReturn(reviewUrl2); when(reviewNoTask.getUrl()).thenReturn(reviewUrlNoTask); when(task1.getUrl()).thenReturn(taskUrl1); when(task2.getUrl()).thenReturn(taskUrl2); when(task1.getTaskId()).thenReturn("1"); when(task1.getTaskId()).thenReturn("2"); when(review1.getTaskId()).thenReturn("3"); when(review2.getTaskId()).thenReturn("4"); when(reviewNoTask.getTaskId()).thenReturn("5"); }

Target:
public void setup() { review1 = new TaskTask("reviewKind", reviewUrl1, "3"); review1.setUrl(reviewUrl1); review2 = new TaskTask("reviewKind", reviewUrl2, "4"); review2.setUrl(reviewUrl2); reviewNoTask = new TaskTask("reviewKind", reviewUrlNoTask, "5"); reviewNoTask.setUrl(reviewUrlNoTask); task1 = new TaskTask("reviewKind", taskUrl1, "1"); task1.setUrl(taskUrl1); task2 = new TaskTask("reviewKind", taskUrl2, "2"); task2.setUrl(taskUrl2); }
Source:
public void init(FilterConfig filterConfig) throws ServletException { boolean enabled = loadBooleanParam("enabled", filterConfig, true); int requestDurationThresholdInSeconds = loadIntParam("request-duration-threshold-in-seconds", filterConfig, 20); int timeBucketCapacityInSeconds = loadIntParam("time-bucket-capacity-in-seconds", filterConfig, 40); int timeBucketRefillAmountInSeconds = loadIntParam("time-bucket-refill-amount-in-seconds", filterConfig, 1000000); int timeBucketRefillPeriodInMinutes = loadIntParam("time-bucket-refill-period-in-minutes", filterConfig, 1); int errorBucketCapacity = loadIntParam("error-bucket-capacity", filterConfig, 10); int errorBucketRefillAmount = loadIntParam("error-bucket-refill-amount", filterConfig, 100); int errorBucketRefillPeriodInMinutes = loadIntParam("error-bucket-refill-period-in-minutes", filterConfig, 1); int maxStateSize = loadIntParam("max-state-size", filterConfig, 10000); int stateExpirationInSeconds = loadIntParam("state-expiration-in-seconds", filterConfig, 15); this.enabled = enabled; throttler = new Throttler<>( Duration.of(requestDurationThresholdInSeconds, SECONDS), new UserAgentIpAddressBucketting(), createThrottlingState( timeBucketCapacityInSeconds, timeBucketRefillAmountInSeconds, timeBucketRefillPeriodInMinutes, errorBucketCapacity, errorBucketRefillAmount, errorBucketRefillPeriodInMinutes), CacheBuilder.newBuilder() .maximumSize(maxStateSize) .expireAfterAccess(stateExpirationInSeconds, TimeUnit.MINUTES) .build()); }

Target:
public void init(FilterConfig filterConfig) throws ServletException { int requestDurationThresholdInSeconds = loadIntParam("request-duration-threshold-in-seconds", filterConfig, 10); int timeBucketCapacityInSeconds = loadIntParam("time-bucket-capacity-in-seconds", filterConfig, 60); int timeBucketRefillAmountInSeconds = loadIntParam("time-bucket-refill-amount-in-seconds", filterConfig, 60); int timeBucketRefillPeriodInMinutes = loadIntParam("time-bucket-refill-period-in-minutes", filterConfig, 1); int errorBucketCapacity = loadIntParam("error-bucket-capacity", filterConfig, 10); int errorBucketRefillAmount = loadIntParam("error-bucket-refill-amount", filterConfig, 100); int errorBucketRefillPeriodInMinutes = loadIntParam("error-bucket-refill-period-in-minutes", filterConfig, 1); int maxStateSize = loadIntParam("max-state-size", filterConfig, 10000); int stateExpirationInMinutes = loadIntParam("state-expiration-in-minutes", filterConfig, 15); this.enabled = loadBooleanParam("enabled", filterConfig, true); throttler = new Throttler<>( Duration.of(requestDurationThresholdInSeconds, SECONDS), new UserAgentIpAddressBucketing(), createThrottlingState( timeBucketCapacityInSeconds, timeBucketRefillAmountInSeconds, timeBucketRefillPeriodInMinutes, errorBucketCapacity, errorBucketRefillAmount, errorBucketRefillPeriodInMinutes), CacheBuilder.newBuilder() .maximumSize(maxStateSize) .expireAfterAccess(stateExpirationInMinutes, TimeUnit.MINUTES) .build()); }
Source:
public void testStructureContainment() { final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("structure-containtment.dmn", this.getClass()); final DMNModel dmnModel = runtime.getModel("<LINK_0>", "structure-containtment"); assertThat(dmnModel, notNullValue()); assertThat(DMNRuntimeUtil.formatMessages(dmnModel.getMessages()), dmnModel.hasErrors(), is(false)); final DMNContext context = DMNFactory.newContext(); context.set("an employee", prototype(entry("age", 50))); final DMNResult dmnResult = runtime.evaluateAll(dmnModel, context); assertThat(DMNRuntimeUtil.formatMessages(dmnResult.getMessages()), dmnResult.hasErrors(), is(false)); final DMNContext result = dmnResult.getContext(); assertThat(result.get("is there"), is("true")); }

Target:
public void testStructureContainment() { final DMNRuntime runtime = DMNRuntimeUtil.createRuntime("structure-containtment.dmn", this.getClass()); final DMNModel dmnModel = runtime.getModel("<LINK_0>", "structure-containtment"); assertThat(dmnModel, notNullValue()); assertThat(DMNRuntimeUtil.formatMessages(dmnModel.getMessages()), dmnModel.hasErrors(), is(false)); final DMNContext context = DMNFactory.newContext(); context.set("an employee", prototype(entry("age", BigDecimal.valueOf(50)))); final DMNResult dmnResult = runtime.evaluateAll(dmnModel, context); assertThat(DMNRuntimeUtil.formatMessages(dmnResult.getMessages()), dmnResult.hasErrors(), is(false)); final DMNContext result = dmnResult.getContext(); assertThat(result.get("is there"), is(true)); }
Source:
private Entity event(Entity entity) { String kind = entity.getKey().getKind(); final EventTypes eventTypes = EventUtils .getEventAndActionType(kind); if (eventTypes != null) { Map<String, Object> event = updateOrCreateEvent(entity, eventTypes); try { return EventUtils.createEventLogEntity(event, new Date()); } catch (IOException e) { throw new RuntimeException(e); } } return entity; }

Target:
private Entity event(Entity entity) { String kind = entity.getKey().getKind(); final EventTypes eventTypes = EventUtils .getEventAndActionType(kind); if (eventTypes == null) { return null; } else { Map<String, Object> event = updateOrCreateEvent(entity, eventTypes); try { return EventUtils.createEventLogEntity(event, new Date()); } catch (IOException e) { throw new RuntimeException(e); } } }
Source:
private Object readResolve() { if (loggers == null) { loggers = new ArrayList<>(); } if (!targets.isEmpty()) { loggers.addAll(targets.getView()); } if (!loggers.isEmpty()) { targets.addAll(loggers); } return this; }

Target:
private Object readResolve() { if (loggers == null) { loggers = new ArrayList<>(); } if (targets != null && !targets.isEmpty()) { loggers.addAll(targets.getView()); } if (!loggers.isEmpty()) { targets.addAll(loggers); } return this; }
Source:
public String getTranscoding() { if (getTranscodingClassification() == TranscodingClassification.TRANSCODED_TO_IMAGE) { if (width == null) return "image"; else if (width <= 199) return "image_0_199"; else if (width >= 200 && width <= 399 ) return "image_200_399"; else if (width >= 400 && width <= 599 ) return "image_400_599"; else if (width >= 600 && width <= 799 ) return "image_600_799"; else if (width >= 800 && width <= 999 ) return "image_800_999"; else if (width >= 1000) return "image_1000"; } else if (getTranscodingClassification() == TranscodingClassification.TRANSCODED_TO_MOVIE) { if (height == null) return "movie"; else if (height <= 239) return "movie_0_239"; else if (height >= 240 || height <= 479 ) return "movie_240_479"; else if (height >= 480 ) return "movie_480"; } else if (getTranscodingClassification() == TranscodingClassification.ORIGINAL) { return "original"; } else if (getTranscodingClassification() == TranscodingClassification.TRANSCODED_TO_AUDIO) { return "audio"; } return null; }

Target:
public String getTranscoding() { if (transcodingClassification == TranscodingClassification.TRANSCODED_TO_IMAGE) { if (width == null) return "image"; else if (width <= 199) return "image_0_199"; else if (width >= 200 && width <= 399 ) return "image_200_399"; else if (width >= 400 && width <= 599 ) return "image_400_599"; else if (width >= 600 && width <= 799 ) return "image_600_799"; else if (width >= 800 && width <= 999 ) return "image_800_999"; else if (width >= 1000) return "image_1000"; } else if (transcodingClassification == TranscodingClassification.TRANSCODED_TO_MOVIE) { if (height == null) return "movie"; else if (height <= 239) return "movie_0_239"; else if (height >= 240 || height <= 479 ) return "movie_240_479"; else if (height >= 480 ) return "movie_480"; } else if (transcodingClassification == TranscodingClassification.ORIGINAL) { return "original"; } else if (transcodingClassification == TranscodingClassification.TRANSCODED_TO_AUDIO) { return "audio"; } return null; }
Source:
CancellationTokenRegistration register(Runnable action) { CancellationTokenRegistration ctr; synchronized (lock) { throwIfClosed(); ctr = new CancellationTokenRegistration(this, action); if (cancellationRequested) { action.run(); } else { registrations.add(ctr); } } return ctr; }

Target:
CancellationTokenRegistration register(Runnable action) { CancellationTokenRegistration ctr; synchronized (lock) { throwIfClosed(); ctr = new CancellationTokenRegistration(this, action); if (cancellationRequested) { ctr.runAction(); } else { registrations.add(ctr); } } return ctr; }
Source:
private void setTableManipulation(JdbcStringBasedStoreConfigurationBuilder storeBuilder) { buildTableManipulation(storeBuilder.table()); }

Target:
protected void setTableManipulation(JdbcStringBasedStoreConfigurationBuilder storeBuilder) { buildTableManipulation(storeBuilder.table()); }
Source:
private void setNodeIdForVertex(GraphMLVertex vertex) { if (Objects.isNull(vertex)) { return; } if (Objects.isNull(vertex.getNodeID())) { String foreignSource = (String) vertex.getProperties().get(GraphMLProperties.FOREIGN_SOURCE); String foreignId = (String) vertex.getProperties().get(GraphMLProperties.FOREIGN_ID); if (!Strings.isNullOrEmpty(foreignSource) && !Strings.isNullOrEmpty(foreignId)) { OnmsNode onmsNode = m_serviceAccessor.getNodeDao().findByForeignId(foreignSource, foreignId); if (onmsNode != null) { vertex.setNodeID(onmsNode.getId()); } else { LOG.warn("no node found for the given foreignSource ({}) and foreignId ({})", foreignSource, foreignId); } } else { LOG.warn("nodeId is null, foreignSource ({}) and foreignId ({}) must be set both", foreignSource, foreignId); } } }

Target:
private void setNodeIdForVertex(GraphMLVertex vertex) { if (vertex == null) { return; } if (vertex.getNodeID() == null) { String foreignSource = (String) vertex.getProperties().get(GraphMLProperties.FOREIGN_SOURCE); String foreignId = (String) vertex.getProperties().get(GraphMLProperties.FOREIGN_ID); if (!Strings.isNullOrEmpty(foreignSource) && !Strings.isNullOrEmpty(foreignId)) { OnmsNode onmsNode = m_serviceAccessor.getNodeDao().findByForeignId(foreignSource, foreignId); if (onmsNode != null) { vertex.setNodeID(onmsNode.getId()); } else { LOG.warn("No node found for the given foreignSource ({}) and foreignId ({}).", foreignSource, foreignId); } } else { LOG.warn("The given nodeId is null. In order to resolve the nodeId a foreignSource ({}) and foreignId ({}) must be set.", foreignSource, foreignId); } } }
Source:
public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); writeTrackingFile(); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess":"")); } }

Target:
public void onMessage(Message message) { try { URLNotification notification = URLNotificationJSONConverter.parseJSON(new ByteArrayInputStream(message.getData())); receiveNotification(notification); if (!exceptionThrown || updateSequenceAfterException) { sequence = message.getSequence(); writeTrackingFile(); } } catch (Exception e) { exceptionThrown = true; LOGGER.log(Level.WARNING, "[" + getName() + "] exception handling NATSStreaming message." + (!updateSequenceAfterException ? " Will no longer update sequence; restart PDL to reprocess.":"") + " Stack Trace: " + e); LOGGER.log(Level.FINE, "[" + getName() + "] Message: " + message.getData()); } }
Source:
private VariantContext calculateGenotypes(VariantContext vc){ final VariantContext.Type type = vc.getType(); final GenotypeLikelihoodsCalculationModel model; if ( type == VariantContext.Type.INDEL ) { model = GenotypeLikelihoodsCalculationModel.INDEL; } else { model = GenotypeLikelihoodsCalculationModel.SNP; } return genotypingEngine.calculateGenotypes(vc, model, null); }

Target:
private VariantContext calculateGenotypes(VariantContext vc){ final GenotypeLikelihoodsCalculationModel model = vc.getType() == VariantContext.Type.INDEL ? GenotypeLikelihoodsCalculationModel.INDEL : GenotypeLikelihoodsCalculationModel.SNP; return genotypingEngine.calculateGenotypes(vc, model, null); }
Source:
public void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution) { if(this.relationships.containsKey(taskExecution.getExecutionId())) { this.relationships.get(taskExecution.getExecutionId()).add(jobExecution.getId()); } else { TreeSet<Long> jobExecutionIds = new TreeSet<>(); jobExecutionIds.add(jobExecution.getId()); this.relationships.put(taskExecution.getExecutionId(), jobExecutionIds); } }

Target:
public void saveRelationship(TaskExecution taskExecution, JobExecution jobExecution) { Assert.notNull(taskExecution, "A taskExecution is required"); Assert.notNull(jobExecution, "A jobExecution is required"); if(this.relationships.containsKey(taskExecution.getExecutionId())) { this.relationships.get(taskExecution.getExecutionId()).add(jobExecution.getId()); } else { TreeSet<Long> jobExecutionIds = new TreeSet<>(); jobExecutionIds.add(jobExecution.getId()); this.relationships.put(taskExecution.getExecutionId(), jobExecutionIds); } }
Source:
public DefaultRepositoryMetadata(Class<?> repositoryInterface) { super(repositoryInterface); Assert.isTrue(Repository.class.isAssignableFrom(repositoryInterface), MUST_BE_A_REPOSITORY); Class<? extends Serializable> idType = resolveIdType(repositoryInterface); Class<?> domainType = resolveDomainType(repositoryInterface); Assert.notNull(idType, "IdType must not be null!"); Assert.notNull(domainType, "DomainType must not be null!"); this.idType = idType; this.domainType = domainType; }

Target:
public DefaultRepositoryMetadata(Class<?> repositoryInterface) { super(repositoryInterface); Assert.isTrue(Repository.class.isAssignableFrom(repositoryInterface), MUST_BE_A_REPOSITORY); this.idType = resolveIdType(repositoryInterface); this.domainType = resolveDomainType(repositoryInterface); }
Source:
public static LocalFile cleanLfsBlob(Repository db, InputStream originalContent) throws IOException { LocalFile buffer = new TemporaryBuffer.LocalFile(null); CleanFilter f = new CleanFilter(db, originalContent, buffer); while (f.run() != -1) { } return buffer; }

Target:
public static TemporaryBuffer cleanLfsBlob(Repository db, InputStream originalContent) throws IOException { LocalFile buffer = new TemporaryBuffer.LocalFile(null); CleanFilter f = new CleanFilter(db, originalContent, buffer); try { while (f.run() != -1) { } } catch (IOException e) { buffer.close(); throw e; } return buffer; }
Source:
public static Map<Long, Map<String, MetricNameDto>> getMappedMetricDtos(Collection<MetricNameDto> metricNameDtos) { Map<Long, Map<String, MetricNameDto>> taskIdMap = new HashMap<Long, Map<String, MetricNameDto>>(); for (MetricNameDto metricName : metricNameDtos) { Set<Long> ids = metricName.getTaskIds(); for (Long id : ids) { if (taskIdMap.get(id) == null) { taskIdMap.put(id, new HashMap<String, MetricNameDto>()); } Map<String, MetricNameDto> metricIdMap = taskIdMap.get(id); if (metricIdMap.get(metricName.getMetricName()) == null) { metricIdMap.put(metricName.getMetricName(), metricName); } else { throw new IllegalStateException(metricName.toString() + " already in Map"); } } } return taskIdMap; }

Target:
public static Map<Long, Map<String, MetricNameDto>> getMappedMetricDtos(Collection<MetricNameDto> metricNameDtos) { Map<Long, Map<String, MetricNameDto>> taskIdMap = new HashMap<Long, Map<String, MetricNameDto>>(); for (MetricNameDto metricName : metricNameDtos) { Set<Long> ids = metricName.getTaskIds(); for (Long id : ids) { if (!taskIdMap.containsKey(id)) { taskIdMap.put(id, new HashMap<String, MetricNameDto>()); } Map<String, MetricNameDto> metricIdMap = taskIdMap.get(id); if (!metricIdMap.containsKey(metricName.getMetricName())) { metricIdMap.put(metricName.getMetricName(), metricName); } else { throw new IllegalStateException(metricName.toString() + " already in Map"); } } } return taskIdMap; }
Source:
private void parseMetadata(TraceEventField field) { Map<@NonNull String, @NonNull Object> args = field.getArgs(); String name = field.getName(); if (args == null) { return; } if (name.equals(PROCESS_NAME)) { String procName = (String) args.get(NAME_ARG); fPidNames.put(field.getPid(), procName); if (procName != null) { fProperties.put("pid-" + field.getPid(), procName); } } else if (name.equals(PROCESS_LABELS)) { String procLabels = (String) args.get(LABELS); if (procLabels != null) { fProperties.put("pidLabel-" + field.getPid(), procLabels); } } else if (name.equals(PROCESS_SORT_INDEX)) { String sortIndex = (String) args.get(SORT_INDEX); if (sortIndex != null) { fProperties.put(name + '-' + field.getPid(), sortIndex); } } else if (name.equals(THREAD_NAME)) { String threadName = (String) args.get(NAME_ARG); fTidNames.put(field.getTid(), threadName); if (threadName != null) { fProperties.put("tid-" + field.getTid(), threadName); } } else if (name.equals(THREAD_SORT_INDEX)) { String sortIndex = (String) args.get(SORT_INDEX); if (sortIndex != null) { fProperties.put(name + '-' + field.getTid(), sortIndex); } } else { fProperties.put(name, String.valueOf(args)); } }

Target:
private void parseMetadata(TraceEventField field) { Map<@NonNull String, @NonNull Object> args = field.getArgs(); String name = field.getName(); if (args == null) { return; } switch (name) { case PROCESS_NAME: String procName = (String) args.get(NAME_ARG); fPidNames.put(field.getPid(), procName); if (procName != null) { fProperties.put(PID_PREFIX + field.getPid(), procName); } break; case PROCESS_LABELS: String procLabels = (String) args.get(LABELS); if (procLabels != null) { fProperties.put(PID_LABEL_PREFIX + field.getPid(), procLabels); } break; case PROCESS_SORT_INDEX: String sortIndex = (String) args.get(SORT_INDEX); if (sortIndex != null) { fProperties.put(name + '-' + field.getPid(), sortIndex); } break; case THREAD_NAME: String threadName = (String) args.get(NAME_ARG); fTidNames.put(field.getTid(), threadName); if (threadName != null) { fProperties.put(TID_PREFIX + field.getTid(), threadName); } break; case THREAD_SORT_INDEX: sortIndex = (String) args.get(SORT_INDEX); if (sortIndex != null) { fProperties.put(name + '-' + field.getTid(), sortIndex); } break; default: fProperties.put(name, String.valueOf(args)); break; } }
Source:
static private ByteBuffer copyByteBufferData(ByteBuffer buffer) { if (!buffer.isDirect() && !buffer.hasArray()) { int pos = buffer.position(); ByteBuffer bb = ByteBuffer.allocate(buffer.capacity()).put(buffer); bb.position(pos); bb.limit(buffer.limit()); buffer.position(pos); return bb; } return buffer; }

Target:
static private ByteBuffer copyByteBufferData(ByteBuffer buffer) { if(!buffer.isDirect() && !buffer.hasArray()) { int pos = buffer.position(); ByteBuffer bb = ByteBuffer.allocate(buffer.remaining()).put(buffer); bb.position(0); buffer.position(pos); return bb; } return buffer; }
Source:
public DerivedStringProperty(String name, String defaultValue) { super(name, defaultValue); deriveAndSet(); }

Target:
public DerivedStringProperty(String name, String defaultValue) { delegate = DynamicPropertyFactory.getInstance().getStringProperty(name, defaultValue); deriveAndSet(); delegate.addCallback(new Runnable() { public void run() { propertyChangedInternal(); } }); }
Source:
public static int getAutoplayType(@NonNull final Context context) { final String defaultType = context.getString(R.string.autoplay_wifi_key); final String always = context.getString(R.string.autoplay_always_key); final String never = context.getString(R.string.autoplay_never_key); final String type = getAutoplayType(context, defaultType); if (type.equals(always)) { return AUTOPLAY_TYPE_ALWAYS; } else if (type.equals(never)) { return AUTOPLAY_TYPE_NEVER; } else { return AUTOPLAY_TYPE_WIFI; } }

Target:
public static int getAutoplayType(@NonNull final Context context) { final String type = getAutoplayType(context, context.getString(R.string.autoplay_wifi_key)); if (type.equals(context.getString(R.string.autoplay_always_key))) { return AUTOPLAY_TYPE_ALWAYS; } else if (type.equals(context.getString(R.string.autoplay_never_key))) { return AUTOPLAY_TYPE_NEVER; } else { return AUTOPLAY_TYPE_WIFI; } }
Source:
private void handleAddMetadata(Object arg) { if (arg instanceof List) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) arg; if (values.size() == 3 && values.get(METADATA_SECTION) instanceof String && values.get(METADATA_KEY) instanceof String) { if (values.get(METADATA_VALUE) instanceof String) { addMetadataString((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), (String) values.get(METADATA_VALUE)); } else if (values.get(METADATA_VALUE) instanceof Boolean) { addMetadataBoolean((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), (Boolean) values.get(METADATA_VALUE)); } else if (values.get(METADATA_VALUE) instanceof Number) { addMetadataDouble((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), ((Number) values.get(METADATA_VALUE)).doubleValue()); } } else if (values.size() == 2) { removeMetadata((String)values.get(METADATA_SECTION), (String)values.get(METADATA_KEY)); return; } } warn("ADD_METADATA object is invalid: " + arg); }

Target:
private void handleAddMetadata(Object arg) { if (arg instanceof List) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) arg; if (values.size() == 3 && values.get(METADATA_SECTION) instanceof String && values.get(METADATA_KEY) instanceof String) { if (values.get(METADATA_VALUE) instanceof String) { addMetadataString((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), (String) values.get(METADATA_VALUE)); return; } else if (values.get(METADATA_VALUE) instanceof Boolean) { addMetadataBoolean((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), (Boolean) values.get(METADATA_VALUE)); return; } else if (values.get(METADATA_VALUE) instanceof Number) { addMetadataDouble((String) values.get(METADATA_SECTION), (String) values.get(METADATA_KEY), ((Number) values.get(METADATA_VALUE)).doubleValue()); return; } } else if (values.size() == 2) { removeMetadata((String)values.get(METADATA_SECTION), (String)values.get(METADATA_KEY)); return; } } warn("ADD_METADATA object is invalid: " + arg); }
Source:
public void check(Message message, Topic topic) { if (ContentType.AVRO != topic.getContentType() || (ContentType.JSON == topic.getContentType() && !topic.isJsonToAvroDryRunEnabled())) { return; } BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(message.getData(), null); try { new GenericDatumReader<>(message.<Schema>getSchema().get().getSchema()).read(null, binaryDecoder); } catch (Exception e) { throw new InvalidMessageException("Could not deserialize avro message with provided schema", ImmutableList.of(e.getMessage())); } }

Target:
public void check(Message message, Topic topic) { if (ContentType.AVRO != topic.getContentType() || (ContentType.JSON == topic.getContentType() && !topic.isJsonToAvroDryRunEnabled())) { return; } BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(message.getData(), null); try { new GenericDatumReader<>(message.<Schema>getSchema()).read(null, binaryDecoder); } catch (Exception e) { throw new InvalidMessageException("Could not deserialize avro message with provided schema", ImmutableList.of(e.getMessage())); } }
Source:
String keyspace() { SetKeyspaceAttempt currentAttempt = targetKeyspace.get(); return currentAttempt == null ? null : currentAttempt.keyspace; }

Target:
String keyspace() { return targetKeyspace.get().keyspace; }
Source:
public String show(Request request, Response response) throws IOException { String environmentName = request.params("name"); EnvironmentConfig environmentConfig = fetchEntityFromConfig(environmentName); setEtagHeader(environmentConfig, response); return writerForTopLevelObject(request, response, outputWriter -> EnvironmentRepresenter.toJSON(outputWriter, environmentConfig)); }

Target:
public String show(Request request, Response response) throws IOException { String environmentName = request.params("name"); EnvironmentConfig environmentConfig = fetchEntityFromConfig(environmentName); String etag = etagFor(environmentConfig); if (fresh(request, etag)) { return notModified(response); } setEtagHeader(environmentConfig, response); return writerForTopLevelObject(request, response, outputWriter -> EnvironmentRepresenter.toJSON(outputWriter, environmentConfig)); }
Source:
public void addContextServiceInGUI() { String name = "EEContextService_" + RandomStringUtils.randomAlphanumeric(6); ConfigFragment config = page.getConfigFragment(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", name); editor.text(JNDI_NAME, JNDI_VALID); wizard.clickSave(); Console.withBrowser(browser).dismissReloadRequiredWindowIfPresent(); assertTrue("Context service should be present in table", config.resourceIsPresent(name)); ResourceAddress address = new ResourceAddress(eeAddress).add(EE_CHILD, name); verifier.verifyResource(address, true, 5000); removeEEChild(EE_CHILD, name); }

Target:
public void addContextServiceInGUI() { String name = "EEContextService_" + RandomStringUtils.randomAlphanumeric(6); ConfigFragment config = page.getConfigFragment(); WizardWindow wizard = config.getResourceManager().addResource(); Editor editor = wizard.getEditor(); editor.text("name", name); editor.text(JNDI_NAME, JNDI_VALID); wizard.saveAndDismissReloadRequiredWindow(); assertTrue("Context service should be present in table", config.resourceIsPresent(name)); ResourceAddress address = new ResourceAddress(eeAddress).add(EE_CHILD, name); verifier.verifyResource(address, true, 5000); removeEEChild(EE_CHILD, name); }
Source:
public boolean isTestingAccount(AccountAttributes account){ boolean isTestingAccount = false; if(account.email.contains("tmt") || account.institute.contains("TEAMMATES test")){ isTestingAccount = true; } return isTestingAccount; }

Target:
public boolean isTestingAccount(AccountAttributes account){ boolean isTestingAccount = false; if(account.email.endsWith(".tmt") || account.institute.contains("TEAMMATES Test Institute")){ isTestingAccount = true; } return isTestingAccount; }
Source:
protected void validateApplications(ArtifactCoordinates domain, List<ArtifactCoordinates> applications) throws ValidationException { if (applications == null || applications.size() == 0) { throw new ValidationException("A domain bundle should contain at least one application"); } for (ArtifactCoordinates applicationCoordinates : applications) { validateApplication(domain, applicationCoordinates); } }

Target:
protected void validateApplications(ArtifactCoordinates domain, List<ArtifactCoordinates> applications) throws ValidationException { if (applications == null || applications.isEmpty()) { throw new ValidationException("A domain bundle should contain at least one application"); } for (ArtifactCoordinates applicationCoordinates : applications) { validateApplication(domain, applicationCoordinates); } }
Source:
protected boolean isExceedSize(int tableRegionsCount, long sizeToCheck) { long sumSize = 0; for (HStore store : region.getStores()) { sumSize += store.getSize(); } if (sumSize > sizeToCheck) { LOG.debug("ShouldSplit because region size is big enough " + " size=" + StringUtils.humanSize(sumSize) + ", sizeToCheck=" + StringUtils.humanSize(sizeToCheck) + ", regionsWithCommonTable=" + tableRegionsCount); return true; } return false; }

Target:
protected boolean isExceedSize(int tableRegionsCount, long sizeToCheck) { long sumSize = 0; for (HStore store : region.getStores()) { sumSize += store.getSize(); } if (sumSize > sizeToCheck) { LOG.debug("ShouldSplit because region size is big enough " + "size={}, sizeToCheck={}, regionsWithCommonTable={}", StringUtils.humanSize(sumSize), StringUtils.humanSize(sizeToCheck), tableRegionsCount); return true; } return false; }
Source:
public Builder time(final long timeToSet, final TimeUnit precisionToSet) { Preconditions.checkNotNull(precisionToSet, "TimeUnit must not be null!"); this.time = timeToSet; this.precision = precisionToSet; return this; }

Target:
public Builder time(final long timeToSet, final TimeUnit precisionToSet) { this.time = timeToSet; if (null != precisionToSet) { this.precision = precisionToSet; } return this; }
Source:
public HiveMetastoreClient createMetastoreClient() { List<HostAndPort> metastores = new ArrayList<>(addresses); metastores.sort(Comparator.comparingLong(m -> concurrentMap.get(m).getBackoffDelayNanos())); TException lastException = null; for (HostAndPort metastore : metastores) { try { HiveMetastoreClient client = new FailureAwareHiveMetaStoreClient(clientFactory.create(metastore), new ResponseHandle() { @Override public void success() { concurrentMap.get(metastore).success(); } @Override public void failed(TException e) { if (e.getCause() instanceof SocketTimeoutException) { concurrentMap.get(metastore).fail(); } } }); if (!isNullOrEmpty(metastoreUsername)) { client.setUGI(metastoreUsername); } return client; } catch (TException e) { lastException = e; } } throw new PrestoException(HIVE_METASTORE_ERROR, "Failed connecting to Hive metastore: " + addresses, lastException); }

Target:
public HiveMetastoreClient createMetastoreClient() throws TException { TException lastException = null; for (HostAndPort metastore : addresses) { try { HiveMetastoreClient client = new FailureAwareHiveMetaStoreClient(clientFactory.create(metastore), new ResponseHandle() { @Override public void success() { } @Override public void failed(TException e) { if (!metastore.equals(addresses.getLast())) { addresses.remove(metastore); addresses.addLast(metastore); } } }); if (!isNullOrEmpty(metastoreUsername)) { client.setUGI(metastoreUsername); } return client; } catch (TException e) { lastException = e; } } throw new TException("Failed connecting to Hive metastore: " + addresses, lastException); }
Source:
private static String adjustValueForExtension(String field, String value, ExtUUID queryEntity) { String result = value; if (queryEntity.equals(Authz.QueryEntity.PRINCIPAL)) { if (!(field.equals("$DEPARTMENT") || field.equals("$TITLE"))) { result = value.contains("@") ? value.substring(0, value.indexOf("@")) : value; } } return result; }

Target:
private static String adjustValueForExtension(String field, String value, ExtUUID queryEntity) { String result = value; if (queryEntity.equals(Authz.QueryEntity.PRINCIPAL)) { if (!NON_ADJUSTABLE_FIELDS.contains(field)) { result = value.contains("@") ? value.substring(0, value.indexOf("@")) : value; } } return result; }
Source:
public void readVector(ObjectColumnVector<T> vector, long current, long total) { int index = 0; for ( ; index < ColumnVector.DEFAULT_VECTOR_LENGTH; index++, current++) { if (current >= total) { ((ColumnVector) vector).setNumberOfValues(index); return; } T record = read(); if (shouldSkipCurrentRecord) { if (DEBUG) { LOG.debug("skipping record"); } vector.isNull[index] = true; } vector.values[index] = record; } ((ColumnVector) vector).setNumberOfValues(index); }

Target:
protected void readVector(ObjectColumnVector<T> vector, long current, long total) { int index = 0; for ( ; index < ColumnVector.MAX_VECTOR_LENGTH; index++, current++) { if (current >= total) { ((ColumnVector) vector).setNumberOfValues(index); return; } T record = read(); if (shouldSkipCurrentRecord) { if (DEBUG) { LOG.debug("skipping record"); } vector.isNull[index] = true; } vector.values[index] = record; } ((ColumnVector) vector).setNumberOfValues(index); }
Source:
public void taskSubmitted(Future<?> future, ManagedExecutorService managedExecutorService, Object o) { }

Target:
public void taskSubmitted(Future<?> future, ManagedExecutorService managedExecutorService, Object o) { log.debug("Task submitted: {}", Thread.currentThread().getName()); }
Source:
public void addMiniTaskstoView() { List<Integer> taskIds = model.getTaskIds(); this.view.resetTaskList(); Color filterColor = MainView.getInstance().getFilterColor(); for (int i : taskIds) { MiniTaskView miniTaskView = taskMap.get(i).getMiniView(); if (filterColor.equals(taskMap.get(i).getModel().getLabelColor()) || filterColor.equals(MainView.getInstance() .getNoFilterColor())) { if (MainView.getInstance().getShowArchived()) { view.addTaskToView(miniTaskView); } else { if (!taskMap.get(i).getModel().getIsArchived()) { view.addTaskToView(miniTaskView); } } } } view.revalidate(); view.repaint(); }

Target:
public void addMiniTaskstoView() { List<Integer> taskIds = model.getTaskIds(); Filter filter = new Filter(); this.view.resetTaskList(); for (int i : taskIds) { MiniTaskView miniTaskView = taskMap.get(i).getMiniView(); if (filter.matches(taskMap.get(i))) { if (MainView.getInstance().getShowArchived()) { view.addTaskToView(miniTaskView); } else { if (!taskMap.get(i).getModel().getIsArchived()) { view.addTaskToView(miniTaskView); } } } } view.revalidate(); view.repaint(); }