text:
package org.apache.axis2.jaxws.description;

import junit.framework.TestCase;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.AsyncHandler;
import javax.xml.ws.Response;
import java.util.concurrent.Future;

/**
 *
 */
public class GetSyncOperationTests extends TestCase {

    public void testNoSyncOperation() {
        ServiceDescription sDesc =
            DescriptionFactory.createServiceDescription(null,
                                                        new QName("org.apache.axis2.jaxws.description", "syncOperationTestService2"),
                                                        javax.xml.ws.Service.class);
        EndpointDescription eDesc =
            DescriptionFactory.updateEndpoint(sDesc,
                                              AsyncOnlySEI.class,
                                              new QName("org.apache.axis2.jaxws.description", "syncOperationTestPort2"),
                                              DescriptionFactory.UpdateType.GET_PORT);
        EndpointInterfaceDescription eiDesc = eDesc.getEndpointInterfaceDescription();
        OperationDescription opDescs[] = eiDesc.getOperations();
        assertNotNull(opDescs);
        assertEquals(2, opDescs.length);
        // Make sure each of the async operations reference the sync opDesc
        int asyncOperations = 0;
        OperationDescription syncOpDescs[] = eiDesc.getOperationForJavaMethod("echo");
        assertNull(syncOpDescs);
        for (OperationDescription opDesc : opDescs) {
            if (opDesc.isJAXWSAsyncClientMethod()) {
                asyncOperations++;
            }
            // Since there isn't a sync method in the (invalid) SEI, then this should return null
            assertNull(opDesc.getSyncOperation());
        }
        assertEquals(2, asyncOperations);
    }

    public void testSyncOperation() {
        ServiceDescription sDesc =
            DescriptionFactory.createServiceDescription(null,
                                                        new QName("org.apache.axis2.jaxws.description", "syncOperationTestService1"),
                                                        javax.xml.ws.Service.class);
        EndpointDescription eDesc =
            DescriptionFactory.updateEndpoint(sDesc,
                                              SyncAndAsyncSEI.class,
                                              new QName("org.apache.axis2.jaxws.description", "syncOperationTestPort1"),
                                              DescriptionFactory.UpdateType.GET_PORT);
        EndpointInterfaceDescription eiDesc = eDesc.getEndpointInterfaceDescription();
        OperationDescription opDescs[] = eiDesc.getOperations();
        assertNotNull(opDescs);
        assertEquals(3, opDescs.length);
        // Make sure each of the async operations reference the sync opDesc
        int asyncOperations = 0;
        OperationDescription syncOpDescs[] = eiDesc.getOperationForJavaMethod("echo");
        assertNotNull(syncOpDescs);
        assertEquals(1, syncOpDescs.length);
        OperationDescription syncOpDesc = syncOpDescs[0];

        for (OperationDescription opDesc : opDescs) {
            if (opDesc.isJAXWSAsyncClientMethod()) {
                asyncOperations++;
            }
            // Make sure all the operations point to the sync operation
            assertEquals(syncOpDesc, opDesc.getSyncOperation());
        }

        assertEquals(2, asyncOperations);
    }

}

@WebService
interface AsyncOnlySEI {
    // Note this is an INVALID SEI since it only contains the
    // JAXWS client async methods, and not the corresponding sync
    // method.
    @WebMethod(operationName = "echo")
    public Response<String> echoAsync(String toEcho);
    @WebMethod(operationName = "echo")
    public Future<?> echoAsync(String toEcho, AsyncHandler<String> asyncHandler);
}

@WebService
interface SyncAndAsyncSEI {
    @WebMethod(operationName = "echo")
    public Response<String> echoAsync(String toEcho);
    @WebMethod(operationName = "echo")
    public Future<?> echoAsync(String toEcho, AsyncHandler<String> asyncHandler);
    @WebMethod(operationName = "echo")
    public String echo(String toEcho);
}


