Ejemplo n.º 1
0
        public static IEnumerable<Int64> Split(this Int64 value)
        {
            var intParts = new List<Int64>();

            do
            {
                intParts.Add(value % 10);
            } while ((value /= 10) > 0);

            intParts.Reverse();

            return intParts;
        }
		static List<FS2JournalItem> GetJournalItems(Device device, int journalType, int currentStage, int stageCount)
		{
			var result = new List<FS2JournalItem>();

			CallbackManager.AddProgress(new FS2ProgressInfo("Чтение индекса последней записи", 50, currentStage, stageCount));
			var response = USBManager.Send(device, "Чтение индекса последней записи", 0x01, 0x21, journalType);
			if (response.HasError)
				return null;
			int lastIndex = BytesHelper.ExtractInt(response.Bytes, 0);

			CallbackManager.AddProgress(new FS2ProgressInfo("Чтение индекса первой записи", 50, currentStage, stageCount));
			response = USBManager.Send(device, "Чтение индекса первой записи", 0x01, 0x24, journalType);
			if (response.HasError)
				return null;
			var count = BytesHelper.ExtractShort(response.Bytes, 0);

			int firstIndex = Math.Max(lastIndex - count + 1, 0);

			for (int i = firstIndex; i <= lastIndex; i++)
			{
				var journalName = "Чтение пожарных записей журнала ";
				if (journalType == 0x02)
					journalName = "Чтение охранных записей журнала ";
				CallbackManager.AddProgress(new FS2ProgressInfo(journalName + (i - firstIndex).ToString() + " из " + (lastIndex - firstIndex + 1).ToString(),
					(i - firstIndex) * 100 / (lastIndex - firstIndex), currentStage, stageCount));
				response = USBManager.Send(device, "Чтение конкретной записи журнала", 0x01, 0x20, journalType, BitConverter.GetBytes(i).Reverse());
				if (!response.HasError)
				{
					try
					{
						var journalParser = new JournalParser();
						var journalItem = journalParser.Parce(null, device, response.Bytes, journalType);
						if (journalItem != null)
						{
							result.Add(journalItem);
						}
					}
					catch (Exception e)
					{
						Logger.Error(e, "ReadJournalOperationHelper.Parse");
					}
				}
			}

			result.Reverse();
			for (int i = 0; i < result.Count; i++)
			{
				result[i].No = i + 1;
			}
			return result;
		}
Ejemplo n.º 3
0
        // Returns the computed path by the RRT, and smooth it if that's the case
        private List<Node> ReturnPath(Node endNode, bool smooth)
        {
            Node n = endNode;
            List<Node> points = new List<Node> ();

            while (n != null) {
                points.Add (n);
                n = n.parent;
            }
            points.Reverse ();

            // If we didn't find a path
            if (points.Count == 1)
                points.Clear ();
            else if (smooth) {
                // Smooth out the path
                Node final = null;
                foreach (Node each in points) {
                    final = each;
                    while (Extra.Collision.SmoothNode(final, this, SpaceState.Editor, true)) {
                    }
                }

                points.Clear ();

                while (final != null) {
                    points.Add (final);
                    final = final.parent;
                }
                points.Reverse ();
            }

            return points;
        }
Ejemplo n.º 4
0
        private List<RouteInstance> completeDelivery(RouteNode goal)
        {
            List<RouteInstance> path = new List<RouteInstance>();
            RouteNode nextNode = goal;
            RouteInstance nextInstance;

            //int totalCost = 0;
            //int totalPrice = 0;

            do
            {
                nextInstance = originPath[nextNode];
                path.Add(nextInstance);
                nextNode = nextInstance.Route.Origin;
                /*
                    totalCost += nextInstance.Route.CostPerCm3 * delivery.VolumeInCm3;
                    totalCost += nextInstance.Route.CostPerGram * delivery.WeightInGrams;

                    totalPrice += nextInstance.Route.PricePerCm3 * delivery.VolumeInCm3;
                    totalPrice += nextInstance.Route.PricePerGram * delivery.WeightInGrams;
                */
            }
            while (originPath[nextNode].Route != null);
            /*
                delivery.TotalCost = totalCost;
                delivery.TotalPrice = totalPrice;
                delivery.TimeOfDelivery = originPath[delivery.Destination].ArrivalTime;
            */
            path.Reverse(0, path.Count);
            return path;
        }
