예제 #1
0
        public static void init()
        {
            var         icon          = AbstractResourceTest.GetTestAbstractImage();
            ClusterType t1            = null;
            var         yieldResource =
                getTestSingularGameResourceYield(
                    type: GameResourceTest.getTestGameResourceType(),
                    value: 500
                    );
            var fullYield =
                GameResourceYieldTest.GetTestFinishedGameResourceYield(yields: yieldResource);
            YieldModifier yieldMod = (yield) => yield.scalePure(2).readOnly();

            Assert.DoesNotThrow(() => t1 = getTestClusterType(
                                    id: 0,
                                    image: icon,
                                    name: "Test1",
                                    desc: "TestD1",
                                    mod: yieldMod
                                    ));


            Assert.Multiple(() => {
                Assert.AreEqual(0, t1.id);
                Assert.AreEqual("Test1", t1.name);
                Assert.AreEqual("TestD1", t1.description);
                Assert.AreEqual(icon, t1.icon);
                Assert.AreNotSame(fullYield, t1.modifyYield(fullYield));
                Assert.AreNotEqual(fullYield, t1.modifyYield(fullYield));
            });
        }
예제 #2
0
        public void Run(ClusterType clustertype)
        {
            switch (clustertype)
            {
            case ClusterType.Grid:
                _clusters           = new GridCluster(_points).GetCluster();
                DisplayGridInCanvas = true;
                break;

            case ClusterType.KMeans:
                _clusters = new KMeans(_points).GetCluster();
                break;

            case ClusterType.MarkerClusterer:
                _clusters = new MarkerClusterer(_points).GetCluster();
                break;

            case ClusterType.DistanceClusterer:
                _clusters = new DistanceClusterer(_points).GetCluster();
                break;

            case ClusterType.Unknown:
                break;
            }
        }
예제 #3
0
 private ZclClusterType(int clusterId, string label, ClusterType clusterType, Func <ZigBeeEndpoint, ZclCluster> clusterFactory)
 {
     this.ClusterId      = clusterId;
     this.Label          = label;
     this.Type           = clusterType;
     this.ClusterFactory = clusterFactory;
 }
예제 #4
0
 // static methods
 internal static ClusterDescription CreateInitial(ClusterId clusterId, ClusterType clusterType)
 {
     return(new ClusterDescription(
                clusterId,
                clusterType,
                Enumerable.Empty <ServerDescription>()));
 }
예제 #5
0
 public TrainingSample(string observation, int variable1, int variable2, ClusterType clusterType)
 {
     this.Observation = observation;
     this.Variable1   = variable1;
     this.Variable2   = variable2;
     this.ClusterType = clusterType;
 }
        public static void DeleteClusterIfExists(ClusterType clusterType)
        {
            var name = AppConfig.AzureResourceName + clusterType.ToString().ToLowerInvariant();

            LOG.Info(String.Format("Deleting Cluster: Name = {0}, Type = {1}", name, clusterType));
            DeleteClusterIfExists(name);
        }
예제 #7
0
        private bool IsServerValidForCluster(ClusterType clusterType, ClusterConnectionMode connectionMode, ServerType serverType)
        {
            switch (clusterType)
            {
            case ClusterType.Standalone:
                return(serverType == ServerType.Standalone);

            case ClusterType.ReplicaSet:
                return(serverType.IsReplicaSetMember());

            case ClusterType.Sharded:
                return(serverType == ServerType.ShardRouter);

            case ClusterType.Unknown:
                switch (connectionMode)
                {
                case ClusterConnectionMode.Automatic:
                    if (serverType == ServerType.Standalone)
                    {
                        return(Settings.Scheme == ConnectionStringScheme.MongoDBPlusSrv);        // Standalone is only valid in MultiServerCluster when using MongoDBPlusSrv scheme
                    }
                    return(serverType.IsReplicaSetMember() || serverType == ServerType.ShardRouter);

                default:
                    throw new MongoInternalException("Unexpected connection mode.");
                }

            default:
                throw new MongoInternalException("Unexpected cluster type.");
            }
        }
예제 #8
0
        private bool IsServerValidForCluster(ClusterType clusterType, ClusterConnectionMode connectionMode, ServerType serverType)
        {
            switch (clusterType)
            {
            case ClusterType.ReplicaSet:
                return(serverType.IsReplicaSetMember());

            case ClusterType.Sharded:
                return(serverType == ServerType.ShardRouter);

            case ClusterType.Standalone:
                return(serverType == ServerType.Standalone);

            case ClusterType.Unknown:
                switch (connectionMode)
                {
                case ClusterConnectionMode.Automatic:
                case ClusterConnectionMode.Direct:
                    return(true);

                default:
                    throw new MongoInternalException("Unexpected connection mode.");
                }

            default:
                throw new MongoInternalException("Unexpected cluster type.");
            }
        }
예제 #9
0
 /// <summary>
 /// Send webrequest for given URL and protocol
 /// </summary>
 /// <param name="url">URL</param>
 /// <param name="protocol">Protocol</param>
 /// <param name="clusterType"></param>
 /// <returns>Returns success status of web request <true>return true if success</true></returns>
 private bool SendWebRequest(string url, string protocol, ClusterType clusterType)
 {
     try
     {
         WebRequest request = WebRequest.Create(url);
         if (clusterType.Equals(ClusterType.Secure))
         {
             request.Credentials = new NetworkCredential(userName, password);
         }
         else if (clusterType.Equals(ClusterType.Azure))
         {
             request.Headers.Add("Username", userName);
             request.Headers.Add("Password", password);
         }
         request.Method = protocol;
         using (var response = request.GetResponse())
         {
             response.Close();
         }
         return(true);
     }
     catch (Exception e)
     {
         Console.Error.WriteLine("/**SendWebRequest(string url, string protocol)**/" + e.Message + "\n" + e.StackTrace);
         return(false);
     }
 }
 public MB3_MeshBakerGrouperCore CreateGrouper(ClusterType t, GrouperData data)
 {
     if (t == ClusterType.grid)
     {
         grouper = new MB3_MeshBakerGrouperGrid(data);
     }
     if (t == ClusterType.pie)
     {
         grouper = new MB3_MeshBakerGrouperPie(data);
     }
     if (t == ClusterType.agglomerative)
     {
         MB3_TextureBaker  tb = GetComponent <MB3_TextureBaker>();
         List <GameObject> gos;
         if (tb != null)
         {
             gos = tb.GetObjectsToCombine();
         }
         else
         {
             gos = new List <GameObject>();
         }
         grouper = new MB3_MeshBakerGrouperCluster(data, gos);
     }
     if (t == ClusterType.none)
     {
         grouper = new MB3_MeshBakerGrouperNone(data);
     }
     return(grouper);
 }
 public CompositeUniqueConstraint(IDialect dialect, string key1, string key2, ClusterType clusterType)
 {
     _dialect     = dialect;
     _key1        = key1;
     _key2        = key2;
     _clusterType = clusterType;
 }
예제 #12
0
        public override Request Request(Request request)
        {
            base.Request(request);

            if (OClient.ProtocolVersion < 24)
            {
                request.AddDataItem(ClusterType.ToString().ToUpper());
            }

            request.AddDataItem(ClusterName);

            if (OClient.ProtocolVersion < 24)
            {
                if (OClient.ProtocolVersion >= 10 || ClusterType == OClusterType.Physical)
                {
                    request.AddDataItem("");
                }

                if (OClient.ProtocolVersion >= 10)
                {
                    request.AddDataItem("default");
                }
                else
                {
                    request.AddDataItem((short)-1);
                }
            }
            if (OClient.ProtocolVersion >= 18)
            {
                request.AddDataItem((short)-1); //clusterid
            }
            return(request);
        }
예제 #13
0
        public static WoWUnit GetBestUnitForCluster(IEnumerable <WoWUnit> units, ClusterType type, float clusterRange)
        {
            if (!units.Any())
            {
                return(null);
            }

            switch (type)
            {
            case ClusterType.Radius:
                return((from u in units
                        select new { Count = GetRadiusClusterCount(u, units, clusterRange), Unit = u }).OrderByDescending(a => a.Count).
                       FirstOrDefault().Unit);

            case ClusterType.Chained:
                return((from u in units
                        select new { Count = GetChainedClusterCount(u, units, clusterRange), Unit = u }).OrderByDescending(a => a.Count).
                       FirstOrDefault().Unit);

            case ClusterType.Path:
                return((from u in units
                        select new { Count = GetPathClusterCount(u, units, clusterRange), Unit = u }).OrderByDescending(a => a.Count).
                       FirstOrDefault().Unit);

            // coned doesn't have a best unit, since we are the source
            default:
                throw new ArgumentOutOfRangeException("type");
            }
        }
예제 #14
0
        public override Request Request(Request request)
        {
            request.AddDataItem((byte)OperationType.DATACLUSTER_ADD);
            request.AddDataItem(request.SessionId);


            if (OClient.ProtocolVersion < 24)
            {
                request.AddDataItem(ClusterType.ToString().ToUpper());
            }

            request.AddDataItem(ClusterName);

            if (OClient.ProtocolVersion < 24)
            {
                if (OClient.ProtocolVersion >= 10 || ClusterType == OClusterType.Physical)
                {
                    request.AddDataItem("");
                }

                if (OClient.ProtocolVersion >= 10)
                {
                    request.AddDataItem("default");
                }
                else
                {
                    request.AddDataItem((short)-1);
                }
            }
            if (OClient.ProtocolVersion >= 18)
            {
                request.AddDataItem((short)-1); //clusterid
            }
            return(request);
        }
예제 #15
0
 private ZclClusterType(int clusterId, ProfileType profileType, string label, ClusterType clusterType)
 {
     this.ClusterId   = clusterId;
     this.ProfileType = profileType;
     this.Label       = label;
     this.Type        = clusterType;
 }
        public static ClusterDetails CreateClusterIfNotExists(ClusterType clusterType)
        {
            var name = AppConfig.AzureResourceName + clusterType.ToString().ToLowerInvariant();

            LOG.Info(String.Format("Creating Cluster: Name = {0}, Type = {1}", name, clusterType));

            var parameters = new ClusterCreateParametersV2()
            {
                Name = name,
                ClusterSizeInNodes        = HDInsightClusterSize,
                Location                  = AppConfig.AzureResourceLocation,
                ClusterType               = clusterType,
                HeadNodeSize              = "Large",
                DataNodeSize              = "Large",
                ZookeeperNodeSize         = "Medium",
                UserName                  = AppConfig.AzureResourceUsername,
                Password                  = AppConfig.AzureResourcePassword,
                DefaultStorageAccountName = AzureStorageHelper.Name,
                DefaultStorageAccountKey  = AzureStorageHelper.PrimaryKey,
                DefaultStorageContainer   = AppConfig.AzureResourceName,
                Version = "3.2",
                //VirtualNetworkId = VirtualNetworkHelper.VNetId,
                //SubnetName = VirtualNetworkHelper.SubnetName,
            };

            return(CreateClusterIfNotExists(parameters));
        }
예제 #17
0
        // private methods
        private ClusterDescription CreateClusterDescription(ClusterType type)
        {
            var clusterId = new ClusterId(1);
            var servers   = new ServerDescription[0];

            return(new ClusterDescription(clusterId, ClusterConnectionMode.Automatic, type, servers));
        }
예제 #18
0
        /// <summary>
        ///  Renames Selected file/folder(s)
        /// </summary>
        /// <param name="host"></param>
        /// <param name="clusterType"></param>
        /// <param name="sourceName">Current file name</param>
        /// <param name="targetName">New name for the file</param>
        /// <returns>If Rename succeeds returns true else returns false</returns>
        public bool MoveFile(string host, ClusterType clusterType, string sourceName, string targetName)
        {
            string commonHome = Directory.GetParent("..\\..\\..\\..\\..\\..\\..\\..\\").ToString();

            UploadFile(host, clusterType, commonHome + "\\BigDataSDK\\Samples\\Data\\WarPeace.txt", targetName);
            DeleteFile(host, clusterType, "/Data/PracticeTemp.txt");
            return(true);
        }