text:
@interface NSString (XAlign)
- (NSString *)xtrim;
- (NSString *)xtrimTail;
- (NSUInteger)xlength;
- (NSString *)stringByAligningWithPatterns:(NSArray *)patterns;
- (NSString *)stringByAligningWithPatterns:(NSArray *)patterns partialCount:(NSUInteger)count;
- (NSArray *)componentsSeparatedByRegexPattern:(NSString *)pattern position:(XAlignPosition)position match:(NSString **)match;
@end

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.TrafficManager.Testing.ScenarioTests
{
    using System.Collections.Generic;
    using System.Linq;
    using global::TrafficManager.Tests.Helpers;
    using Microsoft.Azure.Management.Resources.Models;
    using Microsoft.Azure.Management.TrafficManager.Models;
    using Microsoft.Azure.Management.TrafficManager.Testing.Helpers;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using Xunit;

    public class GeographicHierarchyScenarioTests : TestBase
    {
        [Fact]
        public void GetDefaultGeographicHierarchy()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                TrafficManagerManagementClient trafficManagerClient = this.GetTrafficManagerManagementClient(context);

                TrafficManagerGeographicHierarchy getHierarchyResponse = trafficManagerClient.GeographicHierarchies.GetDefault();
                Assert.NotNull(getHierarchyResponse);
                Assert.Equal("/providers/Microsoft.Network/trafficManagerGeographicHierarchies/default", getHierarchyResponse.Id);
                Assert.Equal("Microsoft.Network/trafficManagerGeographicHierarchies", getHierarchyResponse.Type);
                Assert.Equal("default", getHierarchyResponse.Name);

                Assert.NotNull(getHierarchyResponse.GeographicHierarchy);
                Region root = getHierarchyResponse.GeographicHierarchy;

                Assert.Equal("WORLD", root.Code);
                Assert.Equal("World", root.Name);
                Assert.NotEmpty(root.Regions);

                foreach (var grouping in root.Regions)
                {
                    Assert.NotNull(grouping.Code);
                    Assert.NotEmpty(grouping.Code);
                    Assert.NotNull(grouping.Name);
                    Assert.NotEmpty(grouping.Name);
                    Assert.NotEmpty(grouping.Regions);
                }
            }
        }
    }
}


text:
class ExtensionServiceInterface;
class GURL;

namespace base {
class ListValue;
}

namespace drive {
class DriveServiceInterface;
class DriveUploaderInterface;
}

namespace storage {
class FileSystemURL;
}

namespace leveldb {
class Env;
}