Ejemplo n.º 5
0
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, float playerSpeed)
        {
            this.speed = 1.0d / playerSpeed;
            try {
                Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (1000000);
                List<Node> closed = new List<Node> ();

                // Initialize our version of the matrix (can we skip this?)
                Node[][][] newMatrix = new Node[matrix.Length][][];
                for (int t=0; t<matrix.Length; t++) {
                    newMatrix [t] = new Node[matrix [t].Length][];
                    for (int x = 0; x < matrix [t].Length; x++) {
                        newMatrix [t] [x] = new Node[matrix [t] [x].Length];
                        for (int y = 0; y < matrix [t] [x].Length; y++) {
                            newMatrix [t] [x] [y] = new Node ();
                            newMatrix [t] [x] [y].parent = null;
                            newMatrix [t] [x] [y].cell = matrix [t] [x] [y];
                            newMatrix [t] [x] [y].x = x;
                            newMatrix [t] [x] [y].y = y;
                            newMatrix [t] [x] [y].t = t;
                        }
                    }
                }
                // Do the work for the first cell before firing the algorithm
                start = newMatrix [0] [startX] [startY];
                end = newMatrix [0] [endX] [endY];
                start.parent = null;
                start.visited = true;
                start.accSpeed = speed - Math.Floor(speed);
                foreach (Node n in getAdjacent(start, newMatrix)) {
                    n.parent = start;
                    float fVal = f (n);
                    n.Priority = fVal;
                    heap2.Enqueue (n, fVal);
                }
                while (heap2.Count != 0) {
                    Node first = heap2.Dequeue ();
                    if (first.x == end.x && first.y == end.y) {
                        end = newMatrix [first.t] [end.x] [end.y];
                        break;
                    }
                    first.visited = true;
                    foreach (Node m in getAdjacent(first, newMatrix)) {
                        float currentG = g (first) + h (m, first);
                        float gVal = g (m);
                        if (m.visited) {
                            if (gVal > currentG) {
                                m.parent = first;
                                acc(m);
                            }
                        } else {
                            if (!heap2.Contains (m)) {
                                m.parent = first;
                                m.Priority = f (m);
                                heap2.Enqueue (m, m.Priority);
                                acc(m);
                            } else {
                                if (gVal > currentG) {
                                    m.parent = first;
                                    m.Priority = f (m);
                                    heap2.UpdatePriority (m, m.Priority);
                                    acc(m);
                                }
                            }
                        }
                    }
                }
                // Creates the result list
                Node e = end;
                List<Node> points = new List<Node> ();
                while (e != null) {
                    points.Add (e);
                    e = e.parent;
                }
                points.Reverse ();

                // If we didn't find a path
                if (points.Count == 1)
                    points.Clear ();
                return points;
            } catch (System.Exception e) {
                Debug.Log (e.Message);
                Debug.Log (e.StackTrace);
                Debug.Log ("ERROR 2");
                return null;
            }
        }
Ejemplo n.º 6
0
		public static List<JournalItem> GetTopLast(int count)
		{
			var journalItems = new List<JournalItem>();
			try
			{
				lock (locker)
				{
					if (File.Exists(AppDataFolderHelper.GetDBFile("GkJournalDatabase.sdf")))
					{
						using (var dataContext = new SqlCeConnection(ConnectionString))
						{
							var query = "SELECT TOP (" + count.ToString() + ") * FROM Journal ORDER BY SystemDateTime DESC";
							var sqlCeCommand = new SqlCeCommand(query, dataContext);
							dataContext.Open();
							var reader = sqlCeCommand.ExecuteReader();
							while (reader.Read())
							{
								var journalItem = ReadOneJournalItem(reader);
								journalItems.Add(journalItem);
							}
						}
					}
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "GKDBHelper.GetTopLast");
			}
			journalItems.Reverse();
			return journalItems;
		}