예제 #19
0
 public ClusterInfo(string name, ClusterType type, string location, string resourceGroup)
 {
     this.Name          = name;
     this.Type          = type.ToString();
     this.RpName        = type == ClusterType.connectedClusters ? ArcClusterRP : AksClusterRP;
     this.Location      = location;
     this.ResourceGroup = resourceGroup;
 }
예제 #20
0
 public Cluster(ClusterType type, int x, int y)
 {
     Type = type;
       tiles = new Tile[Constants.ClusterWidth * Constants.ClusterHeight];
       Active = false;
       Coordinates = new Coordinates(x, y);
       HashCode = GetHashCode();
 }
예제 #21
0
 public CompositeKeyConstraint(IDialect dialect, string tableName, string key1, string key2, ClusterType clusterType)
 {
     _dialect     = dialect;
     _key1        = key1;
     _key2        = key2;
     _clusterType = clusterType;
     _tables      = tableName.Split(Convert.ToChar("_"));
 }
예제 #22
0
 public ClusterModifyInfoPacket(QQUser user)
     : base(user)
 {
     SubCommand = ClusterCommand.MODIFY_CLUSTER_INFO;
     AuthType   = AuthType.Need;
     Name       = Notice = Description = string.Empty;
     Type       = ClusterType.PERMANENT;
 }
예제 #23
0
 public ClusterDescription(
     ClusterId clusterId,
     ClusterConnectionMode connectionMode,
     ClusterType type,
     IEnumerable <ServerDescription> servers)
     : this(clusterId, connectionMode, dnsMonitorException : null, type, servers)
 {
 }
예제 #24
0
        // Public
        #region Constructors

        public ObjectArrayCluster(int address, int clusterSizeBytes, Guid volumeID, ClusterType clusterType,
                                  int elementLength, Action <BinaryWriter, T> saveDelegate, Func <BinaryReader, T> loadDelegate, Action <BinaryWriter> zeroDelegate)
            : base(address, clusterSizeBytes, volumeID, clusterType, elementLength + sizeof(bool))
        {
            _saveDelegate  = saveDelegate;
            _loadDelegate  = loadDelegate;
            _zeroDelegate  = zeroDelegate;
            _elementLength = elementLength;
        }
예제 #25
0
        //public Type ClusterClass
        //{
        //    get; private set;
        //}

        private ZclClusterType(int clusterId, ProfileType profileType, string label, ClusterType clusterType, Func <ZigBeeEndpoint, ZclCluster> clusterFactory)
        {
            this.ClusterId      = clusterId;
            this.ProfileType    = profileType;
            this.Label          = label;
            this.Type           = clusterType;
            this.ClusterFactory = clusterFactory;
            //this.ClusterClass = clusterClass;
        }
예제 #26
0
        // Public
        #region Constructors

        /// <summary>
        /// Create a data cluster.
        /// </summary>
        /// <param name="address"></param>
        /// <param name="clusterSizeBytes"></param>
        /// <param name="volumeID"></param>
        /// <param name="clusterType"></param>
        public DataCluster(int address, int clusterSizeBytes, Guid volumeID, ClusterType clusterType)
            : base(clusterSizeBytes, volumeID, clusterType)
        {
            if (address == Constants.NoAddress)
            {
                throw new ArgumentException();
            }
            _address = address;
        }
예제 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClusterDescription" /> class.
 /// </summary>
 /// <param name="clusterId">The cluster identifier.</param>
 /// <param name="directConnection">Whether to make a direct connection.</param>
 /// <param name="dnsMonitorException">The last DNS monitor exception (null if there was none).</param>
 /// <param name="type">The type.</param>
 /// <param name="servers">The servers.</param>
 public ClusterDescription(
     ClusterId clusterId,
     bool?directConnection,
     Exception dnsMonitorException,
     ClusterType type,
     IEnumerable <ServerDescription> servers)
     : this(clusterId, connectionMode : default, ConnectionModeSwitch.UseDirectConnection, directConnection, dnsMonitorException, type, servers)
 {
 }
예제 #28
0
 // constructors
 /// <summary>
 /// Initializes a new instance of the <see cref="ClusterDescription"/> class.
 /// </summary>
 /// <param name="clusterId">The cluster identifier.</param>
 /// <param name="type">The type.</param>
 /// <param name="servers">The servers.</param>
 public ClusterDescription(
     ClusterId clusterId,
     ClusterType type,
     IEnumerable <ServerDescription> servers)
 {
     _clusterId = Ensure.IsNotNull(clusterId, "clusterId");
     _type      = type;
     _servers   = (servers ?? new ServerDescription[0]).OrderBy(n => n.EndPoint, new ToStringComparer <EndPoint>()).ToList();
 }
예제 #29
0
        // Protected
        #region Constructors

        protected ArrayCluster(int address, int clusterSize, Guid volumeID, ClusterType clusterType) :
            base(address, clusterSize, volumeID, clusterType)
        {
            if (address == Constants.NoAddress)
            {
                throw new ArgumentOutOfRangeException();
            }
            _nextClusterAddress = Constants.NoAddress;
        }
        public void Description_should_return_correct_description_when_not_initialized(ClusterConnectionMode connectionMode, ClusterType clusterType)
        {
            var subject = CreateSubject(connectionMode);
            var description = subject.Description;

            description.Servers.Should().BeEmpty();
            description.State.Should().Be(ClusterState.Disconnected);
            description.Type.Should().Be(clusterType);
        }
 public RequireServer ClusterType(ClusterType clusterType)
 {
     var actualClusterType = CoreTestConfiguration.Cluster.Description.Type;
     if (actualClusterType == clusterType)
     {
         return this;
     }
     throw new SkipTestException($"Test skipped because cluster type is {actualClusterType} and not {clusterType}.");
 }
예제 #32
0
파일: Cluster.cs 프로젝트: svermeulen/iris
        internal Cluster(SyntaxContext context)
        {
            ArgumentValidator.ThrowIfNull(context, "scope");

            this.m_containedGroupsAndClusters = new List<string>();
            this.m_syntaxContext = context;
            this.m_ClusterType = ClusterType.NONMAGIC;
            this.m_directItems = new SetOfSyntaxItems();
            this.m_syntaxDefinition = context.SyntaxDefinition;
        }
예제 #33
0
        internal Cluster(SyntaxContext context)
        {
            ArgumentValidator.ThrowIfNull(context, "scope");

            this.m_containedGroupsAndClusters = new List <string>();
            this.m_syntaxContext    = context;
            this.m_ClusterType      = ClusterType.NONMAGIC;
            this.m_directItems      = new SetOfSyntaxItems();
            this.m_syntaxDefinition = context.SyntaxDefinition;
        }
예제 #34
0
 // private methods
 private ClusterDescription CreateClusterDescription(
     ClusterId clusterId = null,
     ClusterConnectionMode connectionMode = ClusterConnectionMode.Automatic,
     ClusterType type = ClusterType.Unknown,
     IEnumerable <ServerDescription> servers = null)
 {
     clusterId = clusterId ?? new ClusterId(1);
     servers   = servers ?? new ServerDescription[0];
     return(new ClusterDescription(clusterId, connectionMode, type, servers));
 }
예제 #35
0
 public List<Bucket> Run(ClusterType clustertype, List<LatLong> points)
 {
     switch (clustertype)
     {
         case ClusterType.KMeans:
             return new KMeans(points).GetCluster();
         case ClusterType.MarkerClusterer:
             return new MarkerClusterer(points).GetCluster();
         case ClusterType.DistanceClusterer:
             return new DistanceClusterer(points).GetCluster();
     }
     return null;
 }
예제 #36
0
 public static IEnumerable<WoWUnit> GetCluster(WoWUnit target, IEnumerable<WoWUnit> otherUnits, ClusterType type, float clusterRange)
 {
     switch (type)
     {
         case ClusterType.Radius:
             return GetRadiusCluster(target, otherUnits, clusterRange);
         case ClusterType.Chained:
             return GetChainedCluster(target, otherUnits, clusterRange);
         case ClusterType.Cone:
             return GetConeCluster(target, otherUnits, clusterRange);
         case ClusterType.Path:
             return GetPathCluster(target, otherUnits, clusterRange);
         default:
             throw new ArgumentOutOfRangeException("type");
     }
 }
예제 #37
0
파일: Clusters.cs 프로젝트: ipo/AGBA
        public static int GetClusterCount(DiaUnit target, IEnumerable<DiaObject> otherUnits, ClusterType type, float clusterRange)
        {
            if (otherUnits.Count() == 0)
                return 0;

            switch (type)
            {
                case ClusterType.Radius:
                    return GetRadiusClusterCount(target, otherUnits, clusterRange);
                case ClusterType.Chained:
                    return GetChainedClusterCount(target, otherUnits, clusterRange);
                //case ClusterType.Cone:
                //    return GetConeClusterCount(target, otherUnits, clusterRange);
                default:
                    throw new ArgumentOutOfRangeException("type");
            }
        }
예제 #38
0
파일: Clusters.cs 프로젝트: ipo/AGBA
        public static DiaObject GetBestUnitForCluster(IEnumerable<DiaObject> units, ClusterType type, float clusterRange)
        {
            if (units.Count() == 0)
                return null;

            switch (type)
            {
                case ClusterType.Radius:
                    return (from u in units
                            select new { Count = GetRadiusClusterCount(u, units, clusterRange), Unit = u }).OrderByDescending(a => a.Count).
                        FirstOrDefault().Unit;
                case ClusterType.Chained:
                    return (from u in units
                            select new { Count = GetChainedClusterCount(u, units, clusterRange), Unit = u }).OrderByDescending(a => a.Count).
                        FirstOrDefault().Unit;
                // coned doesn't have a best unit, since we are the source
                default:
                    throw new ArgumentOutOfRangeException("type");
            }
        }
예제 #39
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determines the cluster type based upon how many items it has in rev and curr.
		/// If it does not have any items in rev and curr (ie-it's been constructed but not
		/// yet filled out) no type will be set, or Debug.Assert will fail.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		internal void DetermineType()
		{
			// determine the cluster type
			if (this.itemsRev.Count == 1 && this.itemsCurr.Count == 1)
				this.clusterType = ClusterType.MatchedItems;
			else if (this.itemsRev.Count == 0 && this.itemsCurr.Count == 1)
				this.clusterType = ClusterType.AddedToCurrent;
			else if (this.itemsRev.Count == 1 && this.itemsCurr.Count == 0)
				this.clusterType = ClusterType.MissingInCurrent;
			else if (this.itemsRev.Count == 0 && this.itemsCurr.Count > 1)
				this.clusterType = ClusterType.AddedToCurrent;
			else if (this.itemsRev.Count > 1 && this.itemsCurr.Count == 0)
				this.clusterType = ClusterType.MissingInCurrent;
			else if (this.itemsRev.Count == 1 && this.itemsCurr.Count > 1)
				this.clusterType = ClusterType.SplitInCurrent;
			else if (this.itemsRev.Count > 1 && this.itemsCurr.Count == 1)
				this.clusterType = ClusterType.MergedInCurrent;
			else if (this.itemsRev.Count > 1 && this.itemsCurr.Count > 1)
				this.clusterType = ClusterType.MultipleInBoth;
			else Debug.Assert(false, "problem determinining cluster type");
		}
예제 #40
0
        public static int GetClusterCount(WoWUnit target, IEnumerable<WoWUnit> otherUnits, ClusterType type, float clusterRange)
        {
            if (target == null)
                return 0;

            if (otherUnits == null || !otherUnits.Any())
                return 0;

            switch (type)
            {
                case ClusterType.Radius:
                    return GetRadiusClusterCount(target, otherUnits, clusterRange);
                case ClusterType.Chained:
                    return GetChainedClusterCount(target, otherUnits, clusterRange);
                case ClusterType.Cone:
                    return GetConeClusterCount(target, otherUnits, clusterRange);
                case ClusterType.Path:
                    return GetPathClusterCount(target, otherUnits, clusterRange);
                default:
                    throw new ArgumentOutOfRangeException("type");
            }
        }