namespace sync_file_system {

class FileChange;
class SyncFileMetadata;

namespace drive_backend {

class LocalToRemoteSyncer;
class MetadataDatabase;
class RemoteChangeProcessorOnWorker;
class RemoteToLocalSyncer;
class SyncEngineContext;
class SyncEngineInitializer;

class SyncWorker : public SyncWorkerInterface,
                   public SyncTaskManager::Client {
 public:
  SyncWorker(const base::FilePath& base_dir,
             const base::WeakPtr<ExtensionServiceInterface>& extension_service,
             leveldb::Env* env_override);

  ~SyncWorker() override;

  void Initialize(std::unique_ptr<SyncEngineContext> context) override;

  // SyncTaskManager::Client overrides
  void MaybeScheduleNextTask() override;
  void NotifyLastOperationStatus(SyncStatusCode sync_status,
                                 bool used_network) override;
  void RecordTaskLog(std::unique_ptr<TaskLogger::TaskLog> task_log) override;

  // SyncWorkerInterface overrides
  void RegisterOrigin(const GURL& origin,
                      const SyncStatusCallback& callback) override;
  void EnableOrigin(const GURL& origin,
                    const SyncStatusCallback& callback) override;
  void DisableOrigin(const GURL& origin,
                     const SyncStatusCallback& callback) override;
  void UninstallOrigin(const GURL& origin,
                       RemoteFileSyncService::UninstallFlag flag,
                       const SyncStatusCallback& callback) override;
  void ProcessRemoteChange(const SyncFileCallback& callback) override;
  void SetRemoteChangeProcessor(RemoteChangeProcessorOnWorker*
                                    remote_change_processor_on_worker) override;
  RemoteServiceState GetCurrentState() const override;
  void GetOriginStatusMap(
      const RemoteFileSyncService::StatusMapCallback& callback) override;
  std::unique_ptr<base::ListValue> DumpFiles(const GURL& origin) override;
  std::unique_ptr<base::ListValue> DumpDatabase() override;
  void SetSyncEnabled(bool enabled) override;
  void PromoteDemotedChanges(const base::Closure& callback) override;
  void ApplyLocalChange(const FileChange& local_change,
                        const base::FilePath& local_path,
                        const SyncFileMetadata& local_metadata,
                        const storage::FileSystemURL& url,
                        const SyncStatusCallback& callback) override;
  void ActivateService(RemoteServiceState service_state,
                       const std::string& description) override;
  void DeactivateService(const std::string& description) override;
  void DetachFromSequence() override;
  void AddObserver(Observer* observer) override;

 private:
  friend class DriveBackendSyncTest;
  friend class SyncWorkerTest;

  enum AppStatus {
    APP_STATUS_ENABLED,
    APP_STATUS_DISABLED,
    APP_STATUS_UNINSTALLED,
  };

  typedef base::hash_map<std::string, AppStatus> AppStatusMap;

  void DoDisableApp(const std::string& app_id,
                    const SyncStatusCallback& callback);
  void DoEnableApp(const std::string& app_id,
                   const SyncStatusCallback& callback);

  void PostInitializeTask();
  void DidInitialize(SyncEngineInitializer* initializer,
                     SyncStatusCode status);
  void UpdateRegisteredApps();
  static void QueryAppStatusOnUIThread(
      const base::WeakPtr<ExtensionServiceInterface>& extension_service_ptr,
      const std::vector<std::string>* app_ids,
      AppStatusMap* status,
      const base::Closure& callback);
  void DidQueryAppStatus(const AppStatusMap* app_status);
  void DidProcessRemoteChange(RemoteToLocalSyncer* syncer,
                              const SyncFileCallback& callback,
                              SyncStatusCode status);
  void DidApplyLocalChange(LocalToRemoteSyncer* syncer,
                           const SyncStatusCallback& callback,
                           SyncStatusCode status);

  // Returns true if a FetchChanges task is scheduled.
  bool MaybeStartFetchChanges();
  void DidResolveConflict(SyncStatusCode status);
  void DidFetchChanges(SyncStatusCode status);

  void UpdateServiceStateFromSyncStatusCode(SyncStatusCode state,
                                            bool used_network);
  void UpdateServiceState(RemoteServiceState state,
                          const std::string& description);

  void CallOnIdleForTesting(const base::Closure& callback);

  drive::DriveServiceInterface* GetDriveService();
  drive::DriveUploaderInterface* GetDriveUploader();
  MetadataDatabase* GetMetadataDatabase();

  base::FilePath base_dir_;

  leveldb::Env* env_override_;

  // Sync with SyncEngine.
  RemoteServiceState service_state_;

  bool should_check_conflict_;
  bool should_check_remote_change_;
  bool listing_remote_changes_;
  base::TimeTicks time_to_check_changes_;

  bool sync_enabled_;
  base::Closure call_on_idle_callback_;

  std::unique_ptr<SyncTaskManager> task_manager_;

  base::WeakPtr<ExtensionServiceInterface> extension_service_;

  std::unique_ptr<SyncEngineContext> context_;
  base::ObserverList<Observer> observers_;

  base::SequenceChecker sequence_checker_;

  base::WeakPtrFactory<SyncWorker> weak_ptr_factory_;
  DISALLOW_COPY_AND_ASSIGN(SyncWorker);
};

}  // namespace drive_backend
}  // namespace sync_file_system

#endif  // CHROME_BROWSER_SYNC_FILE_SYSTEM_DRIVE_BACKEND_SYNC_WORKER_H_


text:
<?php $this->load->helper('url'); ?>
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>SGV - Administrar Usuarios</title>

        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bower_components/fullcalendar/dist/fullcalendar.min.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bower_components/animate.css/animate.min.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bower_components/bootstrap-sweetalert/lib/sweet-alert.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bootstrap-validator/bootstrapValidator.min.css" />
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bower_components/material-design-iconic-font/dist/css/material-design-iconic-font.min.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bower_components/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.min.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/vendors/bootgrid/jquery.bootgrid.min.css">

        <link rel="stylesheet" href="<?php echo base_url()?>public/css/app.min.1.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/css/app.min.2.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/css/general.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/plugins/mdl-icons/material-icons.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/plugins/bootstrap-table/bootstrap-table.min.css">
        <link rel="stylesheet" href="<?php echo base_url()?>public/plugins/mdl/material.min.css">

        <?php echo $cabecera ?>

                <?php echo $menu ?>

Administrar Usuarios

Lista de Usuarios

            	             <?php echo $tableUsers ?>


text:
var isInteger = require('is-integer');

//
// NOTE: use array.{every|some} in the case of booleans
//

