auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public int removeRecipient(String channelName, String selectorExpression) { int counter = 0; for (Iterator<Recipient> it = this.recipients.iterator();it.hasNext();) { Recipient next = it.next(); MessageSelector selector = next.getSelector(); MessageChannel channel = next.getChannel(); if(selector instanceof ExpressionEvaluatingSelector && channel.equals(this.getBeanFactory().getBean(channelName)) && ((ExpressionEvaluatingSelector)selector).getExpressionString().equals(selectorExpression)) { it.remove(); counter++; } } return counter; }

Target:
public int removeRecipient(String channelName, String selectorExpression) { int counter = 0; MessageChannel targetChannel = this.getBeanFactory().getBean(channelName, MessageChannel.class); for (Iterator<Recipient> it = this.recipients.iterator();it.hasNext();) { Recipient next = it.next(); MessageSelector selector = next.getSelector(); MessageChannel channel = next.getChannel(); if(selector instanceof ExpressionEvaluatingSelector && channel == targetChannel && ((ExpressionEvaluatingSelector) selector).getExpressionString().equals(selectorExpression)) { it.remove(); counter++; } } return counter; }
Source:
public void should_allow_to_specify_type_comparator_after_using_extracting_with_single_parameter_on_object() { Person obiwan = new Person("Obi-Wan"); obiwan.setHeight(new BigDecimal("1.820")); assertThat(obiwan).extracting("height") .usingComparatorForType(BIG_DECIMAL_COMPARATOR, BigDecimal.class) .isEqualTo(new BigDecimal("1.82")); }

Target:
public void should_allow_to_specify_type_comparator_after_using_extracting_with_single_parameter_on_object() { Person obiwan = new Person("Obi-Wan"); obiwan.setHeight(new BigDecimal("1.820")); Comparator<Object> heightComparator = (o1, o2) -> { if (o1 instanceof BigDecimal) return BIG_DECIMAL_COMPARATOR.compare((BigDecimal) o1, (BigDecimal) o2); throw new IllegalStateException("only supported for BigDecimal"); }; assertThat(obiwan).extracting("height") .usingComparator(heightComparator) .isEqualTo(new BigDecimal("1.82")); }
Source:
public InMemoryFormat getInMemoryFormat() { return getMapContainer().getMapConfig().getInMemoryFormat(); }