예제 #41
0
 /// <summary>创建一个临时群
 /// Creates the temporary cluster.
 /// </summary>
 /// <param name="name">The name.群名称</param>
 /// <param name="type">The type.临时群类型</param>
 /// <param name="parentClusterId">The parent cluster id.父群内部ID</param>
 /// <param name="members">The members.成员QQ号数组</param>
 public void CreateTemporaryCluster(string name, ClusterType type, int parentClusterId, List<int> members)
 {
     ClusterCreateTempPacket packet = new ClusterCreateTempPacket(QQClient);
     packet.Type = type;
     packet.Name = name;
     packet.Members = members;
     packet.ParentClusterId = parentClusterId;
     QQClient.PacketManager.SendPacket(packet, QQPort.Main.Name);
 }
예제 #42
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// A helper method for section cluster tests-
		/// Verifies the contents of the given Cluster. This overload lets the caller ignore
		/// the indexToInsertAtInOther, which is only needed for Missing/Added clusters.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void VerifySectionCluster(Cluster cluster, int refMin, int refMax, ClusterType type,
			object expectedItemsCurr, object expectedItemsRev)
		{
			Assert.IsTrue(cluster.clusterType != ClusterType.MissingInCurrent &&
				cluster.clusterType != ClusterType.AddedToCurrent,
				"Missing/Added clusters must be verified by passing in the indexToInsertAtInOther parameter.");

			// verify the details
			VerifySectionCluster(cluster, refMin, refMax, type, expectedItemsCurr, expectedItemsRev, -1);
		}
예제 #43
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// A helper method for section cluster tests-
		/// Verifies the contents of the given Cluster.
		/// </summary>
		/// <param name="cluster">The given cluster.</param>
		/// <param name="refMin">The expected verse ref min.</param>
		/// <param name="refMax">The expected verse ref max.</param>
		/// <param name="type">The the expected cluster type.</param>
		/// <param name="expectedItemsCurr">The expected items for the Current
		/// (see VerifyClusterItems() for details).</param>
		/// <param name="expectedItemsRev">The expected items for the Revision
		/// (see VerifyClusterItems() for details)</param>
		/// <param name="indexToInsertAtInOther">The expected index</param>
		/// ------------------------------------------------------------------------------------
		private void VerifySectionCluster(Cluster cluster, int refMin, int refMax, ClusterType type,
			object expectedItemsCurr, object expectedItemsRev, int indexToInsertAtInOther)
		{
			//here we check the calling test code:
			// expected items should be consistent with the expected cluster type
			switch (type)
			{
				case ClusterType.MatchedItems:
					Assert.IsTrue(expectedItemsCurr is IScrSection || expectedItemsCurr is IScrTxtPara);
					Assert.IsTrue(expectedItemsRev is IScrSection || expectedItemsRev is IScrTxtPara);
					break;
				case ClusterType.MissingInCurrent:
					Assert.IsNull(expectedItemsCurr);
					Assert.IsTrue(expectedItemsRev is IScrSection || expectedItemsRev is IScrTxtPara);
					break;
				case ClusterType.AddedToCurrent:
					Assert.IsTrue(expectedItemsCurr is IScrSection || expectedItemsCurr is IScrTxtPara);
					Assert.IsNull(expectedItemsRev);
					break;
				case ClusterType.MultipleInBoth:
					Assert.IsTrue(expectedItemsCurr is List<IScrSection>);
					Assert.IsTrue(expectedItemsRev is List<IScrSection>);
					break;
				case ClusterType.SplitInCurrent:
					Assert.IsTrue(expectedItemsCurr is List<IScrSection>);
					Assert.IsTrue(expectedItemsRev is List<IScrSection>);
					break;
				case ClusterType.MergedInCurrent:
					Assert.IsTrue(expectedItemsCurr is List<IScrSection>);
					Assert.IsTrue(expectedItemsRev is List<IScrSection>);
					break;
				default:
					Assert.Fail("invalid type expected");
					break;
			}

			VerifyCluster(cluster, refMin, refMax, type, expectedItemsCurr, expectedItemsRev,
				indexToInsertAtInOther, ClusterKind.ScrSection);
		}
예제 #44
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Verifies expected characteristics of any kind of cluster.
		/// </summary>
		/// <param name="cluster">The cluster.</param>
		/// <param name="refMin">The reference min.</param>
		/// <param name="refMax">The reference max.</param>
		/// <param name="type">The cluster type.</param>
		/// <param name="expectedItemsCurr">The expected items in the Current.</param>
		/// <param name="expectedItemsRev">The expected items in the Revision.</param>
		/// <param name="indexToInsertAtInOther">The index to insert at in other.</param>
		/// <param name="kindOfCluster">The kind of cluster.</param>
		/// ------------------------------------------------------------------------------------
		private void VerifyCluster(Cluster cluster, int refMin, int refMax, ClusterType type,
			object expectedItemsCurr, object expectedItemsRev, int indexToInsertAtInOther,
			ClusterKind kindOfCluster)
		{
			// verify the basics
			Assert.AreEqual(refMin, cluster.verseRefMin);
			Assert.AreEqual(refMax, cluster.verseRefMax);
			Assert.AreEqual(type, cluster.clusterType);

			// verify the indexToInsertAtInOther
			Assert.AreEqual(indexToInsertAtInOther, cluster.indexToInsertAtInOther);

			// now verify the cluster's items
			switch (kindOfCluster)
			{
				case ClusterKind.ScrSection:
					VerifySectionClusterItems(expectedItemsCurr, cluster.itemsCurr, kindOfCluster);
					VerifySectionClusterItems(expectedItemsRev, cluster.itemsRev, kindOfCluster);
					break;
				case ClusterKind.ScrVerse:
					VerifyScrVerseClusterItems(expectedItemsCurr, cluster.itemsCurr, kindOfCluster);
					VerifyScrVerseClusterItems(expectedItemsRev, cluster.itemsRev, kindOfCluster);
					break;
			}
		}
예제 #45
0
        public void GenerateJavascriptDrawFile(ClusterType clusterType)
        {
            var sb = new StringBuilder();

                // markers
                var head = "function drawMarkers(ctx) {" + NL;
                var tail = NL + "}" + NL;

                sb.Append(head);

                // grid
                if (DisplayGridInCanvas)
                {
                    sb.Append("ctx.beginPath();" + NL);
                    for (int i = 0; i < GridX + 1; i++)
                    {
                        sb.Append(String.Format("ctx.moveTo({0}, {1});{2}",
                                                ToStringEN(MinX + i * DeltaX),
                                                ToStringEN(MinY), NL));
                        sb.Append(String.Format("ctx.lineTo({0}, {1});{2}",
                                                ToStringEN(MinX + i * DeltaX),
                                                ToStringEN(MaxY), NL));
                    }
                    for (int j = 0; j < GridY + 1; j++)
                    {
                        sb.Append(String.Format("ctx.moveTo({0}, {1});{2}",
                                                ToStringEN(MinX),
                                                ToStringEN(MinY + j * DeltaY), NL));
                        sb.Append(String.Format("ctx.lineTo({0}, {1});{2}",
                                                ToStringEN(MaxX),
                                                ToStringEN(MinY + j * DeltaY), NL));
                    }
                    sb.Append("ctx.stroke(); " + NL);
                }

                // if to many points, the canvas can not be drawn or is slow,
                // use max points and clusters for drawing
                const int max = 10000;

                // markers
                if (_points != null)
                {
                    sb.Append(NL);
                    for (int i = 0; i < _points.Count; i++)
                    {
                        var p = _points[i];
                        sb.Append(string.Format("drawMark({0}, {1}, {2}, {3});{4}",
                                  ToStringEN(p.X), ToStringEN(p.Y), p.Color, ctx, NL));
                        if (i > max)
                            break;
                    }
                }
                string clusterInfo = "0";
                if (_clusters != null)
                {
                    sb.Append(NL);

                    if (clusterType == ClusterType.Grid || clusterType == ClusterType.KMeans)
                    {
                        for (int i = 0; i < _clusters.Count; i++)
                        {
                            var c = _clusters[i];
                            sb.Append(string.Format("drawCluster({0}, {1}, {2}, {3}, {4});{5}",
                                                    ToStringEN(c.X), ToStringEN(c.Y), c.Color,
                                                    c.Size, ctx, NL));

                            if (i > max)
                                break;
                        }
                    }

                    else if (clusterType == ClusterType.MarkerClusterer)
                    {
                        for (int i = 0; i < _clusters.Count; i++)
                        {
                            var c = _clusters[i];
                            sb.Append(string.Format(
                                "drawMarkerCluster({0}, {1}, {2}, {3}, {4}, {5});{6}",
                                                    ToStringEN(c.X), ToStringEN(c.Y), c.Color,
                                                    c.Size, MARKERCLUSTERER_SIZE, ctx, NL));

                            if (i > max)
                                break;
                        }
                    }
                    else if (clusterType == ClusterType.DistanceClusterer)
                    {
                        for (int i = 0; i < _clusters.Count; i++)
                        {
                            var c = _clusters[i];
                            sb.Append(string.Format(
                                "drawDistanceCluster({0}, {1}, {2}, {3}, {4}, {5});{6}",
                                                    ToStringEN(c.X), ToStringEN(c.Y), c.Color,
                                                    c.Size, DISTANCECLUSTERER_SIZE, ctx, NL));

                            if (i > max)
                                break;
                        }
                    }

                    clusterInfo = _clusters.Count + string.Empty;
                }

                // bottom text
                sb.Append("ctx.fillStyle = 'rgb(0,0,0)';" + NL);
                sb.Append(string.Format("ctx.fillText('Clusters = ' + {0}, {1}, {2});{3}",
                    clusterInfo, ToStringEN(MinX + 10), ToStringEN(MaxY + 20), NL));

                sb.Append(tail);
                CreateFile(sb.ToString());
                //Console.WriteLine(sb.ToString());
        }
예제 #46
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Determine if the Current is the source.
		/// </summary>
		/// <param name="clusterType">Type of the cluster--should be a missing or added.</param>
		/// <returns><c>true</c> if the cluster item(s) was/were added to current;
		/// <c>false</c> if the cluster item(s) was/were missing in current</returns>
		/// <exception cref="InvalidOperationException">thrown if clusterType is not added to current
		/// or missing in current.</exception>
		/// ------------------------------------------------------------------------------------
		public static bool CurrentIsSource(ClusterType clusterType)
		{
			if (clusterType == ClusterType.AddedToCurrent || clusterType == ClusterType.OrphansInCurrent)
				return true;

			if (clusterType == ClusterType.MissingInCurrent || clusterType == ClusterType.OrphansInRevision)
				return false;

			throw new InvalidOperationException(string.Format(
				"Cluster type {0} incompatible. Cluster type must be added to or missing in current.",
				clusterType.ToString()));
		}
        public static ClusterDetails CreateClusterIfNotExists(ClusterType clusterType)
        {
            var name = AppConfig.AzureResourceName + clusterType.ToString().ToLowerInvariant();
            LOG.Info(String.Format("Creating Cluster: Name = {0}, Type = {1}", name, clusterType));

            var parameters = new ClusterCreateParametersV2()
            {
                Name = name,
                ClusterSizeInNodes = HDInsightClusterSize,
                Location = AppConfig.AzureResourceLocation,
                ClusterType = clusterType,
                HeadNodeSize = "Large",
                DataNodeSize = "Large",
                ZookeeperNodeSize = "Medium",
                UserName = AppConfig.AzureResourceUsername,
                Password = AppConfig.AzureResourcePassword,
                DefaultStorageAccountName = AzureStorageHelper.Name,
                DefaultStorageAccountKey = AzureStorageHelper.PrimaryKey,
                DefaultStorageContainer = AppConfig.AzureResourceName,
                Version = "3.2",
                //VirtualNetworkId = VirtualNetworkHelper.VNetId,
                //SubnetName = VirtualNetworkHelper.SubnetName,
            };
            return CreateClusterIfNotExists(parameters);
        }