Ejemplo n.º 7
0
        public static IEnumerable<Candidate> GetCandidates(
            ExplorationSpace space,
            ExplorationNode start,
            ExplorationNode lastGoal,
            HashSet<uint> busyObjects,
            Scorer scorer,
            int numRecommendations,
            bool descending)
        {
            if (busyObjects == null)
                busyObjects = new HashSet<uint>();

            List<Candidate> candidates = new List<Candidate>();
            foreach (ExplorationNode node in space.Nodes)
            {
                if (start == node)
                    continue;

                // Make sure it's reachable
                ExplorationEdge[] path = start.GetPathOut(node.Id);
                if (path != null)
                {
                    // Add it as a candidate if the score is high enough
                    double score = scorer(start, node);
                    ExplorationEdge edge = path[0];
                    ExplorationNode goal = path.Last().Target;
                    double sentimentScore = SentimentScore(score, path);
                    candidates.Add(new Candidate(path, goal, sentimentScore));
                }
            }

            // Sort the candidates by score
            candidates.Sort((c1, c2) => c1.Score.CompareTo(c2.Score));
            if (descending == true)
                candidates.Reverse();

            // Add the previous goal to the front if we still have a path to it
            if (lastGoal != null)
            {
                ExplorationEdge[] oldPath = start.GetPathOut(lastGoal.Id);
                if (oldPath != null)
                    candidates.Insert(0, new Candidate(oldPath, lastGoal, 0.0));
            }

            HashSet<ExplorationNode> seenGoals = new HashSet<ExplorationNode>();
            HashSet<ExplorationEdge> seenEdges = new HashSet<ExplorationEdge>();

            // Pick the top N
            int count = 0;
            foreach (Candidate candidate in candidates)
            {
                ExplorationNode goal = candidate.Goal;
                if (candidate.Path.Length == 0)
                    continue;
                ExplorationEdge edge = candidate.Path[0];

                // Nix this event if it uses an object that's currently in use
                // TODO: Assumes only one event per edge
                TransitionEvent evt = edge.Events[0];
                foreach (uint id in evt.Participants)
                    if (busyObjects.Contains(id) == true)
                        goto skipCandidate;

                // If this is a novel direction to go, add it
                bool seenGoal = seenGoals.Contains(goal);
                bool seenEdge = seenEdges.Contains(edge);

                if (seenGoal == false && seenEdge == false)
                {
                    seenGoals.Add(goal);
                    seenEdges.Add(edge);
                    count++;
                    yield return candidate;
                }

                if (count >= numRecommendations)
                    break;

                skipCandidate : continue;
            }
        }