Target:
public InMemoryFormat getInMemoryFormat() { return inMemoryFormat; }
Source:
boolean deleteService() { try { final Response response = coreClient.deleteNamespacedServiceCall(getTopologyName(), getNamespace(), null, null, 0, null, KubernetesConstants.DELETE_OPTIONS_PROPAGATION_POLICY, null, null).execute(); if (response.isSuccessful()) { LOG.log(Level.INFO, "Headless Service for the Job [" + getTopologyName() + "] in namespace [" + getNamespace() + "] is deleted."); return true; } else { if (response.code() == HTTP_NOT_FOUND) { LOG.log(Level.INFO, "Kubernetes headless service does not exist for Topology: " + getTopologyName()); return true; } LOG.log(Level.SEVERE, "Error when deleting the Service of the job [" + getTopologyName() + "] in namespace [" + getNamespace() + "]"); LOG.log(Level.SEVERE, "Error killing topoogy message:" + response.message()); KubernetesUtils.logResponseBodyIfPresent(LOG, response); throw new TopologyRuntimeManagementException( KubernetesUtils.errorMessageFromResponse(response)); } } catch (ApiException e) { if (e.getCode() == HTTP_NOT_FOUND) { LOG.log(Level.INFO, "Kubernetes headless service does not exist for Topology: " + getTopologyName()); return true; } } catch (IOException e) { KubernetesUtils.logExceptionWithDetails(LOG, "Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); return false; } return false; }

Target:
void deleteService() { try (Response response = coreClient.deleteNamespacedServiceCall(getTopologyName(), getNamespace(), null, null, 0, null, KubernetesConstants.DELETE_OPTIONS_PROPAGATION_POLICY, null, null).execute()) { if (!response.isSuccessful()) { if (response.code() == HTTP_NOT_FOUND) { LOG.log(Level.WARNING, "Deleting non-existent Kubernetes headless service for Topology: " + getTopologyName()); return; } LOG.log(Level.SEVERE, "Error when deleting the Service of the job [" + getTopologyName() + "] in namespace [" + getNamespace() + "]"); LOG.log(Level.SEVERE, "Error killing topology message:" + response.message()); KubernetesUtils.logResponseBodyIfPresent(LOG, response); throw new TopologyRuntimeManagementException( KubernetesUtils.errorMessageFromResponse(response)); } } catch (ApiException e) { if (e.getCode() == HTTP_NOT_FOUND) { LOG.log(Level.WARNING, "Tried to delete a non-existent Kubernetes service for Topology: " + getTopologyName()); return; } throw new TopologyRuntimeManagementException("Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); } catch (IOException e) { throw new TopologyRuntimeManagementException("Error deleting topology [" + getTopologyName() + "] Kubernetes service", e); } LOG.log(Level.INFO, "Headless Service for the Job [" + getTopologyName() + "] in namespace [" + getNamespace() + "] is deleted."); }
Source:
public void testIterationWithConcurrentClearedCacheException() { try (CacheManager cacheManager = createTestCacheManager()) { Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class); byte[] data = new byte[10 * 1024]; range(0, 20).forEach(k -> cache.put(k, data)); Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator(); cache.clear(); try { while (true) { iterator.next(); } } catch (NoSuchElementException e) { } } }

Target:
public void testIterationWithConcurrentClearedCacheException() { try (CacheManager cacheManager = createTestCacheManager()) { Cache<Long, byte[]> cache = cacheManager.getCache(testName.getMethodName(), Long.class, byte[].class); byte[] data = new byte[10 * 1024]; Set<Long> initialKeySet = new HashSet<>(); range(0, 20).forEach(k -> { cache.put(k, data); initialKeySet.add(k); }); Iterator<Cache.Entry<Long, byte[]>> iterator = cache.iterator(); cache.clear(); HashSet<Long> foundKeys = new HashSet<>(); try { while (true) { assertThat(foundKeys.add(iterator.next().getKey()), is(true)); } } catch (NoSuchElementException e) { } foundKeys.forEach(k -> assertThat(k, isIn(initialKeySet))); } }
Source:
public static boolean isValidDefinition(URL definitionURL, String definitionType) throws EndpointRegistryException { DefinitionValidator schemaValidator = definitionValidatorMap.get(definitionType); if (schemaValidator != null) { return schemaValidator.validate(definitionURL); } throw new EndpointRegistryException("No Schema Validator found for the given definition type: '" + definitionType + "'"); }

Target:
public static boolean isValidDefinition(URL definitionURL, String definitionType) throws DefinitionValidationException { DefinitionValidator definitionValidator = definitionValidatorMap.get(definitionType); if (definitionValidator != null) { return definitionValidator.validate(definitionURL); } throw new DefinitionValidationException("No Definition Validator found for the given definition type: '" + definitionType + "'"); }
Source:
private long getMaxRead(long position, long count) throws IOException { count = Math.min( maxRemoteSize == 0 || (position + count >= maxRemoteSize && activeFile) ? reallyGetLength() - position : maxRemoteSize - position, count); return (count == 0) ? 0 : count; }

Target:
private long getMaxRead(long position, long count) throws IOException { count = Math.min( maxRemoteSize == 0 || (position + count >= maxRemoteSize && activeFile) ? reallyGetLength() - position : maxRemoteSize - position, count); return count; }
Source:
public ItemHolder(View view) { super(view); this.text = (TextView) view.findViewById(R.id.text); this.container = (LinearLayout) view.findViewById(R.id.container); }

Target:
public ItemHolder(View view) { super(view); this.container = (LinearLayout) view.findViewById(R.id.container); this.text = (TextView) view.findViewById(R.id.text); }
Source:
private void readHeaderData() throws IOException { setFileVersion(parseInt()); gencallVersion = parseString(); clusterVersion = parseString(); callVersion = parseString(); normalizationVersion = parseString(); dateCreated = parseString(); skipBoolean(); if (getFileVersion() == INVALID_FILE_VERSION) { throw new IOException("Version '" + INVALID_FILE_VERSION + "' unsupported"); } manifestName = parseString(); }

Target:
private void readHeaderData() throws IOException { setFileVersion(parseInt()); gencallVersion = parseString(); clusterVersion = parseString(); callVersion = parseString(); normalizationVersion = parseString(); dateCreated = parseString(); isWGT = parseByte() != '\0'; if (getFileVersion() == INVALID_FILE_VERSION) { throw new IOException("Version '" + INVALID_FILE_VERSION + "' unsupported"); } manifestName = parseString(); }
Source:
private void generatePositionEqualsRowWithPageMethod( ClassDefinition classDefinition, CallSiteBinder callSiteBinder, List<Type> joinChannelTypes, List<FieldDefinition> joinChannelFields) { Parameter leftBlockIndex = arg("leftBlockIndex", int.class); Parameter leftBlockPosition = arg("leftBlockPosition", int.class); Parameter rightPosition = arg("rightPosition", int.class); Parameter page = arg("page", Page.class); Parameter rightChannels = arg("rightChannels", int[].class); MethodDefinition positionEqualsRowMethod = classDefinition.declareMethod( a(PUBLIC), "positionEqualsRow", type(boolean.class), leftBlockIndex, leftBlockPosition, rightPosition, page, rightChannels); Variable thisVariable = positionEqualsRowMethod.getThis(); BytecodeBlock body = positionEqualsRowMethod.getBody(); for (int index = 0; index < joinChannelTypes.size(); index++) { BytecodeExpression leftBlock = thisVariable .getField(joinChannelFields.get(index)) .invoke("get", Object.class, leftBlockIndex) .cast(Block.class); BytecodeExpression rightBlock = page.invoke("getBlock", Block.class, rightChannels.getElement(index)); body.append(new IfStatement() .condition(isDistinctFromGenerator.generateIsDistinctFrom( callSiteBinder, joinChannelTypes.get(index), leftBlock, leftBlockPosition, rightBlock, rightPosition)) .ifTrue(constantFalse().ret())); } body.append(constantTrue().ret()); }

Target:
private static void generatePositionEqualsRowWithPageMethod( ClassDefinition classDefinition, CallSiteBinder callSiteBinder, List<Type> joinChannelTypes, List<FieldDefinition> joinChannelFields) { Parameter leftBlockIndex = arg("leftBlockIndex", int.class); Parameter leftBlockPosition = arg("leftBlockPosition", int.class); Parameter rightPosition = arg("rightPosition", int.class); Parameter page = arg("page", Page.class); Parameter rightChannels = arg("rightChannels", int[].class); MethodDefinition positionEqualsRowMethod = classDefinition.declareMethod( a(PUBLIC), "positionEqualsRow", type(boolean.class), leftBlockIndex, leftBlockPosition, rightPosition, page, rightChannels); Variable thisVariable = positionEqualsRowMethod.getThis(); BytecodeBlock body = positionEqualsRowMethod.getBody(); for (int index = 0; index < joinChannelTypes.size(); index++) { BytecodeExpression type = constantType(callSiteBinder, joinChannelTypes.get(index)); BytecodeExpression leftBlock = thisVariable .getField(joinChannelFields.get(index)) .invoke("get", Object.class, leftBlockIndex) .cast(Block.class); BytecodeExpression rightBlock = page.invoke("getBlock", Block.class, rightChannels.getElement(index)); body.append(new IfStatement() .condition(typeEquals(type, leftBlock, leftBlockPosition, rightBlock, rightPosition)) .ifFalse(constantFalse().ret())); } body.append(constantTrue().ret()); }
Source:
protected Optional<DyeColor> getVal(EntityShulker container) { if (!(container instanceof IMixinShulker)) return Optional.empty(); return Optional.of(((IMixinShulker) container).getColor()); }

Target:
protected Optional<DyeColor> getVal(EntityShulker container) { return Optional.of(((IMixinShulker) container).getColor()); }
Source:
public MaxRateRegistry provide() { ConsumerMaxRateRegistryType type; try { type = ConsumerMaxRateRegistryType.fromString(configFactory.getStringProperty(Configs.CONSUMER_MAXRATE_REGISTRY_TYPE)); } catch (Exception e) { logger.error("Could not configure max rate registry", e); throw e; } logger.info("Max rate registry type chosen: {}", type.getConfigValue()); switch (type) { case HIERARCHICAL: return new HierarchicalCacheMaxRateRegistry(configFactory, curator, objectMapper, zookeeperPaths, pathSerializer, subscriptionCache); case FLAT_BINARY: return new FlatBinaryMaxRateRegistry(configFactory, subscriptionAssignmentCache::getAssignedConsumers, subscriptionAssignmentCache::getConsumerSubscriptions, curator, zookeeperPaths, subscriptionIds); default: throw new UnsupportedOperationException("Max-rate type not supported."); } }

Target:
public MaxRateRegistry provide() { ConsumerMaxRateRegistryType type; try { String typeString = configFactory.getStringProperty(Configs.CONSUMER_MAXRATE_REGISTRY_TYPE); type = ConsumerMaxRateRegistryType.fromString(typeString); } catch (Exception e) { logger.error("Could not configure max rate registry", e); throw e; } logger.info("Max rate registry type chosen: {}", type.getConfigValue()); switch (type) { case HIERARCHICAL: return new HierarchicalCacheMaxRateRegistry( configFactory, curator, objectMapper, zookeeperPaths, pathSerializer, subscriptionCache ); case FLAT_BINARY: return new FlatBinaryMaxRateRegistry( configFactory, subscriptionAssignmentCache::getAssignedConsumers, subscriptionAssignmentCache::getConsumerSubscriptions, curator, zookeeperPaths, subscriptionIds ); default: throw new UnsupportedOperationException("Max-rate type not supported."); } }
Source:
private boolean canTypeBeAnalyzed(String fieldType) { return "string".equals( fieldType ); }

Target:
private boolean canTypeBeAnalyzed(String fieldType) { return TYPE_STRING.equals( fieldType ); }
Source:
private String getFieldCheckRequired(String column, boolean required) throws IOException { String str = reader.get(column); if (str == null) { if (!missingRequiredColumns.contains(column)) { feed.errors.add(new MissingColumnError(tableName, row, column)); missingRequiredColumns.add(column); } } else if (str.isEmpty()) { if (required) { feed.errors.add(new EmptyFieldError(tableName, row, column)); } str = null; } return str; }

Target:
private String getFieldCheckRequired(String column, boolean required) throws IOException { String str = reader.get(column); if (str == null) { if (!missingRequiredColumns.contains(column)) { feed.errors.add(new MissingColumnError(tableName, column)); missingRequiredColumns.add(column); } } else if (str.isEmpty()) { if (required) { feed.errors.add(new EmptyFieldError(tableName, row, column)); } str = null; } return str; }
Source:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context){ StartedDrugOrderCohortDefinition cd = (StartedDrugOrderCohortDefinition) cohortDefinition; context = ObjectUtil.nvl(context, new EvaluationContext()); HqlQueryBuilder q = new HqlQueryBuilder(); q.select("do.patient.patientId"); q.from(DrugOrder.class, "do"); q.wherePatientIn("do.patient.patientId", context); q.whereEqual("do.action", Action.NEW); q.whereNull("do.previousOrder"); if (cd.getActiveOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateActivated", cd.getActiveOnOrBefore()); q.whereGreaterOrNull("do.dateStopped", cd.getActiveOnOrBefore()); } if (cd.getActiveOnOrAfter() != null) { q.whereNotNull("do.dateActivated"); q.whereGreaterEqualOrNull("do.dateStopped", cd.getActiveOnOrAfter()); } if (cd.getStartedOnOrAfter()!= null) { q.whereGreaterOrEqualTo("do.dateStopped", cd.getStartedOnOrAfter()); } if (cd.getStartedOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateStopped", cd.getStartedOnOrBefore()); } if (cd.getDrugSet() != null && cd.getDrugSet().size() > 0) { q.whereInAny("do.drugs", cd.getDrugSet().toArray()); } if (cd.getGenericDrugList() != null && cd.getGenericDrugList().size() > 0) { q.whereInAny("do.concept", cd.getGenericDrugList().toArray()); } List<Integer> pIds = evaluationService.evaluateToList(q, Integer.class, context); Cohort c = new Cohort(pIds); return new EvaluatedCohort(c, cd, context); }

Target:
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) { StartedDrugOrderCohortDefinition cd = (StartedDrugOrderCohortDefinition) cohortDefinition; context = ObjectUtil.nvl(context, new EvaluationContext()); HqlQueryBuilder q = new HqlQueryBuilder(); q.select("do.patient.patientId"); q.from(DrugOrder.class, "do"); q.wherePatientIn("do.patient.patientId", context); q.whereEqual("do.action", Action.NEW); q.whereNull("do.previousOrder"); if (cd.getActiveOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateActivated", cd.getActiveOnOrBefore()); q.whereGreaterOrNull("do.dateStopped", cd.getActiveOnOrBefore()); } if (cd.getActiveOnOrAfter() != null) { q.whereNotNull("do.dateActivated"); q.whereGreaterEqualOrNull("do.dateStopped", cd.getActiveOnOrAfter()); } if (cd.getStartedOnOrAfter() != null) { q.whereGreaterOrEqualTo("do.dateStopped", cd.getStartedOnOrAfter()); } if (cd.getStartedOnOrBefore() != null) { q.whereLessOrEqualTo("do.dateStopped", cd.getStartedOnOrBefore()); } if (cd.getDrugSet() != null && cd.getDrugSet().size() > 0) { q.whereInAny("do.drug", cd.getDrugSet().toArray()); } if (cd.getGenericDrugList() != null && cd.getGenericDrugList().size() > 0) { q.whereInAny("do.drug", cd.getGenericDrugList().toArray()); } List<Integer> pIds = evaluationService.evaluateToList(q, Integer.class, context); Cohort c = new Cohort(pIds); return new EvaluatedCohort(c, cd, context); }
Source:
private void bulkPrepare(BulkOperations bulkOperations, Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = getStoredVariantAnnotations(variantAnnotations); for (Map.Entry<String, VariantAnnotation> entry : variantAnnotations.entrySet()) { final String key = entry.getKey(); if (storedVariantAnnotations.containsKey(key)) { bulkUpdate(bulkOperations, key, storedVariantAnnotations.get(key).concatenate(entry.getValue())); } else { bulkAddToSet(bulkOperations, key, entry.getValue()); } } }

Target:
private void bulkPrepare(BulkOperations bulkOperations, Map<String, VariantAnnotation> variantAnnotations) { Map<String, VariantAnnotation> storedVariantAnnotations = getStoredVariantAnnotations(variantAnnotations); for (Map.Entry<String, VariantAnnotation> entry : variantAnnotations.entrySet()) { final String variantId = entry.getKey(); if (storedVariantAnnotations.containsKey(variantId)) { bulkUpdate(bulkOperations, variantId, storedVariantAnnotations.get(variantId).concatenate(entry.getValue())); } else { bulkAddToSet(bulkOperations, variantId, entry.getValue()); } } }
Source:
public Optional<Instant> nextRun(final Optional<Instant> lastRun) { final Duration fullPeriod = Duration.of(_periodCount, _period); final Instant now = _clock.instant(); final Instant start = lastRun .filter(run -> run.compareTo(now) >= 0) .map(run -> run.plus(fullPeriod)) .orElse(now); final long epochMillis = start.toEpochMilli(); final Instant nextRun = Instant.ofEpochMilli((epochMillis / fullPeriod.toMillis()) * fullPeriod.toMillis()); return Optional.of(nextRun); }

Target:
public Optional<Instant> nextRun(final Optional<Instant> lastRun) { final Instant now = _clock.instant(); final Instant start = lastRun .filter(run -> run.compareTo(now) >= 0) .map(run -> run.plus(_fullPeriod)) .orElse(now); final long excessMillis = start.toEpochMilli() % _fullPeriod.toMillis(); return Optional.of(start.minusMillis(excessMillis)); }
Source:
public SingleNodeApplication run(String... args) { System.out.println(BannerUtils.displayBanner(getClass().getSimpleName(), null)); ContainerBootstrapContext bootstrapContext = new ContainerBootstrapContext(new SingleNodeOptions()); SpringApplicationBuilder admin = new SpringApplicationBuilder(SingleNodeOptions.class, ParentConfiguration.class, SingleNodeApplication.class) .listeners(bootstrapContext.commandLineListener()) .profiles(AdminServerApplication.ADMIN_PROFILE, SINGLE_PROFILE) .child(SingleNodeOptions.class, AdminServerApplication.class) .listeners(bootstrapContext.commandLineListener()); admin.run(args); SpringApplicationBuilder container = admin .sibling(SingleNodeOptions.class, ContainerServerApplication.class) .profiles(ContainerServerApplication.NODE_PROFILE, SINGLE_PROFILE) .listeners(bootstrapContext.commandLineListener()) .listeners(bootstrapContext.sharedContextInitializers()) .child(CoreRuntimeConfiguration.class) .listeners(bootstrapContext.commandLineListener()) .web(false); container.run(args); adminContext = admin.context(); coreContext = container.context(); containerContext = (ConfigurableApplicationContext) coreContext.getParent(); SingleNodeApplication singleNodeApp = adminContext.getBean(SingleNodeApplication.class); if (singleNodeApp.controlTransport == ControlTransport.local) { setUpControlChannels(adminContext, coreContext); } return this; }

Target:
public SingleNodeApplication run(String... args) { System.out.println(BannerUtils.displayBanner(getClass().getSimpleName(), null)); ContainerBootstrapContext bootstrapContext = new ContainerBootstrapContext(new SingleNodeOptions()); SpringApplicationBuilder admin = new SpringApplicationBuilder(SingleNodeOptions.class, ParentConfiguration.class, SingleNodeApplication.class) .listeners(bootstrapContext.commandLineListener()) .profiles(AdminServerApplication.ADMIN_PROFILE, SINGLE_PROFILE) .child(SingleNodeOptions.class, AdminServerApplication.class) .listeners(bootstrapContext.commandLineListener()); admin.run(args); SpringApplicationBuilder container = admin .sibling(SingleNodeOptions.class, ContainerServerApplication.class) .profiles(ContainerServerApplication.NODE_PROFILE, SINGLE_PROFILE) .listeners(ApplicationUtils.mergeApplicationListeners(bootstrapContext.commandLineListener(), bootstrapContext.orderedContextInitializers())) .child(ContainerConfiguration.class) .listeners(bootstrapContext.commandLineListener()) .web(false); container.run(args); adminContext = admin.context(); containerContext = container.context(); pluginContext = (ConfigurableApplicationContext) containerContext.getParent(); SingleNodeApplication singleNodeApp = adminContext.getBean(SingleNodeApplication.class); if (singleNodeApp.controlTransport == ControlTransport.local) { setUpControlChannels(adminContext, containerContext); } return this; }
Source:
private void waitForPartitionsFetchedOnce() { while ((partitions.isEmpty() || partitionCount == 0) && client.getConnectionManager().isAlive()) { ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); if (!processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist)) { throw new NoDataMemberInClusterException( "Cluster could not initialize the partition table "); } } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }

Target:
private void waitForPartitionsFetchedOnce() { while (partitions.isEmpty() && client.getConnectionManager().isAlive()) { ClientClusterService clusterService = client.getClientClusterService(); Collection<Member> memberList = clusterService.getMemberList(); if (memberList.isEmpty()) { break; } if (isClusterFormedByOnlyLiteMembers(memberList)) { throw new NoDataMemberInClusterException( "Partitions can't be assigned since all nodes in the cluster are lite members"); } ClientMessage requestMessage = ClientGetPartitionsCodec.encodeRequest(); ClientInvocationFuture future = new ClientInvocation(client, requestMessage, null).invokeUrgent(); try { ClientMessage responseMessage = future.get(); ClientGetPartitionsCodec.ResponseParameters response = ClientGetPartitionsCodec.decodeResponse(responseMessage); processPartitionResponse(response.partitions, response.partitionStateVersion, response.partitionStateVersionExist); } catch (Exception e) { if (client.getLifecycleService().isRunning()) { logger.warning("Error while fetching cluster partition table!", e); } } } }
Source:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { DSpaceRestPermission restPermission = DSpaceRestPermission.convert(permission); if (!DSpaceRestPermission.READ.equals(restPermission) || !StringUtils.equals(targetType, "WORKFLOWITEM")) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); XmlWorkflowItem workflowItem = workflowItemService.find(context, dsoId); if (ePerson.equals(workflowItem.getSubmitter())) { return true; } if (poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } if (claimedTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }

Target:
public boolean hasDSpacePermission(Authentication authentication, Serializable targetId, String targetType, DSpaceRestPermission permission) { DSpaceRestPermission restPermission = DSpaceRestPermission.convert(permission); if (!DSpaceRestPermission.READ.equals(restPermission) || !StringUtils.equalsIgnoreCase(WorkflowItemRest.NAME, targetType)) { return false; } Request request = requestService.getCurrentRequest(); Context context = ContextUtil.obtainContext(request.getServletRequest()); EPerson ePerson = null; try { ePerson = ePersonService.findByEmail(context, (String) authentication.getPrincipal()); if (ePerson == null) { return false; } Integer dsoId = Integer.parseInt(targetId.toString()); XmlWorkflowItem workflowItem = workflowItemService.find(context, dsoId); if (ePerson.equals(workflowItem.getSubmitter())) { return true; } if (poolTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } if (claimedTaskService.findByWorkflowIdAndEPerson(context, workflowItem, ePerson) != null) { return true; } } catch (SQLException | AuthorizeException | IOException e) { log.error(e.getMessage(), e); } return false; }
Source:
public void shouldThrowNullPointerOnJoinWithStreamWhenStreamJoinedIsNull() { final StreamJoined joined = null; testStream.join(testStream, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10)), joined); }