예제 #48
0
        public void clustering(ClusterType type, string fname)
        {
            #region lam clustering
            switch (type)
            {
                #region case "DBScan": Code by Minh & V?ng
                case ClusterType.DBSCAN:
                    // Save();
                    mClusterListener.onSave();

                    ez_load_xml(fname);

                    mClusterListener.onUpdateProgressbar(0);

                    DBScanForm dbscanForm = new DBScanForm();
                    dbscanForm.ShowDialog();

                    if ((dbscanForm.EpsBox.Text == "") || (dbscanForm.PtsBox.Text == ""))
                    {
                        break;
                    }

                    minPts = Int32.Parse(dbscanForm.PtsBox.Text);
                    eps = Double.Parse(dbscanForm.EpsBox.Text);
                    if (newLinks != null && newSensors != null)
                    {
                        newLinks.Clear();
                        newSensors.Clear();
                        listBeforeClusters.Clear();
                        listAfterClusters.Clear();
                        listPathDirectoryOpen.Clear();
                        int[] LinkFrom = new int[listLink.Count];//M?ng 1 chi?u luu các link vào
                        int[] LinkTo = new int[listLink.Count];//M?ng 1 chi?u luu các link ra
                        double[][] sensor = new double[listSensor.Count][];//M?ng 2 chi?u luu ID và t?a d? X Y và stype c?a các sensor
                        int[] LinkFromgiunguyen = new int[LinkFrom.Length];
                        int[] LinkTogiunguyen = new int[LinkTo.Length];
                        //SplashScreen.ShowSplashScreen();
                        //SplashScreen.SetStatus("Please wait ... ");
                        //Clustering.dbscanClustering(listSensor, listLink, ref newSensors, ref newLinks, minPts, eps);
                        //Console.WriteLine("\n================================");
                        List<List<Sensor>> clusters = DBSCAN.GetClusters(listSensor, eps, minPts);
                        //Console.WriteLine("\nXu?t t?ng c?m");
                        Console.WriteLine("\n===================================");
                        int countcluster = 0;//d?m xem trong list clusters có bn cluster
                        for (int i = 0; i < clusters.Count; i++)
                        {
                            countcluster++;
                        }
                        Console.WriteLine("\n===================================");
                        //T?o b?ng LinkFrom và LinkTo
                        int demLink = 0;
                        for (int i = 0; i < listLink.Count; i++)
                        {
                            LinkTo[i] = listLink[i].getDest().getId();
                            LinkFrom[i] = listLink[i].getSource().getId();
                            demLink++;
                            //Console.WriteLine("Link: from sensor {0} to sensor {1}\n", listLink[i].getSource().getId(), listLink[i].getDest().getId());
                        }
                        //B?ng các Sensor
                        for (int i = 0; i < listSensor.Count; i++)
                        {
                            sensor[i] = new double[8];
                            sensor[i][0] = listSensor[i].getId();//C?t 1 ID sensor
                            sensor[i][1] = listSensor[i].getX();//C?t 2 t?a d? X
                            sensor[i][2] = listSensor[i].getY();//C?t 3 t?a d? Y
                            sensor[i][3] = listSensor[i].getstype();//C?t 4 ch?a ki?u sensor (0 là source, 1 là sink, 2 là trung gian)
                            sensor[i][4] = listSensor[i].getsending_rate();//ch?a sending rate c?a sensor
                            sensor[i][5] = listSensor[i].getprocessing_rate();//ch?a processing rate c?a sensor
                            sensor[i][6] = listSensor[i].getXLabel();//X of label
                            sensor[i][7] = listSensor[i].getYLabel();//Y of label
                        }
                        int[][] cluster = new int[countcluster][];//B?ng ch?a ID các sensor trong t?ng c?m
                        int[][] sensorgiunguyen = new int[countcluster][];//Ch?a các sensor du?c gi? nguyên trong t?ng c?m
                        int[] numsensorincluster = new int[countcluster];//Th?ng kê s? lu?ng sensor trong t?ng c?m
                        for (int i = 0; i < countcluster; i++)
                        {
                            for (int j = 0; j < clusters[i].Count; j++)
                            {
                                numsensorincluster[i] += 1;
                            }
                            //MessageBox.Show("Cluster thu"+(i + 1).ToString() + "có"+numsensorincluster[i].ToString()+"sensor","Message");
                        }
                        //B?ng ch?a ID các sensor trong t?ng c?m
                        Console.WriteLine("\n===================================");
                        for (int i = 0; i < countcluster; i++)
                        {
                            cluster[i] = new int[numsensorincluster[i]];
                            Console.WriteLine("\nCluster {0}:", i + 1);
                            for (int j = 0; j < clusters[i].Count; j++)
                            {
                                cluster[i][j] = clusters[i][j].getId();
                                Console.WriteLine(" {0} ", cluster[i][j]);
                            }

                        }

                        //B?ng ID sensor gi? nguyên c?a t?ng c?m
                        //Gi? nguyên sink source
                        for (int i = 0; i < cluster.Length; i++)
                        {
                            sensorgiunguyen[i] = new int[numsensorincluster[i]];
                            for (int j = 0; j < cluster[i].Length; j++)
                            {
                                for (int n = 0; n < sensor.Length; n++)
                                {
                                    if (cluster[i][j] == sensor[n][0])
                                    {
                                        if ((sensor[n][3] == 1) || (sensor[n][3] == 2))
                                        {
                                            sensorgiunguyen[i][j] = cluster[i][j];
                                            Console.WriteLine("\ni={0}, j={1}", i, j);
                                        }
                                    }
                                }
                            }
                        }
                        //Gi? nguyên sensor có link di ra ho?c di vào c?m
                        #region //Gi? nguyên sensor có link di ra ho?c di vào c?m
                        Boolean flag = false;//c? ki?m tra xem m?t sensor có n?m cùng c?m v?i sensor dang xét không
                        for (int i = 0; i < cluster.Length; i++)
                        {
                            for (int j = 0; j < cluster[i].Length; j++)
                            {
                                for (int k = 0; k < LinkFrom.Length; k++)
                                {
                                    if (LinkFrom[k] == cluster[i][j])//N?u nó có du?ng ra - n?m trong b?ng from
                                    {
                                        for (int n = 0; n < cluster[i].Length; n++)
                                        {
                                            if (LinkTo[k] == cluster[i][n])// và n?u nó n?i d?n sensor cùng c?m
                                            {
                                                flag = true;//b?t c? thành true
                                                break;
                                            }
                                            else flag = false;
                                        }
                                        if (flag == false)//n?u c? false, nghia là nó có link ra ngoài kh?i c?m dang xét
                                        {
                                            sensorgiunguyen[i][j] = LinkFrom[k];//gi? nó l?i thôi
                                            LinkFromgiunguyen[k] = LinkFrom[k];
                                            LinkTogiunguyen[k] = LinkTo[k];
                                        }

                                    }
                                    if (LinkTo[k] == cluster[i][j])//N?u nó có du?ng vào - n?m trong b?ng to
                                    {
                                        for (int n = 0; n < cluster[i].Length; n++)
                                        {
                                            if (LinkFrom[k] == cluster[i][n])// và n?u nó du?c n?i t? sensor cùng c?m
                                            {
                                                flag = true;//b?t c? thành true
                                                break;
                                            }
                                            else flag = false;

                                        }
                                        if (flag == false)//n?u c? false, nghia là nó có link t? sensor c?m khác link vào c?m dang xét
                                        {
                                            sensorgiunguyen[i][j] = LinkTo[k];//gi? l?i nó thôi
                                            LinkFromgiunguyen[k] = LinkFrom[k];
                                            LinkTogiunguyen[k] = LinkTo[k];
                                        }
                                    }
                                }
                            }
                        }
                        #endregion

                        // Create new cluster path
                        //CURRENT_PATH = ROOT_CLUSTER + "\\" + DateTime.Now.Millisecond.ToString();
                        //BCdirectoryPath = ResultdirectoryPath + @"\" + "Before_Cluster";
                        //ACdirectoryPath = ResultdirectoryPath + @"\" + "After_Cluster";
                        listPathDirectoryOpen.Add(CURRENT_PATH + AFTER_FOLDER);
                        listPathDirectoryOpen.Add(CURRENT_PATH + BEFORE_FOLDER);
                        //if (Directory.Exists(ROOT_CLUSTER + CURRENT_FOLDER))
                        //{
                        //    numDir++;
                        //    ResultdirectoryPath = ResultdirectoryPath + "_(" + numDir + ")";
                        //    Directory.CreateDirectory(ResultdirectoryPath);
                        //    Directory.CreateDirectory(BCdirectoryPath);
                        //    Directory.CreateDirectory(ACdirectoryPath);
                        //}
                        //else
                        {
                            Directory.CreateDirectory(CURRENT_PATH);
                            Directory.CreateDirectory(CURRENT_PATH + AFTER_FOLDER);
                            Directory.CreateDirectory(CURRENT_PATH + BEFORE_FOLDER);
                            Directory.CreateDirectory(CURRENT_PATH + PN_FOLDER);
                        }
                        //StatusLabel_Status.Text = "Clustering....";
                        //Log.d(TAG, ProgressBar1.Step.ToString());
                        //Xu?t XML t?ng c?m tru?c khi x? lý
                        for (int i = 0; i < cluster.Length; i++)
                        {
                            mClusterListener.onUpdateProgressbar((100 / countcluster) - 1);
                            // ProgressBar1.Value += (100 / countcluster) - 1;

                            DevLog.d(TAG, "Cluster " + (i + 1) + ":");
                            for (int j = 0; j < cluster[i].Length; j++)
                            {

                                //MessageBox.Show(""+cluster[i][j], "Message");
                                for (int n = 0; n < sensor.Length; n++)
                                {
                                    if (cluster[i][j] == sensor[n][0])
                                    {
                                        Sensor test = new Sensor(cluster[i][j], sensor[n][1], sensor[n][2], Convert.ToInt16(sensor[n][3]), Convert.ToInt16(sensor[n][4]), Convert.ToInt16(sensor[n][5]), sensor[n][6], sensor[n][7]);
                                        listSensorBefore.Add(test);
                                    }
                                    if (sensorgiunguyen[i][j] == sensor[n][0])
                                    {
                                        Sensor test = new Sensor(cluster[i][j], sensor[n][1], sensor[n][2], Convert.ToInt16(sensor[n][3]), Convert.ToInt16(sensor[n][4]), Convert.ToInt16(sensor[n][5]), sensor[n][6], sensor[n][7]);
                                        listSensorAfter.Add(test);
                                        if (checkSensorHave(test, listSensorAfterCluster) == false)
                                        {
                                            listSensorAfterCluster.Add(test);
                                        }
                                    }
                                }
                                for (int n = j + 1; n < cluster[i].Length; n++)
                                {
                                    for (int k = 0; k < LinkFrom.Length; k++)
                                    {
                                        if ((LinkFrom[k] == cluster[i][j]) && (LinkTo[k] == cluster[i][n]))
                                        {
                                            Sensor src = new Sensor(cluster[i][j]);
                                            Sensor dest = new Sensor(cluster[i][n]);
                                            Link testLink = new Link(src, dest, "Real", listLink[k].getTranfer_rate());
                                            listLinkBefore.Add(testLink);
                                        }
                                        if ((LinkFrom[k] == cluster[i][n]) && (LinkTo[k] == cluster[i][j]))
                                        {
                                            Sensor src = new Sensor(cluster[i][n]);
                                            Sensor dest = new Sensor(cluster[i][j]);
                                            Link testLink = new Link(src, dest, "Real", listLink[k].getTranfer_rate());
                                            //if(listLinkTest.Contains(testLink))
                                            listLinkBefore.Add(testLink);
                                        }
                                        if ((LinkFrom[k] == sensorgiunguyen[i][j]) && (LinkTo[k] == sensorgiunguyen[i][n]))
                                        {
                                            Sensor src = new Sensor(sensorgiunguyen[i][j]);
                                            Sensor dest = new Sensor(sensorgiunguyen[i][n]);
                                            Link testLink = new Link(src, dest, "Real", listLink[k].getTranfer_rate());
                                            listLinkAfter.Add(testLink);
                                            //listLinkAfterCluster.Add(testLink);
                                        }
                                        if ((LinkFrom[k] == sensorgiunguyen[i][n]) && (LinkTo[k] == sensorgiunguyen[i][j]))
                                        {
                                            Sensor src = new Sensor(sensorgiunguyen[i][n]);
                                            Sensor dest = new Sensor(sensorgiunguyen[i][j]);
                                            Link testLink = new Link(src, dest, "Real", listLink[k].getTranfer_rate());
                                            listLinkAfter.Add(testLink);
                                            //listLinkAfterCluster.Add(testLink);
                                        }
                                    }
                                }
                            }
                            #region //T?o link gi?
                            //T?o link gi?
                            //T?o list các sensor c?n t?o link gi?
                            List<Link> listVirtualLinkNeedCreate = new List<Link>();
                            bool flag1 = false;//c? d? ki?m tra link c?a m?i sensor d? chuy?n v? d? th? vô hu?ng

                            int[][] graphRouting = new int[listSensorBefore.Count][];
                            //Ðua v? d? th? qu?n lý b?ng m?ng 2 chi?u
                            for (int k = 0; k < listSensorBefore.Count; k++)
                            {
                                graphRouting[k] = new int[listSensorBefore.Count];
                                for (int m = 0; m < graphRouting[k].Length; m++)
                                {
                                    graphRouting[k][m] = 0;
                                }
                            }

                            for (int f = 0; f < listSensorBefore.Count; f++)
                            {
                                for (int t = 0; t < listSensorBefore.Count; t++)
                                {
                                    foreach (Link l in listLinkBefore)
                                    {
                                        if ((listSensorBefore[f].getId() == l.getSource().getId()) && (listSensorBefore[t].getId() == l.getDest().getId()))
                                        {
                                            //graphRouting[f][t] = TinhKhoangCach(listSensorBefore[f].getX(), listSensorBefore[f].getY(), listSensorBefore[t].getX(), listSensorBefore[t].getY());
                                            graphRouting[f][t] = 1;
                                            flag1 = true;
                                            break;
                                        }
                                    }
                                    if (flag1 == true)
                                        continue;
                                }
                            }
                            //DFS(graphRouting);//Duy?t d? th?

                            //Xét di?u ki?n d? t?o link gi?
                            bool flag4 = false;
                            for (int f = 0; f < listSensorAfter.Count; f++)
                            {
                                for (int t = 0; t < listSensorAfter.Count; t++)
                                {
                                    if (f == t)
                                    {
                                        continue;
                                    }
                                    foreach (Link l in listLinkAfter)
                                    {
                                        if ((listSensorAfter[f].getId() == l.getSource().getId()) && (listSensorAfter[t].getId() == l.getDest().getId()))
                                        {
                                            flag4 = true;
                                            break;
                                        }
                                        if ((listSensorAfter[t].getId() == l.getSource().getId()) && (listSensorAfter[f].getId() == l.getDest().getId()))
                                        {
                                            flag4 = true;
                                            break;
                                        }
                                    }
                                    if (flag4 == true)
                                    {
                                        flag4 = false;
                                        continue;
                                    }
                                    if (listSensorAfter[t].getstype() == 1)//1 là src - To đến src
                                    {
                                        continue;
                                    }
                                    if (listSensorAfter[f].getstype() == 2)//2 là sink - sink To ra
                                    {
                                        break;
                                    }
                                    Link virtuallink = new Link(listSensorAfter[f], listSensorAfter[t], "Virtual");
                                    listVirtualLinkNeedCreate.Add(virtuallink);
                                }
                            }
                            checkListVirtualLinkNeedCreate(listVirtualLinkNeedCreate);
                            //for (int test = 0; test < listVirtualLinkNeedCreate.Count; test++)
                            //{

                            //    //MessageBox.Show("Src: " + listVirtualLinkNeedCreate[test].getSource().getId() + " - dest: " + listVirtualLinkNeedCreate[test].getDest().getId(), "msg");
                            //}
                            //string[][] Pathfull = new string[listVirtualLinkNeedCreate.Count][];
                            for (int test = 0; test < listVirtualLinkNeedCreate.Count; test++)
                            {
                                DevLog.d(TAG, "Link need create: " + listVirtualLinkNeedCreate[test].getSource().getId() + " _ " + listVirtualLinkNeedCreate[test].getDest().getId());
                            }
                            int from = 0;
                            int to = 0;
                            bool flag2 = false;
                            bool flag3 = false;
                            //int countVirtualLink = 0;
                            //truy?n các c?p c?n t?o link gi? vào.
                            for (int g = 0; g < listVirtualLinkNeedCreate.Count; g++)
                            {
                                DevLog.d(TAG, "Src: " + listVirtualLinkNeedCreate[g].getSource().getId() + " - dest: " + listVirtualLinkNeedCreate[g].getDest().getId());
                                for (int index = 0; index < listSensorBefore.Count; index++)
                                {
                                    if (listVirtualLinkNeedCreate[g].getSource().getId() == listSensorBefore[index].getId())
                                    {
                                        flag2 = true;
                                        from = index;
                                    }
                                    else if (listVirtualLinkNeedCreate[g].getDest().getId() == listSensorBefore[index].getId())
                                    {
                                        flag3 = true;
                                        to = index;
                                    }
                                    if (flag2 && flag3)
                                    {
                                        break;
                                    }
                                }
                                if (flag2 && flag3)
                                {
                                    flag2 = false;
                                    flag3 = false;
                                    DevLog.d(TAG, "=======START========");
                                    //string temp11 = "";
                                    //for (int list = 0; list < listSensorAfter.Count; list++)
                                    //{

                                    //    temp11 += listSensorAfter[list].getId();
                                    //    temp11 += ", ";

                                    //}
                                    //MessageBox.Show("list Sensor gi? nguyên: " + temp11, "msg");
                                    path = "";
                                    PathID = "";
                                    Dem_path = 0;
                                    DevLog.d(TAG, "Checking...from_to: " + from + " _ " + to);
                                    //MessageBox.Show("Path from " + from + " to " + to, "msg");
                                    //PrintPath(from, to);//hàm in ra du?ng di
                                    //if (dijkstra(from, to, graphRouting) == true)//hàm ktra t? from d?n to có du?ng di không
                                    if (FindAllPath(from, to, graphRouting) == true)
                                    {
                                        //MessageBox.Show("Path: " + path, "msg");

                                        //In ra t?t c? du?ng di
                                        double newTransfer;
                                        int dem_path_valid = Dem_path;//s? du?ng di h?p l?
                                        double[] delayRate = new double[Dem_path];
                                        char[] c = new char[] { ';' };
                                        string[] s1 = path.Split(c, StringSplitOptions.RemoveEmptyEntries);
                                        //Chuy?n các du?ng di index thành du?ng di d?ng ID
                                        ConvertPathID(s1, listSensorBefore);
                                        //MessageBox.Show("Path ID: " + PathID, "msg");
                                        //xét t?ng du?ng di có th?a di?u ki?n t?o link gi? không
                                        //string[] s2 = PathID.Split(c, StringSplitOptions.RemoveEmptyEntries);
                                        //for (int k = 0; k < s2.Length; k++)
                                        //{
                                        //    string temp = "";
                                        //    temp += s2[k];
                                        //    char[] d = new char[] { '-' };
                                        //    string[] temp_path = temp.Split(d, StringSplitOptions.RemoveEmptyEntries);
                                        //for (int z = 1; z < temp_path.Length - 1; z++)//ph?n t? d?u và cu?i luôn là 2 sensor du?c gi? l?i sau khi cluster
                                        //{
                                        //    for (int p = 0; p < listSensorAfter.Count; p++)
                                        //    {
                                        //        if (temp_path[z] == listSensorAfter[p].getId().ToString())
                                        //        {
                                        //            dem_path_valid--;//có b?t k? sensor nào du?c gi? l?i thì du?ng di dó b? b?
                                        //            //MessageBox.Show("Path not valid: " + temp, "Msg");
                                        //            //MessageBox.Show("path valid to break: " + dem_path_valid, "Msg");
                                        //            break;
                                        //        }
                                        //    }
                                        //    break;
                                        //}
                                        //}
                                        //if (dem_path_valid != 0)
                                        //{
                                        //MessageBox.Show("path valid: " + dem_path_valid, "Msg");
                                        graphRouting[from][to] = 1;
                                        Pathfull.Add(PathID);
                                        newTransfer = DelayTime(PathID, listSensorBefore, listLinkBefore);
                                        Link createVirtualLink = new Link(listSensorBefore[from], listSensorBefore[to], "Virtual", Convert.ToInt16(newTransfer));
                                        if (checkLinkHave(createVirtualLink, listLinkAfter) == false)
                                        {
                                            DevLog.d(TAG, "Link created: " + createVirtualLink.getSource().getId() + " _ " + createVirtualLink.getDest().getId());
                                            listLinkAfter.Add(createVirtualLink);
                                            DevLog.d(TAG, "=======END========");
                                        }
                                        //listLinkAfterCluster.Add(createVirtualLink);
                                        //}

                                    }
                                    else
                                    {
                                        path = "";
                                        PathID = "";
                                        Dem_path = 0;
                                        DevLog.d(TAG, "Checking...to_from: " + to + " _ " + from);
                                        //MessageBox.Show("Path from " + to + " to " + from, "msg");
                                        //if (dijkstra(to, from, graphRouting) == true)
                                        if (FindAllPath(to, from, graphRouting) == true)
                                        {
                                            //MessageBox.Show("Path: " + path, "msg");

                                            //In ra t?t c? du?ng di
                                            double newTransfer;
                                            int dem_path_valid = Dem_path;//s? du?ng di h?p l?
                                            double[] delayRate = new double[Dem_path];
                                            char[] c = new char[] { ';' };
                                            string[] s1 = path.Split(c, StringSplitOptions.RemoveEmptyEntries);
                                            //Chuy?n các du?ng di index thành du?ng di d?ng ID
                                            ConvertPathID(s1, listSensorBefore);
                                            //MessageBox.Show("Path ID: " + PathID, "msg");
                                            //xét t?ng du?ng di có th?a di?u ki?n t?o link gi? không
                                            //string[] s2 = PathID.Split(c, StringSplitOptions.RemoveEmptyEntries);
                                            //for (int k = 0; k < s2.Length; k++)
                                            //{
                                            //    string temp = "";
                                            //    temp += s2[k];
                                            //    char[] d = new char[] { '-' };
                                            //    string[] temp_path = temp.Split(d, StringSplitOptions.RemoveEmptyEntries);
                                            //for (int z = 1; z < temp_path.Length - 1; z++)//ph?n t? d?u và cu?i luôn là 2 sensor du?c gi? l?i sau khi cluster
                                            //{
                                            //    for (int p = 0; p < listSensorAfter.Count; p++)
                                            //    {
                                            //        if (temp_path[z] == listSensorAfter[p].getId().ToString())
                                            //        {
                                            //            dem_path_valid--;//có b?t k? sensor nào du?c gi? l?i thì du?ng di dó b? b?
                                            //            //MessageBox.Show("Path not valid: " + temp, "Msg");
                                            //            //MessageBox.Show("path valid to break: " + dem_path_valid, "Msg");
                                            //            break;
                                            //        }
                                            //    }
                                            //    break;
                                            //}
                                            //}
                                            //if (dem_path_valid != 0)
                                            //{
                                            //MessageBox.Show("path valid: " + dem_path_valid, "Msg");
                                            graphRouting[to][from] = 1;
                                            Pathfull.Add(PathID);
                                            newTransfer = DelayTime(PathID, listSensorBefore, listLinkBefore);
                                            Link createVirtualLink = new Link(listSensorBefore[to], listSensorBefore[from], "Virtual", Convert.ToInt16(newTransfer));
                                            if (checkLinkHave(createVirtualLink, listLinkAfter) == false)
                                            {
                                                DevLog.d(TAG, "Link created: " + createVirtualLink.getSource().getId() + " _ " + createVirtualLink.getDest().getId());
                                                listLinkAfter.Add(createVirtualLink);
                                                DevLog.d(TAG, "=======END========");
                                            }
                                            //listLinkAfterCluster.Add(createVirtualLink);
                                            //}

                                        }
                                    }
                                    #region //Ðang th? in ra du?ng di
                                    //            //Ð?m du?ng
                                    //            int demduong = 0;
                                    //            for (int b = 0; b < path.Length; b++)
                                    //            {
                                    //                //MessageBox.Show("from " + (char)path[b] + " " + from, "Message");
                                    //                if (((char)path[b]).ToString() == from.ToString())
                                    //                {
                                    //                    demduong++;
                                    //                    //MessageBox.Show("from2 " + (char)path[b] + " " + from, "Message");
                                    //                }
                                    //                //MessageBox.Show("to " + (char)path[b] + " " + to, "Message");
                                    //                else if (((char)path[b]).ToString() == to.ToString())
                                    //                {
                                    //                    demduong++;
                                    //                    //MessageBox.Show("to2 " + (char)path[b] + " " + to, "Message");
                                    //                    break;
                                    //                }
                                    //                else demduong++;
                                    //                //MessageBox.Show("mang gom: " + demduong, "Message");
                                    //            }

                                    //            //MessageBox.Show("Break r: " + demduong, "Message");
                                    //            //for (int o = 0; o < temp.Length; o++)
                                    //            //{
                                    //            //    MessageBox.Show("" + temp[o], "Message");
                                    //            //}
                                    //            //Luu du?ng di vào m?ng 2 chi?u
                                    //            Pathfull[countVirtualLink] = new string[demduong];
                                    //            int dem = 0;

                                    //            for (int e = 0; e < Pathfull[countVirtualLink].Length; e++)
                                    //            {
                                    //                while (dem < path.Length)
                                    //                {
                                    //                    if (dem == demduong)
                                    //                    {
                                    //                        break;
                                    //                    }
                                    //                    //MessageBox.Show("from " + (char)path[b] + " " + from, "Message");
                                    //                    if (((char)path[dem]).ToString() == from.ToString())
                                    //                    {
                                    //                        Pathfull[countVirtualLink][e] = ((char)path[dem]).ToString();
                                    //                        dem++;
                                    //                        break;
                                    //                        //demduong++;

                                    //                        //MessageBox.Show("from2 " + (char)path[b] + " " + from, "Message");
                                    //                    }
                                    //                    //MessageBox.Show("to " + (char)path[b] + " " + to, "Message");
                                    //                    else if (((char)path[dem]).ToString() == to.ToString())
                                    //                    {
                                    //                        Pathfull[countVirtualLink][e] = ((char)path[dem]).ToString();
                                    //                        dem++;
                                    //                        //demduong++;

                                    //                        //demduong++;
                                    //                        //MessageBox.Show("to2 " + (char)path[b] + " " + to, "Message");
                                    //                        break;
                                    //                    }
                                    //                    else
                                    //                    {
                                    //                        Pathfull[countVirtualLink][e] = ((char)path[dem]).ToString();
                                    //                        dem++;
                                    //                        break;
                                    //                        //MessageBox.Show("mang gom: " + demduong, "Message");
                                    //                    }
                                    //                }
                                    //            }
                                    #endregion
                                }
                            }

                            //Ki?m tra list link after l?n n?a
                        Exception_Link:
                            for (int f1 = 0; f1 < listLinkAfter.Count; f1++)
                            {
                                if (listLinkAfter[f1].getLType() == "Virtual")
                                {
                                    for (int f2 = 0; f2 < listLinkAfter.Count; f2++)
                                    {
                                        if (listLinkAfter[f1].getDest().getId() == listLinkAfter[f2].getSource().getId())
                                        {
                                            for (int f3 = 0; f3 < listLinkAfter.Count; f3++)
                                            {
                                                if ((listLinkAfter[f1].getSource().getId() == listLinkAfter[f3].getSource().getId()) && (listLinkAfter[f2].getDest().getId() == listLinkAfter[f3].getDest().getId()))
                                                {
                                                    if (listLinkAfter[f3].getLType() == "Virtual")
                                                    {
                                                        listLinkAfter.RemoveAt(f3);
                                                        goto Exception_Link;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                if (listLinkAfter[f1].getLType() == "Real")
                                {
                                    for (int f2 = 0; f2 < listLinkAfter.Count; f2++)
                                    {
                                        if (listLinkAfter[f1].getDest().getId() == listLinkAfter[f2].getSource().getId())
                                        {
                                            for (int f3 = 0; f3 < listLinkAfter.Count; f3++)
                                            {
                                                if ((listLinkAfter[f1].getSource().getId() == listLinkAfter[f3].getSource().getId()) && (listLinkAfter[f2].getDest().getId() == listLinkAfter[f3].getDest().getId()))
                                                {
                                                    if (listLinkAfter[f3].getLType() == "Virtual")
                                                    {
                                                        listLinkAfter.RemoveAt(f3);
                                                        goto Exception_Link;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                            }
                            //Log.d(TAG, "====START=======");
                            //Log.d(TAG, "====LIST LINK AFTER CLUSTER=======");
                            //foreach (Link l in listLinkAfterCluster)
                            //{
                            //   DevLog.d(TAG, "src: " + l.getSource().getId() + " dest: " + l.getDest().getId());
                            //}
                            //Log.d(TAG, "====LIST LINK AFTER=======");
                            //foreach (Link l2 in listLinkAfter)
                            //{
                            //   DevLog.d(TAG, "src2: " + l2.getSource().getId() + " dest2: " + l2.getDest().getId());
                            //}
                            listLinkAfterCluster.AddRange(listLinkAfter);

                            //Log.d(TAG, "====END=======");

                            #region cmt
                            ////T?o các src sink gi? trong t?ng c?m
                            //int sourc = 0;
                            //int sink = 0;
                            ////int index_src;
                            ////int index_sink;
                            //bool flagCheck = false;
                            ///*
                            // * gi? nguyên source sink g?c,
                            // * n?u có source r thì các sensor khác không du?c là source,
                            // * n?u có sink r thì các sensor khác không du?c là sink,
                            // *
                            // */
                            //for (int s = 0; s < listSensorBefore.Count; s++)
                            //{
                            //    if (listSensorBefore[s].getstype() == 1)
                            //    {
                            //        sourc = listSensorBefore[s].getId();
                            //        //index_src = s;
                            //        //continue;
                            //    }
                            //    if (listSensorBefore[s].getstype() == 2)
                            //    {
                            //        sink = listSensorBefore[s].getId();
                            //        //index_sink = s;
                            //        //break;
                            //    }
                            //}
                            //#region //ch? có src
                            //if ((sourc != 0) && (sink == 0))//ch? có src
                            //{
                            //    for (int f = 0; f < listSensorAfter.Count; f++)
                            //    {
                            //        if (listSensorAfter[f].getId() == sourc)
                            //        {
                            //            continue;
                            //        }
                            //        else
                            //        {
                            //            //T?o sink gi?
                            //            for (int t = 0; t < LinkTo.Length; t++)
                            //            {
                            //                if (LinkTo[t] == listSensorAfter[f].getId())// có link di vào
                            //                {
                            //                    for (int s = 0; s < listSensorBefore.Count; s++)
                            //                    {
                            //                        if (LinkFrom[t] == listSensorBefore[s].getId())
                            //                        {
                            //                            flagCheck = false;//link t? sensor trong c?m
                            //                            continue;
                            //                        }
                            //                        else
                            //                        {
                            //                            flagCheck = true;//link t? sensor khác c?m
                            //                            break;
                            //                        }

                            //                    }
                            //                    if (flagCheck == true)
                            //                    {
                            //                        for (int g = 0; g < listSensorBefore.Count; g++)
                            //                        {
                            //                            if (listSensorAfter[f].getId() == listSensorBefore[g].getId())
                            //                            {
                            //                                listSensorBefore[g].SType = 2;
                            //                                //MessageBox.Show("Sensor " + listSensorBefore[g].getId() + ": " + listSensorBefore[g].getstype(), "msg");
                            //                            }

                            //                        }
                            //                        flagCheck = false;
                            //                    }
                            //                }
                            //            }

                            //        }

                            //    }
                            //}
                            //#endregion
                            //#region //ch? có sink
                            //if ((sourc == 0) && (sink != 0))//ch? có sink
                            //{
                            //    for (int f = 0; f < listSensorAfter.Count; f++)
                            //    {
                            //        if (listSensorAfter[f].getId() == sink)
                            //        {
                            //            continue;
                            //        }
                            //        else
                            //        {
                            //            //T?o src gi?
                            //            for (int t = 0; t < LinkFrom.Length; t++)
                            //            {
                            //                if (LinkFrom[t] == listSensorAfter[f].getId())// có link di ra
                            //                {
                            //                    for (int s = 0; s < listSensorBefore.Count; s++)
                            //                    {
                            //                        if (LinkTo[t] == listSensorBefore[s].getId())
                            //                        {
                            //                            flagCheck = false;//link ra sensor trong c?m
                            //                            continue;
                            //                        }
                            //                        else
                            //                        {
                            //                            flagCheck = true;//link ra sensor khác c?m
                            //                            break;
                            //                        }
                            //                    }
                            //                    if (flagCheck == true)
                            //                    {
                            //                        for (int g = 0; g < listSensorBefore.Count; g++)
                            //                        {
                            //                            if (listSensorAfter[f].getId() == listSensorBefore[g].getId())
                            //                            {
                            //                                listSensorBefore[g].SType = 1;
                            //                                //MessageBox.Show("Sensor " + listSensorBefore[g].getId() + ": " + listSensorBefore[g].getstype(), "msg");
                            //                            }

                            //                        }
                            //                        flagCheck = false;
                            //                    }
                            //                }

                            //            }

                            //        }

                            //    }
                            //}
                            //#endregion
                            //#region //không có src sink
                            //if ((sourc == 0) && (sink == 0))//không có src sink
                            //{

                            //}
                            //#endregion
                            #endregion
                            #endregion
                            #region //create virtual src & virtual sink
                            for (int g = 0; g < LinkFromgiunguyen.Length; g++)
                            {
                                //Log.d(TAG, "Link from " + LinkFromgiunguyen[g] + " to " + LinkTogiunguyen[g]);
                                if ((LinkFromgiunguyen[g] != 0) && (LinkTogiunguyen[g] != 0))
                                {
                                    //MessageBox.Show("Link from " + LinkFromgiunguyen[g] + " to " + LinkTogiunguyen[g], "msg");
                                    for (int f = 0; f < listSensorBefore.Count; f++)
                                    {
                                        //create virtual sink
                                        if (listSensorBefore[f].getId() == LinkFromgiunguyen[g])
                                        {
                                            for (int t = 0; t < sensor.Length; t++)
                                            {
                                                if (LinkTogiunguyen[g] == sensor[t][0])
                                                {
                                                    if (sensor[t][3] == 1)
                                                    {
                                                        continue;
                                                    }
                                                    else
                                                    {
                                                        //tempStype = sensor[t][3];
                                                        sensor[t][3] = 2;
                                                        Sensor virtualSink = new Sensor(LinkTogiunguyen[g], sensor[t][1], sensor[t][2], Convert.ToInt16(sensor[t][3]), Convert.ToInt16(sensor[t][4]), Convert.ToInt16(sensor[t][5]), sensor[t][6], sensor[t][7]);
                                                        if (listVirtualSink.Count == 0)
                                                        {
                                                            listVirtualSink.Add(virtualSink);
                                                            //break;
                                                        }
                                                        else if ((checkSensorHave(virtualSink, listVirtualSink)) == false)//check this sensor can have found in listSensorBefore return true, otherwise return false
                                                        {
                                                            listVirtualSink.Add(virtualSink);
                                                            //MessageBox.Show("list virtual from: "+listSensorBefore[f].getId() + " to sink " + virtualSink.getId(), "msg");
                                                            //MessageBox.Show("list virtual sink: " + (listVirtualSink.Contains(virtualSink)), "msg");
                                                            //sensor[t][3] = tempStype;
                                                            //break;
                                                        }
                                                        for (int k = 0; k < listLink.Count; k++)
                                                        {
                                                            if ((listLink[k].getSource().getId() == listSensorBefore[f].getId()) && (listLink[k].getDest().getId() == virtualSink.getId()))
                                                            {
                                                                if (checkLinkHave(listLink[k], listLinkBefore) == false)
                                                                {
                                                                    listLinkSink.Add(listLink[k]);
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                            break;
                                        }
                                        //create virtual src
                                        else if (listSensorBefore[f].getId() == LinkTogiunguyen[g])
                                        {
                                            for (int t = 0; t < sensor.Length; t++)
                                            {
                                                if (LinkFromgiunguyen[g] == sensor[t][0])
                                                {
                                                    if (sensor[t][3] == 2)
                                                    {
                                                        continue;
                                                    }
                                                    else
                                                    {
                                                        //tempStype = sensor[t][3];
                                                        sensor[t][3] = 1;
                                                        Sensor virtualSource = new Sensor(LinkFromgiunguyen[g], sensor[t][1], sensor[t][2], Convert.ToInt16(sensor[t][3]), Convert.ToInt16(sensor[t][4]), Convert.ToInt16(sensor[t][5]), sensor[t][6], sensor[t][7]);
                                                        if (listVirtualSource.Count == 0)
                                                        {
                                                            listVirtualSource.Add(virtualSource);
                                                            //break;
                                                        }
                                                        else if ((checkSensorHave(virtualSource, listVirtualSource)) == false)//check this sensor can have found in listSensorBefore return true, otherwise return false
                                                        {
                                                            listVirtualSource.Add(virtualSource);
                                                            //MessageBox.Show("list virtual from src: " + listSensorBefore[f].getId() + " to " + virtualSource.getId(), "msg");
                                                            //MessageBox.Show("list virtual src: " + (listVirtualSource.Contains(virtualSource)), "msg");
                                                            //sensor[t][3] = tempStype;
                                                            //break;
                                                        }
                                                        for (int k = 0; k < listLink.Count; k++)
                                                        {
                                                            if ((listLink[k].getSource().getId() == virtualSource.getId()) && (listLink[k].getDest().getId() == listSensorBefore[f].getId()))
                                                            {
                                                                if (checkLinkHave(listLink[k], listLinkBefore) == false)
                                                                {
                                                                    listLinkSource.Add(listLink[k]);
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                            #endregion

                            DevLog.d(TAG, "=======LIST VIRTUAL SRC=====");
                            foreach (Sensor src in listVirtualSource)
                            {
                                DevLog.d(TAG, "src: " + src.getId());
                            }
                            DevLog.d(TAG, "=======LIST VIRTUAL SINK=====");
                            foreach (Sensor sink in listVirtualSink)
                            {
                                DevLog.d(TAG, "sink: " + sink.getId());
                            }
                            //create one new virtual src & virtual sink
                            DevLog.d(TAG, "=======NEW VIRTUAL SRC=====");
                            int newIDSrc = maxIDSensor(listVirtualSource);//ID of Src have maxSending & minProcessing
                            DevLog.d(TAG, "=======NEW VIRTUAL SINK=====");
                            int newIDSink = maxIDSensor(listVirtualSink);//ID of Sink have maxSending & minProcessing
                            //int oldIDSrc=0;
                            //int oldIDSink=0;
                            foreach (Sensor src in listVirtualSource)
                            {
                                if (src.getId() == newIDSrc)
                                {
                                    Sensor newSrc = new Sensor(newIDSrc, averagePosition(listVirtualSource, 1), averagePosition(listVirtualSource, 2), src.getstype(), src.getsending_rate(), src.getprocessing_rate(), averageLabel(listVirtualSource, 1), averageLabel(listVirtualSource, 2));
                                    listSensorBefore.Add(newSrc);
                                }
                            }
                            foreach (Sensor sink in listVirtualSink)
                            {
                                if (sink.getId() == newIDSink)
                                {
                                    Sensor newSink = new Sensor(newIDSink, averagePosition(listVirtualSink, 1), averagePosition(listVirtualSink, 2), sink.getstype(), sink.getsending_rate(), sink.getprocessing_rate(), averageLabel(listVirtualSink, 1), averageLabel(listVirtualSink, 2));
                                    listSensorBefore.Add(newSink);
                                }
                            }
                            foreach (Link linkSrc in listLinkSource)
                            {
                                //oldIDSrc = linkSrc.getSource().getId();
                                linkSrc.getSource().setId = newIDSrc;
                                //listLinkBefore.Add(linkSrc);
                                //linkSrc.getSource().setId = oldIDSrc;
                            }
                            foreach (Link linkSink in listLinkSink)
                            {
                                //oldIDSink = linkSink.getDest().getId();
                                linkSink.getDest().setId = newIDSink;
                                //listLinkBefore.Add(linkSink);
                                //linkSink.getDest().setId = oldIDSink;
                            }
                            for (int s = 0; s < sensor.Length; s++)
                            {
                                DevLog.d(TAG, "Sensor in array sensor: " + sensor[s][0] + " - Stype: " + sensor[s][3]);
                                DevLog.d(TAG, "Sensor in list: " + listSensor[s].getId() + " - Stype: " + listSensor[s].getstype());
                            }

                            //listSensorBefore.AddRange(listVirtualSource);

                            //listSensorBefore.AddRange(listVirtualSink);
                            foreach (Link lSource in listLinkSource)
                            {
                                if (checkLinkHave(lSource, listLinkBefore) == false)
                                {
                                    listLinkBefore.Add(lSource);
                                }

                            }
                            foreach (Link lSink in listLinkSink)
                            {
                                if (checkLinkHave(lSink, listLinkBefore) == false)
                                {
                                    listLinkBefore.Add(lSink);
                                }

                            }

                            //listSensorBefore.AddRange(listVirtualSource);

                            //listSensorBefore.AddRange(listVirtualSink);

                            listVirtualLinkNeedCreate.RemoveRange(0, listVirtualLinkNeedCreate.Count);
                            state = 1;
                            saveClusters(listSensorBefore, listLinkBefore, i + 1, state, Pathfull);

                            DevLog.d(TAG, "=====Cluster " + i + "=========");
                            for (int s = 0; s < sensor.Length; s++)
                            {
                                if (Convert.ToInt16(sensor[s][0]) != listSensor[s].getId())
                                {
                                    listSensor[s].setId = Convert.ToInt16(sensor[s][0]);

                                }
                                if (Convert.ToInt16(sensor[s][3]) != listSensor[s].getstype())
                                {
                                    sensor[s][3] = listSensor[s].getstype();
                                    //Log.d(TAG, "Sensor: " + sen.getId() + " - Stype: " + sensor[s][3]);
                                    //break;
                                }
                                //Log.d(TAG, "Sensor: " + sen.getId() + " - Stype: " + sen.getstype());

                            }

                            listSensorBefore.Clear();
                            listLinkBefore.Clear();
                            listVirtualSource.Clear();
                            listVirtualSink.Clear();
                            listLinkSink.Clear();
                            listLinkSource.Clear();
                            //MessageBox.Show("Ðã xóa c?m: " + (i + 1), "Message");

                            state = 2;
                            saveClusters(listSensorAfter, listLinkAfter, i + 1, state, Pathfull);
                            listSensorAfter.Clear();
                            listLinkAfter.Clear();
                            //Pathfull.RemoveRange(0, Pathfull.Count);
                            String NoBeforeClusters = "Before_cluster " + (i + 1); ;
                            String NoAfterClusters = "After_cluster " + (i + 1); ;
                            listBeforeClusters.Add(NoBeforeClusters);
                            listAfterClusters.Add(NoAfterClusters);

                        }
                        DevLog.d(TAG, "======Path Full=======");
                        foreach (String pathfull in Pathfull)
                        {
                            DevLog.d(TAG, "" + pathfull);
                        }
                        for (int z = 0; z < LinkFromgiunguyen.Length; z++)
                        {
                            if ((LinkFromgiunguyen[z] != 0) && (LinkTogiunguyen[z] != 0))
                            {
                                foreach (Link l in listLink)
                                {
                                    if ((l.getSource().getId() == LinkFromgiunguyen[z]) && (l.getDest().getId() == LinkTogiunguyen[z]))
                                    {
                                        if (checkLinkHave(l, listLinkAfterCluster) == false)
                                        {
                                            listLinkAfterCluster.Add(l);
                                        }
                                    }
                                }
                            }
                        }
                        state = 3;
                        saveClusters(listSensorAfterCluster, listLinkAfterCluster, 0, state, Pathfull);
                        state = 1;// gán l?i b?ng 1 d? mu?n ch?y cluster n?a thì ch?y

                        #region cmt
                        //DialogResult traloi2;
                        //traloi2 = MessageBox.Show("Do you want export file XML of all clusters after calculate?", "Export Clusters DBScan", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        //if (traloi2 == DialogResult.Yes)
                        //{
                        //    //Xu?t XML t?ng c?m sau khi x? lý
                        //    for (int i = 0; i < sensorgiunguyen.Length; i++)
                        //    {

                        //        for (int j = 0; j < sensorgiunguyen[i].Length; j++)
                        //        {
                        //            for (int n = 0; n < sensor.Length; n++)
                        //            {
                        //                if (sensorgiunguyen[i][j] == sensor[n][0])
                        //                {
                        //                    Sensor test = new Sensor(sensorgiunguyen[i][j], sensor[n][1], sensor[n][2], Convert.ToInt16(sensor[n][3]));
                        //                    listSensorAfter.Add(test);
                        //                    listSensorAfterCluster.Add(test);
                        //                }
                        //            }
                        //            for (int n = j + 1; n < sensorgiunguyen[i].Length; n++)
                        //            {
                        //                for (int k = 0; k < LinkFrom.Length; k++)
                        //                {

                        //                }
                        //            }
                        //        }

                        //    }
                        //}

                        #endregion
                        // }
                        //listPathDirectoryOpen.RemoveRange(0,listPathDirectoryOpen.Count);
                        mClusterListener.onUpdateProgressbar(0);
                        //ProgressBar1.Value = 0;

                        //state = 3;
                        //SaveClusters(listSensorAfterCluster, listLinkAfterCluster, 0, state);
                        //state = 1;// gán l?i b?ng 1 d? mu?n ch?y cluster n?a thì ch?y
                        //saveClustering.ShowDialog();
                        //OpenFile(tmpName, true);
                    };
                    break;
                #endregion

                #region case "Random":
                case ClusterType.Random:
                    {
                        RandomForm rd = new RandomForm();
                        rd.Show();
                        rd.ButtonGetNumSenLinkClicked += (s4, e4) =>
                        {
                            NUM_SENSOR = Int32.Parse(rd.textBox1.Text);
                            NUM_LINK = Int32.Parse(rd.textBox2.Text);
                            rd.Close();

                            //// mlqvu -- Current disable this function
                            //saveRandomNetwork.ShowDialog();
                            //OpenFile(tmpName, true);
                        };
                        //WaitCallback wait = new WaitCallback(saveClustering_FileOk());

                        //rd.getsenlink(ref NUM_SENSOR, ref NUM_LINK);
                        break;
                    }
                #endregion
                default:
                    break;
            }
            //};
            #endregion
        }
        static void Create(string subscriptionId, string resourceGroupName, string clusterDnsName, string clusterLocation,
            List<AzureStorageConfig> asvAccounts, int clusterSize, string clusterUsername, string clusterPassword,
            string hdInsightVersion, List<SqlAzureConfig> sqlAzureMetaStores,
            ClusterType clusterType, OperatingSystemType osType)
        {
            Logger.InfoFormat("ResourceGroup: {0}, Cluster: {1} - Submitting a new cluster deployment request", resourceGroupName, clusterDnsName);

            var clusterCreateParameters = new ClusterCreateParameters()
                {
                    ClusterSizeInNodes = clusterSize,
                    ClusterType = (HDInsightClusterType)Enum.Parse(typeof(HDInsightClusterType), clusterType.ToString()),
                    DefaultStorageAccountKey = asvAccounts[0].Key,
                    DefaultStorageAccountName = asvAccounts[0].Name,
                    DefaultStorageContainer = asvAccounts[0].Container,
                    Location = clusterLocation,
                    Password = clusterPassword,
                    UserName = clusterUsername,
                    Version = hdInsightVersion,
                    OSType = (OSType)Enum.Parse(typeof(OSType), osType.ToString()),
                };

            if (clusterCreateParameters.OSType == OSType.Linux)
            {
                clusterCreateParameters.SshUserName = config.SshUsername;
                if (String.IsNullOrWhiteSpace(config.SshPassword))
                {
                    var publicKey = File.ReadAllText(config.SshPublicKeyFilePath);
                    Logger.Debug("SSH RSA Public Key: " + Environment.NewLine + publicKey + Environment.NewLine);
                    clusterCreateParameters.SshPublicKey = publicKey;
                }
                else
                {
                    clusterCreateParameters.SshPassword = config.SshPassword;
                }
            }
            else
            {
                if (config.AutoEnableRdp)
                {
                    clusterCreateParameters.RdpUsername = config.RdpUsername;
                    clusterCreateParameters.RdpPassword = config.RdpPassword;
                    clusterCreateParameters.RdpAccessExpiry = DateTime.Now.AddDays(int.Parse(config.RdpExpirationInDays));
                }
            }

            if (sqlAzureMetaStores != null && sqlAzureMetaStores.Count > 0)
            {
                var hiveMetastore = sqlAzureMetaStores.FirstOrDefault(s => s.Type.Equals("HiveMetastore"));
                if (hiveMetastore != null)
                {
                    clusterCreateParameters.HiveMetastore =
                        new Metastore(hiveMetastore.Server, hiveMetastore.Database, hiveMetastore.User, hiveMetastore.Password);
                }

                var oozieMetastore = sqlAzureMetaStores.FirstOrDefault(s => s.Type.Equals("OozieMetastore"));
                if (oozieMetastore != null)
                {
                    clusterCreateParameters.OozieMetastore =
                        new Metastore(oozieMetastore.Server, oozieMetastore.Database, oozieMetastore.User, oozieMetastore.Password);
                }
            }

            var localStopWatch = Stopwatch.StartNew();

            var createTask = hdInsightManagementClient.Clusters.CreateAsync(resourceGroupName, clusterDnsName, clusterCreateParameters);
            Logger.InfoFormat("Cluster: {0} - Create cluster request submitted with task id: {1}, task status: {2}",
                clusterDnsName, createTask.Id, createTask.Status);

            Thread.Sleep(pollInterval);

            var error = MonitorCreate(resourceGroupName, clusterDnsName, createTask);

            if (error)
            {
                if (config.CleanupOnError)
                {
                    Logger.InfoFormat("{0} - {1}. Submitting a delete request for the failed cluster creation.", Config.ConfigName.CleanupOnError.ToString(), config.CleanupOnError.ToString());
                    Delete(resourceGroupName, clusterDnsName);
                }
                else
                {
                    throw new ApplicationException(String.Format("Cluster: {0} - Creation unsuccessful", clusterDnsName));
                }
            }
            else
            {
                if (config.AutoEnableRdp && clusterCreateParameters.OSType == OSType.Windows)
                {
                    HDInsightManagementCLIHelpers.CreateRdpFile(clusterDnsName, config.RdpUsername, config.RdpPassword);
                }
            }
        }
예제 #50
0
파일: Common.cs 프로젝트: aash/Singular
        public static Composite CreateClusterHeal( string spell, ClusterType ct, int health, int range, int minCount)
        {
            return new Decorator(
                req => (req as WoWUnit).HealthPercent < health,
                new PrioritySelector(

                    ctx => Clusters.GetBestUnitForCluster(HealerManager.Instance.TargetList.Where(u => u.HealthPercent <= health), ct, range),

                    new Decorator(
                        req =>
                        {
                            if (req == null)
                                return false;

                            if (!Spell.CanCastHack(spell, (WoWUnit)req))
                                return false;

                            if (!((WoWUnit)req).InLineOfSpellSight)
                                return false;

                            int count = Clusters.GetClusterCount(
                                (WoWUnit)req,
                                HealerManager.Instance.TargetList.Where(u => u.HealthPercent <= health),
                                ct,
                                range
                                );

                            if (count < minCount)
                                return false;

                            Logger.Write( LogColor.Hilite, "^Casting {0} on {1} in attempt to hit {2} members below {3}%", spell, ((WoWUnit)req).SafeName(), count, health);
                            return true;
                        },

                        new Sequence(
                            new DecoratorContinue(
                                req => !Me.IsSafelyFacing((WoWUnit)req, 5f),
                                new PrioritySelector(
                                    new Sequence(
                                        new Action(r => Logger.WriteDiagnostic("{0}: trying to face {1}", spell, ((WoWUnit)r).SafeName())),
                                        new Action(r => ((WoWUnit)r).Face()),
                                        new Wait(TimeSpan.FromMilliseconds(1500), until => Me.IsSafelyFacing((WoWUnit)until, 5f), new ActionAlwaysSucceed()),
                                        new Action(r => Logger.Write("{0}:  succeeded at facing {1}", spell, ((WoWUnit)r).SafeName()))
                                        ),
                                    new Action(r =>
                                    {
                                        Logger.Write("{0}:  failed at facing {1}", spell, ((WoWUnit)r).SafeName());
                                        return RunStatus.Failure;
                                    })
                                    )
                                ),

                            Spell.Cast(spell, mov => true, on => (WoWUnit)on, req => true, cancel => false)
                            )
                        )
                    )
                );
        }
예제 #51
0
 public void Run(ClusterType clustertype)
 {
     switch (clustertype)
         {
             case ClusterType.Grid:
                 _clusters = new GridCluster(_points).GetCluster();
                 DisplayGridInCanvas = true;
                 break;
             case ClusterType.KMeans:
                 _clusters = new KMeans(_points).GetCluster();
                 break;
             case ClusterType.MarkerClusterer:
                 _clusters = new MarkerClusterer(_points).GetCluster();
                 break;
             case ClusterType.DistanceClusterer:
                 _clusters = new DistanceClusterer(_points).GetCluster();
                 break;
             case ClusterType.Unknown:
                 break;
         }
 }
예제 #52
0
        public Contracts.SmallGroupClusterType GetSmallGroupClusterType(int clusterTypeID)
        {
            Contracts.SmallGroupClusterTypeMapper mapper = new Contracts.SmallGroupClusterTypeMapper();
            ClusterType type = new ClusterType(clusterTypeID);

            if (type.ClusterTypeID == -1)
                throw new Arena.Services.Exceptions.ResourceNotFoundException("Invalid cluster type ID");

            return mapper.FromArena(type);
        }
예제 #53
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Constructor creates a new one-sided cluster with only one item.
		/// This is valid only for Missing/Added Cluster types.
		/// Useful for forming smaller clusters as we break down a complex cluster.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		public Cluster(ClusterType type, OverlapInfo sourceItem, int indexToInsertAtInDest)
		{
			Debug.Assert(type == ClusterType.AddedToCurrent || type == ClusterType.MissingInCurrent);

			clusterType = type;
			verseRefMin = sourceItem.verseRefMin;
			verseRefMax = sourceItem.verseRefMax;
			indexToInsertAtInOther = indexToInsertAtInDest;
			itemsCurr = new List<OverlapInfo>(6);
			itemsRev = new List<OverlapInfo>(6);
			SourceItems.Add(sourceItem);
		}
예제 #54
0
파일: Cluster.cs 프로젝트: svermeulen/iris
        internal void SetContentsTo(string csvSetNames)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(csvSetNames, "csvSetNames");

            EnsureFinalMembershipWasNotCached();

            string[] items = StringExtensions.Normalize(csvSetNames).Split(',');
            this.m_ClusterType = MembershipTypeFromString(items[0]);

            this.m_containedGroupsAndClusters = this.ExpandWildcardGroupNames(items);
        }
예제 #55
0
 public Cluster(ClusterType type, Coordinates coordinates)
     : this(type, coordinates.X, coordinates.Y)
 {
 }
        private bool IsServerValidForCluster(ClusterType clusterType, ClusterConnectionMode connectionMode, ServerType serverType)
        {
            switch (clusterType)
            {
                case ClusterType.ReplicaSet:
                    return serverType.IsReplicaSetMember();

                case ClusterType.Sharded:
                    return serverType == ServerType.ShardRouter;

                case ClusterType.Standalone:
                    return serverType == ServerType.Standalone;

                case ClusterType.Unknown:
                    switch (connectionMode)
                    {
                        case ClusterConnectionMode.Automatic:
                        case ClusterConnectionMode.Direct:
                            return true;

                        default:
                            throw new MongoInternalException("Unexpected connection mode.");
                    }

                default:
                    throw new MongoInternalException("Unexpected cluster type.");
            }
        }
예제 #57
0
 /// <summary>
 /// Create an empty configuration of the specified type.
 /// </summary>
 /// <param name="type">Configuration type.</param>
 /// <returns>The created configuration.</returns>
 public static ClusterConfiguration CreateConfiguration(ClusterType type)
 {
     switch (type)
     {
         case ClusterType.Cache:
             return new CacheClusterConfiguration();
         case ClusterType.LocalEmulator:
             return new LocalEmulator();
         case ClusterType.AzureDfs:
             return new AzureDfsClusterConfiguration();
         case ClusterType.WebHdfs:
             return new WebHdfsClusterConfiguration();
         case ClusterType.Hdfs:
             return new HdfsClusterConfiguration();
         case ClusterType.Unknown:
         case ClusterType.MaxUnused:
         default:
             return new ErrorConfiguration("Unsupported cluster type " + type);
     }
 }
        public SmallGroupClusterType FromArena(ClusterType arena)
        {
            SmallGroupClusterType type = new SmallGroupClusterType();
            SmallGroupClusterLevelMapper levelMapper = new SmallGroupClusterLevelMapper();

            type.ClusterTypeID = arena.ClusterTypeID;
            type.AllowOccurrences = arena.AllowOccurrences;
            type.AllowRegistration = arena.AllowRegistration;
            type.CategoryID = arena.CategoryID;
            type.LeaderRelationshipStrength = arena.LeaderRelationshipStrength;
            type.Name = arena.Name;
            type.PeerRelationshipStrength = arena.PeerRelationshipStrength;

            type.Levels = new List<SmallGroupClusterLevel>();
            foreach (ClusterLevel lv in arena.Levels)
            {
                type.Levels.Add(levelMapper.FromArena(lv));
            }

            return type;
        }
 public void Run(ClusterType clustertype)
 {
     //set a clusters constant
     GlobalClass.program += "9. Run .. ";
     _clusters = new KMeans(_points).GetCluster();
 }
 public static void DeleteClusterIfExists(ClusterType clusterType)
 {
     var name = AppConfig.AzureResourceName + clusterType.ToString().ToLowerInvariant();
     LOG.Info(String.Format("Deleting Cluster: Name = {0}, Type = {1}", name, clusterType));
     DeleteClusterIfExists(name);
 }