exports.aggregateNumbers = function aggregateNumbers(numbers) {
  return numbers.reduce(function(m, v) {
    v = Number(v);
    if (typeof v !== 'number' || isNaN(v)) {
      throw new Error(numbers + ' is invalid numbers');
    }
    return m + v;
  }, 0.0);
};

exports.aggregateIntegers = function aggregateIntegers(integers) {
  return integers.reduce(function(m, v) {
    v = Number(v);
    if (typeof v !== 'number' || isNaN(v) || !isInteger(v)) {
      throw new Error(integers + ' is invalid integers');
    }
    return m + v;
  }, 0);
};

exports.aggregateRates = function aggregateRates(rates) {
  var rate = rates.reduce(function(m, v) {
    if (v < 0.0) {
      throw new Error(rates + ' is invalid rates');
    }
    return m * v;
  }, 1.0);
  return Math.max(rate, 0.0);
};

/**
 * @example
 *   ([0.2, 0.3])
 *   = 1.0 - ((1.0 - 0.2) * (1.0 - 0.3))
 *   = 1.0 - 0.56 = 0.44
 */
exports.aggregateChances = function aggregateChances(chances) {
  var exclusiveProb = chances.reduce(function(m, v) {
    if (v < 0 || v > 1.0) {
      throw new Error(chances + ' is invalid chances');
    }
    return m * (1.0 - v);
  }, 1.0);
  return 1.0 - exclusiveProb;
};


text:
@interface DateItem : NSObject
@property (nonatomic, assign) NSInteger day;
@property (nonatomic, assign) NSInteger hour;
@property (nonatomic, assign) NSInteger minute;
@property (nonatomic, assign) NSInteger second;
@end

@interface NSDate (Extension)
- (DateItem *)intervalSinceDate:(NSDate *)anotherDate;

- (BOOL)isToday;
- (BOOL)isYesterday;
- (BOOL)isTomorrow;
- (BOOL)isThisYear;
//获取今天周几
- (NSInteger)getNowWeekday;
@end


text:
__author__ = 'zhwei'

from django import forms
from django.forms.models import model_to_dict, fields_for_model
from django.contrib.sites.models import Site
from django.db.models import Q

from .models import Website, Links
from ..accounts.models import User
from ..region.models import Region

class StaffSiteForm(forms.ModelForm):

    """ 分站管理员使用
    """

    class Meta:
        model = Website
        exclude = ('admin')

class CreateSiteForm(forms.ModelForm):
    """ 管理员创建站点
    """

    def __init__(self, *args, **kwargs):
        super(CreateSiteForm, self).__init__(*args, **kwargs)
        self.fields['admin'].queryset = User.objects.filter(is_staff=True,
                                                            is_superuser=False,
                                                            website=None)
    class Meta:
        model = Website

class RegionWebsiteForm(forms.ModelForm):

    regions = forms.ModelMultipleChoiceField(label='城市列表',queryset=None,
                                             help_text='按住<b>Ctrl</b>键多选')

    def __init__(self, *args, **kwargs):
        super(RegionWebsiteForm, self).__init__(*args, **kwargs)
        self.fields['name'].widget.attrs['readonly'] = True
        self.fields['regions'].queryset=Region.objects.filter(Q(parent=None, website=self.instance) | Q(parent=None, website=None))
        self.fields['regions'].initial = self.instance.region_set.all()

    def save(self, commit=True):
        ret = super(RegionWebsiteForm, self).save(commit=False)
        old_region_list = set(Region.objects.filter(website=self.instance))
        new_region_list = set(self.cleaned_data['regions'])
        for r in old_region_list-new_region_list:
            r.website = None
            r.save()
        for r in new_region_list - old_region_list:
            r.website = self.instance
            r.save()
        ret.save()

    class Meta:
        model = Website
        fields = ('name',)

class MyFreLinkForm(forms.ModelForm):
    """ 友情链接Form
    """
    def __init__(self, user=None,*args, **kwargs):
        super(MyFreLinkForm, self).__init__(*args, **kwargs)
        self._user = user

    def save(self, commit=True):
        ret = super(MyFreLinkForm, self).save(commit=False)
        ret.site = self._user.website
        ret.save()

    class Meta:
        model = Links
        fields = ('name', 'url')


text:
package org.apache.camel.component.aws.sqs;

import java.util.Map;

import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;