Target:
public void shouldThrowNullPointerOnJoinWithStreamWhenStreamJoinedIsNull() { testStream.join(testStream, MockValueJoiner.TOSTRING_JOINER, JoinWindows.of(ofMillis(10)), nullStreamJoinedForTest); }
Source:
BitmapBuilder findObjects(Set<? extends ObjectId> start, BitmapBuilder seen, boolean ignoreMissingStart) throws MissingObjectException, IncorrectObjectTypeException, IOException { final BitmapBuilder bitmapResult = bitmapIndex.newBitmapBuilder(); countOfBitmapIndexMisses = 0; for (ObjectId obj : start) { Bitmap bitmap = bitmapIndex.getBitmap(obj); if (bitmap != null) bitmapResult.or(bitmap); } boolean marked = false; for (ObjectId obj : start) { try { if (!bitmapResult.contains(obj)) { walker.markStart(walker.parseAny(obj)); marked = true; } } catch (MissingObjectException e) { if (ignoreMissingStart) continue; throw e; } } if (marked) { BitmapRevFilter filter = newRevFilter(seen, bitmapResult); walker.setRevFilter(filter); while (walker.next() != null) { pm.update(1); } RevObject ro; while ((ro = walker.nextObject()) != null) { bitmapResult.add(ro, ro.getType()); pm.update(1); } countOfBitmapIndexMisses = filter.getCountOfLoadedCommits(); } return bitmapResult; }