Ejemplo n.º 8
0
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][] matrix, bool improve)
        {
            List<Node> opened = new List<Node> ();
            Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (600);

            List<Node> closed = new List<Node> ();

            // Initialize our version of the matrix (can we skip this?)
            Node[][] newMatrix = new Node[matrix.Length][];
            for (int x = 0; x < matrix.Length; x++) {
                newMatrix [x] = new Node[matrix [x].Length];
                for (int y = 0; y < matrix[x].Length; y++) {
                    newMatrix [x] [y] = new Node ();
                    newMatrix [x] [y].parent = null;
                    newMatrix [x] [y].cell = matrix [x] [y];
                    newMatrix [x] [y].x = x;
                    newMatrix [x] [y].y = y;
                }
            }

            // Do the work for the first cell before firing the algorithm
            start = newMatrix [startX] [startY];
            end = newMatrix [endX] [endY];

            closed.Add (start);

            foreach (Node c in getAdjacent(start, newMatrix)) {
                c.parent = start;
                if (improve)
                    heap2.Enqueue (c, f (c));
                else
                    opened.Add (c);
            }

            while ((improve && heap2.Count > 0) || (!improve && opened.Count > 0)) {

                // Pick the closest to the goal
                Node minF = null;
                if (improve) {
                    minF = heap2.Dequeue ();
                } else {
                    for (int i = 0; i < opened.Count; i++) {
                        if (minF == null || f (minF) > f (opened [i]))
                            minF = opened [i];
                    }
                    opened.Remove (minF);
                }

                closed.Add (minF);

                // Found it
                if (minF == end)
                    break;

                foreach (Node adj in getAdjacent(minF, newMatrix)) {

                    float soFar = g (minF) + h (adj, minF);

                    // Create the links between cells (picks the best path)
                    if (closed.Contains (adj)) {
                        if (g (adj) > soFar) {
                            adj.parent = minF;
                        }
                    } else {
                        if ((improve && heap2.Contains (adj)) || (!improve && opened.Contains (adj))) {
                            if (g (adj) > soFar) {
                                adj.parent = minF;
                            }
                        } else {
                            adj.parent = minF;
                            if (improve)
                                heap2.Enqueue (adj, f (adj));
                            else
                                opened.Add (adj);
                        }
                    }
                }
            }

            // Creates the result list
            Node n = end;
            List<Node> points = new List<Node> ();
            while (n != null) {
                points.Add (n);
                n = n.parent;
            }
            points.Reverse ();

            // If we didn't find a path
            if (points.Count == 1)
                points.Clear ();
            return points;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 合并:地址 + 命令 + 子命令 + 专用码
        /// </summary>
        /// <param name="dataType"></param>
        /// <param name="dataBlock"></param>
        /// <param name="specialCode"></param>
        /// <returns></returns>
        private List<byte> MergeDataBlock(string dataType,List<byte>dataBlock=null,int specialCode=0)
        {
            try
            {
                if (dataType == null)
                    return null;
                if (dataType.Equals(string.Empty)||dataType=="\0"||dataType.Length<=1)
                {
                    return null;
                }
                var protocolFactory = new List<byte>();
                // +地址 + 命令 + 子命令 + 专用码
                protocolFactory.AddRange(CommonLib.ByteToAscByte(ProtocolAddress));
                protocolFactory.Add((byte)CommonLib.StringToAsc(dataType[0].ToString()));
                protocolFactory.Add((byte)CommonLib.StringToAsc(dataType[1].ToString()));

                if (dataBlock != null)
                {
                    //逆序dataBlock块--不想吐槽协议这sb行为
                    if (dataBlock.Count > 1 && dataBlock.Count%2 == 0)
                    {
                        for (int i = 0; i < dataBlock.Count/2; i++)
                        {
                            dataBlock.Reverse(i*2, 2);
                        }
                    }
                    else if (dataBlock.Count==3)
                    {
                        dataBlock.Reverse(1, 2);
                    }

                    protocolFactory.AddRange(dataBlock);
                }
                if (specialCode > 255)
                    return null;
                if (specialCode > 0)
                {
                    protocolFactory.Add((byte)specialCode);
                }
                return protocolFactory;
            }
            catch (FormatException)
            {
                return null;
            }
        }
Ejemplo n.º 10
0
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, int time, bool prob)
        {
            try{
            Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node>(600);

            // Initialize our version of the matrix (can we skip this?)
            Node[][] newMatrix = new Node[matrix[0].Length][];
            for (int x = 0; x < matrix [0].Length; x++) {
                newMatrix [x] = new Node[matrix [0] [x].Length];
                for (int y = 0; y < matrix [0] [x].Length; y++) {
                    newMatrix [x] [y] = new Node ();
                    newMatrix [x] [y].parent = null;
                    newMatrix [x] [y].cell = matrix [0] [x] [y];
                    newMatrix [x] [y].x = x;
                    newMatrix [x] [y].y = y;
                }
            }
            enemyPathProb(newMatrix);
            // Do the work for the first cell before firing the algorithm
            start = newMatrix [startX] [startY];
            end = newMatrix [endX] [endY];
            start.parent=null;
            start.visited=true;

            foreach (Node n in getAdjacent(start, newMatrix)) {
                n.t=time;
                n.parent = start;
                float fVal = f (n);
                n.Priority = fVal;
                heap2.Enqueue(n,fVal);
            }
            while(heap2.Count != 0){

                Node first = heap2.Dequeue();
                if(first == end)
                    break;
                first.visited=true;
                double temprt = 1;
                List<Node> adjs = getAdjacent(first,newMatrix);

                foreach(Node m in adjs){
                    float currentG = (float)(g (first) + h (first,m, ref temprt));
                    if(m.visited){
                            if(g (m)>currentG){
                                m.parent=first;
                                m.t = first.t+time;
                            }
                        }
                    else{
                        if( !heap2.Contains(m)){
                            m.parent = first;
                            m.t= first.t +time;
                            m.Priority = (float)temprt*f(m);
                            heap2.Enqueue(m, m.Priority);
                        }
                        else
                        {
                            float gVal = g (m);
                            if(gVal>currentG){
                                m.parent= first;
                                m.t = first.t+time;
                                m.Priority= (float)temprt *f (m);
                                heap2.UpdatePriority(m, m.Priority);
                            }
                        }
                    }
                }
            }
                // Creates the result list
                Node l = end;
                List<Node> points = new List<Node> ();
                while (l != null) {
                    points.Add (l);
                    l = l.parent;
                }
                points.Reverse ();

                // If we didn't find a path
                if (points.Count == 1)
                points.Clear ();
                return points;
            }catch(System.Exception e){
                                Debug.Log (e.Message);
                                Debug.Log (e.StackTrace);
                                Debug.Log ("ERROR 2");
                                return null;
                        }
        }