import org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension;
import org.apache.camel.component.extension.verifier.ResultBuilder;
import org.apache.camel.component.extension.verifier.ResultErrorBuilder;
import org.apache.camel.component.extension.verifier.ResultErrorHelper;

public class SqsComponentVerifierExtension extends DefaultComponentVerifierExtension {

    public SqsComponentVerifierExtension() {
        this("aws-sqs");
    }

    public SqsComponentVerifierExtension(String scheme) {
        super(scheme);
    }

    // *********************************
    // Parameters validation
    // *********************************

    @Override
    protected Result verifyParameters(Map<String, Object> parameters) {

        ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS).error(ResultErrorHelper.requiresOption("accessKey", parameters))
            .error(ResultErrorHelper.requiresOption("secretKey", parameters)).error(ResultErrorHelper.requiresOption("region", parameters));

        // Validate using the catalog

        super.verifyParametersAgainstCatalog(builder, parameters);

        return builder.build();
    }

    // *********************************
    // Connectivity validation
    // *********************************

    @Override
    protected Result verifyConnectivity(Map<String, Object> parameters) {
        ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

        try {
            SqsConfiguration configuration = setProperties(new SqsConfiguration(), parameters);
            AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey());
            AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
            AmazonSQS client = AmazonSQSClientBuilder.standard().withCredentials(credentialsProvider).withRegion(Regions.valueOf(configuration.getRegion())).build();
            client.listQueues();
        } catch (SdkClientException e) {
            ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
                .detail("aws_sqs_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
                .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

            builder.error(errorBuilder.build());
        } catch (Exception e) {
            builder.error(ResultErrorBuilder.withException(e).build());
        }
        return builder.build();
    }
}


text:
alter table Company add homeURL varchar(2000) null;

alter table ExpandoColumn add companyId bigint;
alter table ExpandoColumn add defaultData varchar(2000) null;
alter table ExpandoColumn add typeSettings text null;

alter table ExpandoRow add companyId bigint;

alter table ExpandoTable add companyId bigint;

alter table ExpandoValue add companyId bigint;

alter table JournalArticleImage add elInstanceId varchar(75) null;

alter table JournalStructure add parentStructureId varchar(75);

create table MBMailingList (
	uuid_ varchar(75) null,
	mailingListId bigint not null primary key,
	groupId bigint,
	companyId bigint,
	userId bigint,
	userName varchar(75) null,
	createDate datetime null,
	modifiedDate datetime null,
	categoryId bigint,
	emailAddress varchar(75) null,
	inProtocol varchar(75) null,
	inServerName varchar(75) null,
	inServerPort int,
	inUseSSL bit,
	inUserName varchar(75) null,
	inPassword varchar(75) null,
	inReadInterval int,
	outEmailAddress varchar(75) null,
	outCustom bit,
	outServerName varchar(75) null,
	outServerPort int,
	outUseSSL bit,
	outUserName varchar(75) null,
	outPassword varchar(75) null,
	active_ bit
);

alter table Organization_ add type_ varchar(75);

alter table Role_ add title varchar(2000) null;
alter table Role_ add subtype varchar(75);

alter table TagsAsset add visible bit;

go

update TagsAsset set visible = 1;

alter table TagsEntry add groupId bigint;
alter table TagsEntry add parentEntryId bigint;
alter table TagsEntry add vocabularyId bigint;

go

update TagsEntry set groupId = 0;
update TagsEntry set parentEntryId = 0;
update TagsEntry set vocabularyId = 0;

create table TagsVocabulary (
	vocabularyId bigint not null primary key,
	groupId bigint,
	companyId bigint,
	userId bigint,
	userName varchar(75) null,
	createDate datetime null,
	modifiedDate datetime null,
	name varchar(75) null,
	description varchar(75) null,
	folksonomy bit
);

alter table User_ add reminderQueryQuestion varchar(2000) null;
alter table User_ add reminderQueryAnswer varchar(2000) null;

create table WSRPConfiguredProducer (
	configuredProducerId bigint not null primary key,
	name varchar(75) null,
	portalId varchar(75) null,
	namespace varchar(75) null,
	producerURL varchar(256) null,
	producerVersion varchar(75) null,
	producerMarkupURL varchar(256) null,
	status int,
	registrationData text null,
	registrationContext text null,
	serviceDescription text null,
	userCategoryMapping text null,
	customUserProfile text null,
	identityPropagationType varchar(75) null,
	lifetimeTerminationTime varchar(75) null,
	sdLastModified bigint,
	entityVersion int
);