Target:
BitmapBuilder findObjects(Set<? extends ObjectId> start, BitmapBuilder seen, boolean ignoreMissingStart) throws MissingObjectException, IncorrectObjectTypeException, IOException { final BitmapBuilder bitmapResult = bitmapIndex.newBitmapBuilder(); for (ObjectId obj : start) { Bitmap bitmap = bitmapIndex.getBitmap(obj); if (bitmap != null) bitmapResult.or(bitmap); } boolean marked = false; for (ObjectId obj : start) { try { if (!bitmapResult.contains(obj)) { walker.markStart(walker.parseAny(obj)); marked = true; } } catch (MissingObjectException e) { if (ignoreMissingStart) continue; throw e; } } if (marked) { BitmapRevFilter filter = newRevFilter(seen, bitmapResult); walker.setRevFilter(filter); while (walker.next() != null) { pm.update(1); } RevObject ro; while ((ro = walker.nextObject()) != null) { bitmapResult.add(ro, ro.getType()); pm.update(1); } countOfBitmapIndexMisses += filter.getCountOfLoadedCommits(); } return bitmapResult; }
Source:
private void checkVdsMemoryThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); if (stat.getmem_available() < minAvailableThreshold || stat.getusage_mem_percent() > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(); logable.setVdsId(stat.getId()); logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("AvailableMemory", stat.getmem_available().toString()); logable.AddCustomValue("UsedMemory", stat.getusage_mem_percent().toString()); logable.AddCustomValue("Threshold", stat.getmem_available() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, stat.getmem_available() < minAvailableThreshold ? AuditLogType.VDS_LOW_MEM : AuditLogType.VDS_HIGH_MEM_USE); } }