Ejemplo n.º 11
0
        private static void SaveDirectoryToDB(SqlConnection conn, String schema, String appName, String baseDirectory, String directory)
        {
            foreach (String fileName in System.IO.Directory.GetFiles(directory))
            {
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandTimeout = 300;
                cmd.Connection = conn;
                cmd.CommandText =
                    String.Format("INSERT INTO {0}.{1}([Id],[Name],[Data],[Parent]) VALUES(@Id, @Name, @Data, @Parent)"
                    , schema, baseDirectory);

                System.Data.SqlClient.SqlParameter p;

                p = cmd.Parameters.Add("@Id", System.Data.SqlDbType.UniqueIdentifier);
                p.Value = System.Guid.NewGuid();

                p = cmd.Parameters.Add("@Name", System.Data.SqlDbType.VarChar);
                p.Value = String.Format("{0}/{1}", appName, new System.IO.FileInfo(fileName).Name);

                p = cmd.Parameters.Add("@Data", System.Data.SqlDbType.Text);
                p.Value = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(fileName));

                p = cmd.Parameters.Add("@Parent", System.Data.SqlDbType.VarChar);

                string[] directories = Path.GetDirectoryName(fileName).Split(Path.DirectorySeparatorChar);

                List<string> result = new List<string>();
                for (int i = directories.Length - 1; i >= 0; i--)
                {
                    if (directories[i] == baseDirectory)
                        break;
                    else
                        result.Add(directories[i]);
                }
                result.Reverse();

                string resultPath = "";
                foreach (var item in result)
                    resultPath += Path.DirectorySeparatorChar + item;

                p.Value = resultPath;
                cmd.ExecuteNonQuery();
            }

            foreach (var subDir in Directory.GetDirectories(directory))
                SaveDirectoryToDB(conn, schema, appName, baseDirectory, subDir);
        }