create table WSRPConsumerRegistration (
	consumerRegistrationId bigint not null primary key,
	consumerName varchar(100) null,
	status bit,
	registrationHandle varchar(75) null,
	registrationData text null,
	lifetimeTerminationTime varchar(75) null,
	producerKey varchar(75) null
);

create table WSRPPortlet (
	portletId bigint not null primary key,
	name varchar(75) null,
	channelName varchar(75) null,
	title varchar(75) null,
	shortTitle varchar(75) null,
	displayName varchar(75) null,
	keywords varchar(75) null,
	status int,
	producerEntityId varchar(75) null,
	consumerId varchar(75) null,
	portletHandle varchar(75) null,
	mimeTypes varchar(2000) null
);

create table WSRPProducer (
	producerId bigint not null primary key,
	portalId varchar(75) null,
	status bit,
	namespace varchar(75) null,
	instanceName varchar(75) null,
	requiresRegistration bit,
	supportsInbandRegistration bit,
	version varchar(75) null,
	offeredPortlets varchar(2000) null,
	producerProfileMap varchar(75) null,
	registrationProperties varchar(2000) null,
	registrationValidatorClass varchar(200) null
);


text:
/* -*-C++-*-
****************************************************************************
*
* File:         PartKeyDist.h
* Description:
*
* Created:      8/5/1998
* Language:     C++
*
*
**************************************************************************** */

#include "PartKeyDist.h"
#include "hs_const.h"     /* HS_MAX_BOUNDARY_LEN */
#include "parser.h"      /* for the parser of EncodedValues */

// -----------------------------------------------------------------------
//  methods on PartitionKeyDistribution class -- just ctors for now
// -----------------------------------------------------------------------

PartitionKeyDistribution::PartitionKeyDistribution ()
     : partitionBoundaries_ (HistogramSharedPtr(0), HISTHEAP), /* init to invalid value */
       partitionFactors_ (HISTHEAP, 0),       /* init to invalid value */
       partitionKeyId_ (NULL_VALUE_ID),       /* init to invalid value */
       objectInfoIsValid_ (FALSE)             /* init to invalid value */
{}

PartitionKeyDistribution::PartitionKeyDistribution (
     const RangePartitioningFunction & partFunc,
     const ColStatDescList           & inputHistograms)
     : partitionBoundaries_ (HistogramSharedPtr(0), HISTHEAP), /* init to invalid value */
       partitionFactors_ (HISTHEAP, 0),       /* init to invalid value */
       partitionKeyId_ (NULL_VALUE_ID),       /* init to invalid value */
       objectInfoIsValid_ (FALSE)             /* init to invalid value */
{

  // -----------------------------------------------------------------------
  //  Get the partition boundaries:
  // -----------------------------------------------------------------------
  NAList<EncodedValueList *> boundaries(CmpCommon::statementHeap());
  const RangePartitionBoundaries *rpBoundariesPtr = partFunc.getRangePartitionBoundaries();

  // There are n+1 partition boundaries for n partitions:
  const CollIndex numPartBounds = CollIndex(partFunc.getCountOfPartitions()+1);
  for (CollIndex i=0; i < numPartBounds; i++)
    {
      EncodedValueList *evl = new (CmpCommon::statementHeap())
                              EncodedValueList(CmpCommon::statementHeap(), 0);

      boundaries.insertAt(i, evl);
      const ItemExprList *boundary = rpBoundariesPtr->getBoundaryValues(i);

      // transform to encoded value list
      for (CollIndex j=0; j < boundary->entries(); j++)
        {
          EncodedValue ev((*boundary)[j], FALSE /* "negate" */);
          (boundaries[i])->insertAt(j,ev);
        }
    }

  const ValueIdList listOfPartitionKeys = partFunc.getKeyColumnList();
  const ValueIdList listOfPartitionKeyOrders = partFunc.getOrderOfKeyValues() ;

  // CSDL::divideHistogramAtPartitionBoundaries() returns FALSE if, for
  // some reason, the histogram-to-partition-boundary-list mapping fails
  //
  // if it returns TRUE, then we know that the PartitionKeyDistribution
  // data members partitionBoundaries_ and partitionKeyId_ have been
  // set to valid values.

  if ( inputHistograms.divideHistogramAtPartitionBoundaries (
       listOfPartitionKeys,      /* in  */
       listOfPartitionKeyOrders, /* in  */
       boundaries,               /* in  */
       partitionKeyId_,          /* out */
       isPartitionKeyAscending_, /* out */
       partitionBoundaries_,     /* out */
       partitionFactors_         /* out */ ) == TRUE )
    {
      objectInfoIsValid_ = TRUE ;
    }

} // PartitionKeyDistribution::PartitionKeyDistribution