Target:
private void checkVdsMemoryThreshold(VdsStatistics stat) { Integer minAvailableThreshold = Config.GetValue(ConfigValues.LogPhysicalMemoryThresholdInMB); Integer maxUsedPercentageThreshold = Config.GetValue(ConfigValues.LogMaxPhysicalMemoryUsedThresholdInPercentage); AuditLogType valueToLog = stat.getmem_available() < minAvailableThreshold ? AuditLogType.VDS_LOW_MEM : AuditLogType.VDS_HIGH_MEM_USE; if (stat.getmem_available() < minAvailableThreshold || stat.getusage_mem_percent() > maxUsedPercentageThreshold) { AuditLogableBase logable = new AuditLogableBase(stat.getId()); logable.AddCustomValue("HostName", _vds.getvds_name()); logable.AddCustomValue("AvailableMemory", stat.getmem_available().toString()); logable.AddCustomValue("UsedMemory", stat.getusage_mem_percent().toString()); logable.AddCustomValue("Threshold", stat.getmem_available() < minAvailableThreshold ? minAvailableThreshold.toString() : maxUsedPercentageThreshold.toString()); auditLog(logable, valueToLog); } }
Source:
public void testNotOptional() { try { insert("value.text", getTestBeanEmpty()); fail("Shouldn't be reached"); } catch (IllegalArgumentException ex) { assertThat(select().isPresent()).isFalse(); } }