CollIndex
PartitionKeyDistribution::getHistIdxFromPartIdx (CollIndex extIdx) const
{
  // Since our "internal" representation of the partition boundaries
  // doesn't (necessarily) share the same numbering scheme as the
  // "external" world's view of the partition boundaries, we need to
  // be able to convert from the "external" to "internal" view.
  //
  // Note that there is a n-to-1 mapping between the "external" partitions
  // and the "internal" histogram intervals.  Thus, we can convert exactly
  // from "external" to "internal", but not the other way (a *range* of
  // partitions could be returned, if this functionality is required
  // ... but I don't think it is).
  //
  // Note also that if the partitioning key is in DESCENDING order (a
  // value of FALSE stored in isPartitionKeyAscending_), then we need
  // to provide the "inverse" hist idx.  See PartKeyDist.h for a careful
  // description of what's going on.

  DCMPASSERT(extIdx >= 0 AND extIdx < getNumPartitions());

  CollIndex countParts, interval ;

  if ( isPartitionKeyAscending_ == FALSE )
    {
      CollIndex numParts = getNumPartitions() ;
      // now "flip-flop", since we reversed the boundaries, so we have to
      // "reverse" everything we do when talking about them
      extIdx = numParts - extIdx - 1;
    }

  extIdx += 1 ; // we're zero-based when talking about Partition#
  countParts = 0 ;

  for ( interval = 1 ; interval < partitionFactors_.entries() ; interval++ )
    {
      countParts += partitionFactors_[interval] ;
      if ( countParts >= extIdx )
        break ;
    }

  DCMPASSERT ( countParts >= extIdx ) ; // if not, the index was bad! (or logic wrong!!!)

  // "interval" contains the HistInt index corresponding to the partition
  // requested; OR, it contains the HistInt corresponding to a number of
  // partitions, one of which is the one that was requested.
  return interval ;
}

CostScalar
PartitionKeyDistribution::getRowsForPartition(CollIndex extIdx) const
{
  // The first entry in the histogram will never contain rows because
  // it corresponds to a "partition" for all rows below "MIN".
  // No rows satisfy this. Thus, the first partition is described
  // by the first interval.
  DCMPASSERT(extIdx >= 0 AND extIdx < getNumPartitions());

  // remember : each entry in the histogram represents potentially many
  // different partition boundaries, each with the same partition boundary value.
  CollIndex interval = getHistIdxFromPartIdx (extIdx) ;

  // If there is more than one partition represented by this histogram
  // interval, then we assume that all of the rows in this histogram
  // interval are uniformly distributed between all of them.
  return (*Hist())[interval].getCardinality() / partitionFactors_[interval] ;
}

CostScalar
PartitionKeyDistribution::getUecForPartition (CollIndex extIdx) const
{
  // remember : each entry in the histogram represents potentially many
  // different partition boundaries, each with the same partition boundary value.
  CollIndex interval = getHistIdxFromPartIdx (extIdx) ;

  // If there is more than one partition represented by this histogram
  // interval, then we assume that all of the uec in this histogram
  // interval are uniformly distributed between all of them.
  return (*Hist())[interval].getUec() / partitionFactors_[interval];
}

CollIndex
PartitionKeyDistribution::getNumPartitions () const
{
  // remember : each entry in the histogram represents potentially many
  // different partition boundaries, each with the same partition boundary value.
  CollIndex numParts = 0 ;

  // don't count that first HistInt's counter
  for ( CollIndex i = 1 ; i < partitionFactors_.entries() ; i++ )
    numParts += partitionFactors_[i] ;

  // CollIndex numParts = Hist()->entries() - 1;
  return numParts;
}

CollIndex
PartitionKeyDistribution::getMaxPartitionFactor() const
{

  CollIndex max = 0;
  for ( CollIndex i = 1 ; i < partitionFactors_.entries() ; i++ )
    {
      if (partitionFactors_[i] > max)
        max = partitionFactors_[i];
    }

  return max;
}

// eof