Target:
public void testNotOptional() { assertThatThrownBy(() -> insert("value.text", getTestBeanEmpty())).isInstanceOf(IllegalArgumentException.class); assertThat(select().isPresent()).isFalse(); }
Source:
public static void show(final Long sessionId) { LightningTalk talk = LightningTalk.findById(sessionId); if(talk != null) { render(talk); } else { } }

Target:
public static void show(final Long sessionId) { LightningTalk talk = LightningTalk.findById(sessionId); notFoundIfNull(talk); render(talk); }
Source:
protected void onGetComputedStyles(View element, ComputedStyleAccumulator styles) { styles.store("left", "" + element.getLeft()); styles.store("top", "" + element.getTop()); styles.store("right", "" + element.getRight()); styles.store("bottom", "" + element.getBottom()); }

Target:
protected void onGetComputedStyles(View element, ComputedStyleAccumulator styles) { styles.store("left", Integer.toString(element.getLeft())); styles.store("top", Integer.toString(element.getTop())); styles.store("right", Integer.toString(element.getRight())); styles.store("bottom", Integer.toString(element.getBottom())); }
Source:
private void updateLabels() { if ((null != transition) && (null != transition.getComment()) && !transition.getComment().isEmpty()) { tooltipContent.setText(transition.getComment()); } tooltipContent.setText("[not set]"); revalidate(); repaint(); }

Target:
private void updateLabels() { if ((null != transition.getComment()) && !transition.getComment().isEmpty()) { tooltipContent.setText(transition.getComment()); } else { tooltipContent.setText("[not set]"); } revalidate(); repaint(); }
Source:
public List<String> getAlterTable(String tableName, Collection<SinkRecordField> fields) { final StringBuilder builder = new StringBuilder("ALTER TABLE "); builder.append(escaped(tableName)); builder.append(" ADD("); writeColumnsSpec(builder, fields); builder.append(")"); log.trace("Alter Table query: " + builder.toString()); return Collections.singletonList(builder.toString()); }

Target:
public List<String> getAlterTable(String tableName, Collection<SinkRecordField> fields) { final StringBuilder builder = new StringBuilder("ALTER TABLE "); builder.append(escaped(tableName)); builder.append(" ADD("); writeColumnsSpec(builder, fields); builder.append(")"); return Collections.singletonList(builder.toString()); }
Source:
private void captureStackTrace() { if (stackTraces.size() < options.maxStackSamples()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace.length > 3) { StackTraceElement[] slicedStackTrace = Arrays.copyOfRange(stackTrace, 3, stackTrace.length); JobCancelabilityMonitor.StackTraceSample newStackTraceSample = new StackTraceSample(slicedStackTrace); boolean found = false; Iterator<JobCancelabilityMonitor.StackTraceSample> it = stackTraces.iterator(); while (it.hasNext() && !found) { found = (it.next().hashCode == newStackTraceSample.hashCode); } if (!found) { stackTraces.add(newStackTraceSample); } } } }

Target:
private StackTraceElement[] captureStackTrace() { final StackTraceElement[] ret; StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); if (stackTrace.length > 3) { ret = Arrays.copyOfRange(stackTrace, 3, stackTrace.length); } else { ret = stackTrace; } return ret; }
Source:
private void testContent() throws Exception { ______TS("Typical case: empty profile values"); profilePage.verifyHtml("/studentProfilePageDefault.html"); ______TS("Typical case: existing profile values"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.verifyHtmlPart(By.id("editProfileDiv"), "/studentProfileEditDivExistingValues.html"); ______TS("Typical case: edit profile picture modal (without existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.showPictureEditor(); profilePage.verifyHtmlPart(By.id("studentPhotoUploader"), "/studentProfilePictureModalDefault.html"); ______TS("Typical case: edit profile picture modal (with existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.fillProfilePic("src/test/resources/images/profile_pic.png"); profilePage.uploadPicture(); profilePage.verifyStatusWithRetry(Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED, 10); profilePage.verifyHtml("/studentProfilePageFilled.html"); profilePage.click(By.className("close")); }

Target:
private void testContent() throws Exception { ______TS("Typical case: empty profile values"); profilePage.verifyHtml("/studentProfilePageDefault.html"); ______TS("Typical case: existing profile values"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.verifyHtmlPart(By.id("editProfileDiv"), "/studentProfileEditDivExistingValues.html"); ______TS("Typical case: edit profile picture modal (without existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.showPictureEditor(); profilePage.verifyHtmlPart(By.id("studentPhotoUploader"), "/studentProfilePictureModalDefault.html"); ______TS("Typical case: edit profile picture modal (with existing picture)"); profilePage = getProfilePageForStudent("studentWithExistingProfile"); profilePage.fillProfilePic("src/test/resources/images/profile_pic.png"); profilePage.uploadPicture(); profilePage.verifyStatusWithRetry(Const.StatusMessages.STUDENT_PROFILE_PICTURE_SAVED, 10); profilePage.verifyHtmlMainContent("/studentProfilePageFilled.html"); profilePage.click(By.className("close")); }
Source:
protected List<Statement> generateCreateInstanceStatements(final ClassStructureBuilder<?> bodyBlockBuilder, final Injectable injectable, final DependencyGraph graph, final InjectionContext injectionContext) { final List<Statement> stmts = new ArrayList<>(); final String elementVar = "element"; stmts.add(declareFinalVariable(elementVar, elementClass(), elementInitialization())); for (final Property property : properties) { stmts.add(loadVariable(elementVar).invoke("setPropertyString", loadLiteral(property.name()), loadLiteral(property.value()))); } final String retValVar = "retVal"; stmts.add(declareFinalVariable(retValVar, type, invokeStatic(Js.class, "uncheckedCast", loadVariable(elementVar)))); if (implementsNativeHasValueAndRequiresGeneratedInvocation(type)) { stmts.add(Stmt.invokeStatic(NativeHasValueAccessors.class, "registerAccessor", loadVariable(retValVar), createAccessorImpl(type, retValVar))); } stmts.add(loadVariable(retValVar).returnValue()); return stmts; }

Target:
protected List<Statement> generateCreateInstanceStatements(final ClassStructureBuilder<?> bodyBlockBuilder, final Injectable injectable, final DependencyGraph graph, final InjectionContext injectionContext) { final List<Statement> stmts = new ArrayList<>(); final String elementVar = "element"; stmts.add(declareFinalVariable(elementVar, elementClass(), elementInitialization())); for (final Property property : properties) { stmts.add(loadVariable(elementVar).invoke("setPropertyString", loadLiteral(property.name()), loadLiteral(property.value()))); } final String retValVar = "retVal"; stmts.add(declareFinalVariable(retValVar, type, invokeStatic(Js.class, "cast", loadVariable(elementVar)))); if (implementsNativeHasValueAndRequiresGeneratedInvocation(type)) { stmts.add(Stmt.invokeStatic(NativeHasValueAccessors.class, "registerAccessor", loadVariable(retValVar), createAccessorImpl(type, retValVar))); } stmts.add(loadVariable(retValVar).returnValue()); return stmts; }
Source:
public void onMessage(String message) { logger.debug("[{}]: Message received: {}", xbmc.getHostname(), message); Map<String, Object> json; try { json = mapper.readValue(message, Map.class); } catch (JsonParseException e) { logger.error("Error parsing JSON", e); return; } catch (JsonMappingException e) { logger.error("Error mapping JSON", e); return; } catch (IOException e) { logger.error("An I/O error occured while decoding JSON", e); return; } try { if (json.containsKey("method")) { String method = (String)json.get("method"); if (method.startsWith("Player.On")) { processPlayerStateChanged(method, json); } if (method.startsWith("Application.On")) { processApplicationStateChanged(method, json); } } } catch (Exception e) { logger.error("Error handling player state change message", e); } }

Target:
public void onMessage(String message) { logger.debug("[{}]: Message received: {}", xbmc.getHostname(), message); Map<String, Object> json; try { json = mapper.readValue(message, Map.class); } catch (JsonParseException e) { logger.error("Error parsing JSON", e); return; } catch (JsonMappingException e) { logger.error("Error mapping JSON", e); return; } catch (IOException e) { logger.error("An I/O error occured while decoding JSON", e); return; } try { if (json.containsKey("method")) { String method = (String)json.get("method"); if (method.startsWith("Player.On")) { processPlayerStateChanged(method, json); } else if (method.startsWith("Application.On")) { processApplicationStateChanged(method, json); } } } catch (Exception e) { logger.error("Error handling player state change message", e); } }
Source:
private String read(String classPathResource) throws IOException { InputStream is = getClass().getResourceAsStream(classPathResource); try { return Util.read(is); } finally { if (is != null) { is.close(); } } }

Target:
private String read(String classPathResource) throws IOException { InputStream is = getClass().getResourceAsStream(classPathResource); return Util.read(is); }
Source:
private Accessor getAdderForType(Type collectionProperty, String pluralPropertyName) { List<Accessor> candidates; if ( collectionProperty.isCollectionType() ) { candidates = getAccessorCandidates( collectionProperty, Iterable.class ); } else if ( collectionProperty.isStreamType() ) { candidates = getAccessorCandidates( collectionProperty, getClassForName( JavaStreamConstants.STREAM_FQN ) ); } else { return null; } if ( candidates.isEmpty() ) { return null; } if ( candidates.size() == 1 ) { return candidates.get( 0 ); } for ( Accessor candidate : candidates ) { String elementName = accessorNaming.getElementNameForAdder( candidate ); if ( elementName != null && elementName.equals( Nouns.singularize( pluralPropertyName ) ) ) { return candidate; } } return null; }

Target:
private Accessor getAdderForType(Type collectionProperty, String pluralPropertyName) { List<Accessor> candidates; if ( collectionProperty.isCollectionType() ) { candidates = getAccessorCandidates( collectionProperty, Iterable.class ); } else if ( collectionProperty.isStreamType() ) { candidates = getAccessorCandidates( collectionProperty, Stream.class ); } else { return null; } if ( candidates.isEmpty() ) { return null; } if ( candidates.size() == 1 ) { return candidates.get( 0 ); } for ( Accessor candidate : candidates ) { String elementName = accessorNaming.getElementNameForAdder( candidate ); if ( elementName != null && elementName.equals( Nouns.singularize( pluralPropertyName ) ) ) { return candidate; } } return null; }
Source:
private boolean isJavaProject(String path) { Optional<RegisteredProject> project = projectManager.get(path); return (project.isPresent() && (project.get().getType().equals(MavenAttributes.MAVEN_ID) || project.get().getType().equals(Constants.JAVAC))); }

Target:
private boolean isJavaProject(String path) { Optional<RegisteredProject> project = projectManager.get(path); return (project.isPresent() && (MavenAttributes.MAVEN_ID.equals(project.get().getType()) || Constants.JAVAC.equals(project.get().getType()))); }
Source:
public void ArticleCRUDUser_003_addDropdown() { WikiBasePageObject base = new WikiBasePageObject(driver); String articleContent = PageContent.articleText; String articleTitle = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openRandomArticle(wikiURL); VisualEditModePageObject visualEditMode = article.createArticleUsingDropdown(articleTitle); visualEditMode.addContent(articleContent); visualEditMode.submit(PageType.Article); article.verifyContent(articleContent); article.verifyArticleTitle(articleTitle); }

Target:
public void ArticleCRUDUser_003_addDropdown() { WikiBasePageObject base = new WikiBasePageObject(driver); String articleContent = PageContent.articleText; String articleTitle = PageContent.articleNamePrefix + base.getTimeStamp(); ArticlePageObject article = base.openRandomArticle(wikiURL); VisualEditModePageObject visualEditMode = article.createArticleUsingDropdown(articleTitle); visualEditMode.addContent(articleContent); visualEditMode.submitArticle(); article.verifyContent(articleContent); article.verifyArticleTitle(articleTitle); }
Source:
public static CreateServerIp create(final List<String> serverIps) { return new AutoValue_FirewallPolicy_ServerIp_CreateServerIp(serverIps == null ? ImmutableList.<String>of() : serverIps); }

Target:
public static CreateServerIp create(final List<String> serverIps) { return new AutoValue_FirewallPolicy_ServerIp_CreateServerIp(serverIps == null ? ImmutableList.<String>of() : ImmutableList.copyOf(serverIps)); }
Source:
public void testRegisterProcessorId() { String assignedPath = zkUtils.registerProcessorAndGetId("0.0.0.0 1"); Assert.assertTrue(assignedPath.startsWith(KEY_BUILDER.getProcessorsPath())); Assert.assertTrue(zkUtils.registerProcessorAndGetId("0.0.0.0 1").equals(assignedPath)); }

Target:
public void testRegisterProcessorId() { String assignedPath = zkUtils.registerProcessorAndGetId(new ProcessorData("host", "1")); Assert.assertTrue(assignedPath.startsWith(KEY_BUILDER.getProcessorsPath())); Assert.assertTrue(zkUtils.registerProcessorAndGetId(new ProcessorData("host", "1")).equals(assignedPath)); }
Source:
public boolean deleteRecommendation(String postUuid) throws ForumServiceException{ String recommendationsUrl = resolveUrl(ForumType.RECOMMENDATIONS, FilterType.ENTRIES); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(POST_UNIQUE_IDENTIFIER, postUuid); boolean success = true; try { deleteData(recommendationsUrl, parameters, postUuid); } catch (Exception e) { success = false; throw new ForumServiceException(e); } return success; }

Target:
public boolean deleteRecommendation(String postUuid) throws ForumServiceException{ if(StringUtil.isNotEmpty(this.endpoint.getApiVersion())){ double apiVersion = Double.parseDouble(this.endpoint.getApiVersion()); if(APIVERSION > apiVersion ){ throw new UnsupportedOperationException("This API is only supported on connections 4.5 or above"); } } String recommendationsUrl = resolveUrl(ForumType.RECOMMENDATIONS, FilterType.ENTRIES); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(POST_UNIQUE_IDENTIFIER, postUuid); try { deleteData(recommendationsUrl, parameters, postUuid); return true; } catch (Exception e) { throw new ForumServiceException(e); } }
Source:
protected CommandContext createUpdateVmContext(VmStatic vmStatic) { ExecutionContext ctx = new ExecutionContext(); try { Step step = executionHandler.addSubStep(getExecutionContext(), getExecutionContext().getJob().getStep(StepEnum.EXECUTING), StepEnum.UPDATE_VM, ExecutionMessageDirector.resolveStepMessage( StepEnum.UPDATE_VM, Collections.singletonMap(VdcObjectType.VM.name().toLowerCase(), vmStatic.getName()))); ctx.setJob(getExecutionContext().getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for AddVmFromScratch", e); } return cloneContextAndDetachFromParent().withExecutionContext(ctx); }

Target:
protected CommandContext createUpdateVmContext(VmStatic vmStatic) { ExecutionContext ctx = new ExecutionContext(); try { Step step = executionHandler.addSubStep(getExecutionContext(), getExecutionContext().getJob().getStep(StepEnum.EXECUTING), StepEnum.UPDATE_VM, ExecutionMessageDirector.resolveStepMessage( StepEnum.UPDATE_VM, Collections.singletonMap(VdcObjectType.VM.name().toLowerCase(), vmStatic.getName()))); ctx.setJob(getExecutionContext().getJob()); ctx.setStep(step); ctx.setMonitored(true); } catch (RuntimeException e) { log.error("Failed to create ExecutionContext for UpdateVM", e); } return cloneContextAndDetachFromParent().withExecutionContext(ctx); }