Example #1
0
    public static void PrintResult(List<short> number, short userNum)
    {
        int counter = 0;
        Console.Write("\nThe Binary representation of {0} is: ", userNum);

        number.Reverse();
        if (number.Count < 16)
        {
            for (int i = number.Count; i < 16; i++)
            {
                number.Add(0);
            }
        }

        number.Reverse();

        foreach (short bit in number)
        {
            Console.Write(bit);
            counter++;

            if (counter % 4 == 0)
            {
                Console.Write(" ");
            }
        }

        Console.WriteLine();
    }
Example #2
0
		public static InitializerPath FromResolveResult(ResolveResult resolveResult)
		{
			InitializerPath initializerPath = null;
			var memberPath = new List<IMember>();
			var currentResolveResult = resolveResult;
			do {
				if (currentResolveResult is MemberResolveResult) {
					var memberResolveResult = (MemberResolveResult)currentResolveResult;
					memberPath.Add(memberResolveResult.Member);
					currentResolveResult = memberResolveResult.TargetResult;
				} else if (currentResolveResult is LocalResolveResult) {
					var localResolveResult = (LocalResolveResult)currentResolveResult;
					memberPath.Reverse();
					initializerPath = new InitializerPath(localResolveResult.Variable) {
						MemberPath = memberPath
					};
					break;
				} else if (currentResolveResult is ThisResolveResult) {
					break;
				} else {
					return null;
				}

			} while (currentResolveResult != null);

			if (initializerPath == null) {
				// This path is rooted at a member
				memberPath.Reverse();
				initializerPath = new InitializerPath(memberPath [0]) {
					MemberPath = memberPath.Skip(1).ToList()
				};
			}
			return initializerPath;
		}
 private IEnumerator AnimateModuleExpandCoroutine(bool expand)
 {
     _isAnimating = true;
     var sprites = new List<Sprite>(ShowModuleSprites);
     if (!expand)
     {
         sprites.Reverse();
         foreach (var subsystem in Subsystems)
         {
             subsystem.SetActive(false);
         }
     }
     var moduleImage = ModuleButtonGO.GetComponent<Button>();
     foreach (var sprite in sprites)
     {
         moduleImage.image.sprite = sprite;
         moduleImage.image.rectTransform.sizeDelta = new Vector2(sprite.rect.width, sprite.rect.height);
         yield return new WaitForSeconds(0.03f);
     }
     if (expand)
     {
         sprites.Reverse();
         foreach (var subsystem in Subsystems)
         {
             subsystem.SetActive(true);
         }
     }
     _isAnimating = false;
 }
Example #4
0
    static void Main()
    {
        Console.Write("Enter 16-bit signed number: ");
        int number = int.Parse(Console.ReadLine());
        string binaryNumber = "";

        List<int> digits = new List<int>();

        if (number >= 0)
        {
            while (number != 0)
            {
                digits.Add(number % 2);
                number /= 2;
            }

            digits.Reverse();

            for (int i = 0; i < digits.Count; i++)
            {
                binaryNumber += digits[i];
            }

            while (binaryNumber.Length % 16 != 0)
            {
                binaryNumber = "0" + binaryNumber;
            }
        }
        else
        {
            number = Math.Abs(number) - 1;

            while (number != 0)
            {
                digits.Add(number % 2);
                number /= 2;
            }

            digits.Reverse();

            for (int i = 0; i < digits.Count; i++)
            {
                if (digits[i] == 0)
                {
                    binaryNumber += "1";
                }
                else
                {
                    binaryNumber += "0";
                }
            }

            while (binaryNumber.Length % 16 != 0)
            {
                binaryNumber = "1" + binaryNumber;
            }
        }
        Console.Write("Result: ");
        Console.WriteLine(binaryNumber);
    }
Example #5
0
		public static AccessPath FromResolveResult(ResolveResult resolveResult)
		{
			var memberPath = new List<IMember>();
			var currentResolveResult = resolveResult;
			do {
				if (currentResolveResult is MemberResolveResult) {
					var memberResolveResult = (MemberResolveResult)currentResolveResult;
					memberPath.Add(memberResolveResult.Member);
					currentResolveResult = memberResolveResult.TargetResult;
				} else if (currentResolveResult is LocalResolveResult) {
					// This is the root variable
					var localResolveResult = (LocalResolveResult)currentResolveResult;
					memberPath.Reverse();
					return new AccessPath(localResolveResult.Variable) {
						MemberPath = memberPath
					};
				} else if (currentResolveResult is ThisResolveResult) {
					break;
				} else {
					// Unsupported path
					return null;
				}
			} while (currentResolveResult != null);

			memberPath.Reverse();
			return new AccessPath(null) {
				MemberPath = memberPath
			};
		}
Example #6
0
        static void Main(string[] args)
        {
            int input = int.Parse(Console.ReadLine());
            int frozenPosition = int.Parse(Console.ReadLine());

            // We don't need to roll the bits more than 18 times.
            int rollTimes = int.Parse(Console.ReadLine()) % 18;

            char[] bitArray = Convert.ToString(input, 2).ToCharArray();
            List<char> charList = new List<char>(bitArray);
            charList.Reverse();

            while (charList.Count <= 18) // Make sure the list contains 19 elements.
            {
                charList.Add('0');
            }

            char frozenBit = charList[frozenPosition];
            char temporary = '0';
            charList.RemoveAt(frozenPosition);

            for (int i = 0; i < rollTimes; i++)
            {
                temporary = charList.First();
                charList.RemoveAt(0);
                charList.Add(temporary);
            }

            charList.Insert(frozenPosition, frozenBit);

            charList.Reverse();
            string output = string.Join("", charList);
            Console.WriteLine(Convert.ToInt32(output, 2));
        }
Example #7
0
        /// <summary>
        /// Formats the table of Messages based on the given list of Messages and colors.
        /// </summary>
        /// <param name="messages">The list of messages to display in the table</param>
        /// <param name="backColors">The list of alternating background colors to display in the table</param>
        /// <param name="textColors">The list of alternating text colors to display in the table</param>
        public void PopulateMessageTable(List<ActivEarth.Objects.Groups.Message> messages, Color[] backColors, Color[] textColors)
        {
            int colorIndex = 0;
            int textIndex = 0;

            messages.Reverse();
            foreach (ActivEarth.Objects.Groups.Message message in messages)
            {
                _wall.Rows.Add(MakeRowForTable(message, backColors[colorIndex], textColors[textIndex]));

                colorIndex++;
                if (colorIndex == backColors.Length)
                {
                    colorIndex = 0;
                }

                textIndex++;
                if (textIndex == textColors.Length)
                {
                    textIndex = 0;
                }
            }
            messages.Reverse();
            _wall.Width = new Unit(80, UnitType.Percentage);
        }
Example #8
0
		static void Main(string[] args)
		{
			var arguments = new List<string>(args);
			var input = new List<string>();

			if (Console.IsInputRedirected)
			{
				string line;
				while ((line = Console.ReadLine()) != null)
				{
					input.Add(line);
				}
			}

			if (!arguments.Any())
			{
				//PrintHelp();
				return;
			}

			var fromEnd = false;
			if (arguments.Contains("-e"))
			{
				arguments.Remove("-e");
				fromEnd = true;
			}

			int take;
			if (!int.TryParse(arguments[0], out take))
			{
				return;
			}
			arguments.RemoveAt(0);

			var tempList = new List<string>(input);

			if (fromEnd)
			{
				tempList.Reverse();
			}

			if (take < 0)
			{
				take = tempList.Count + take;
			}

			tempList =
				//take < 0 ? tempList.Skip(tempList.Count + take).ToList() :
				tempList.Take(take).ToList();

			if (fromEnd)
			{
				tempList.Reverse();
			}

			foreach (var line in tempList)
			{
				Console.WriteLine(line);
			}
		}
Example #9
0
    static void Main()
    {
        Console.Write("number: ");
        int binary = int.Parse(Console.ReadLine());
        string binaryNumber = "";

        List<int> digits = new List<int>();

        if (binary >= 0)
        {
            while (binary != 0)
            {
                digits.Add(binary % 2);
                binary /= 2;
            }

            digits.Reverse();

            for (int i = 0; i < digits.Count; i++)
            {
                binaryNumber += digits[i];
            }

            while (binaryNumber.Length % 16 != 0)
            {
                binaryNumber = "0" + binaryNumber;
            }
        }
        else
        {
            binary = Math.Abs(binary) - 1;

            while (binary != 0)
            {
                digits.Add(binary % 2);
                binary /= 2;
            }

            digits.Reverse();

            for (int i = 0; i < digits.Count; i++)
            {
                if (digits[i] == 0)
                {
                    binaryNumber += "1";
                }
                else
                {
                    binaryNumber += "0";
                }
            }

            while (binaryNumber.Length % 16 != 0)
            {
                binaryNumber = "1" + binaryNumber;
            }
        }
        Console.Write("Result: ");
        Console.WriteLine(binaryNumber);
    }
Example #10
0
        public override void Setup (GraphicsDevice device)
        {
            _thickPen = new Pen(Color.Green, 15);

            List<Vector2> path1 = new List<Vector2>() {
                new Vector2(50, 50), new Vector2(100, 50), new Vector2(100, 100), new Vector2(50, 100),
            };

            _gpathf = new GraphicsPath(_thickPen, path1, PathType.Closed);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new Vector2(path1[i].X + 100, path1[i].Y);

            _gpathr = new GraphicsPath(_thickPen, path1, PathType.Closed);

            for (int i = 0; i < path1.Count; i++)
                path1[i] = new Vector2(path1[i].X, path1[i].Y + 100);

            _gpath2r = new GraphicsPath(_thickPen, path1);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new Vector2(path1[i].X - 100, path1[i].Y);

            _gpath2f = new GraphicsPath(_thickPen, path1);
        }
        public GraphicsPathTest()
        {
            _thickPen = new Pen(Microsoft.Xna.Framework.Color.Green, 15);

            List<CCVector2> path1 = new List<CCVector2>() {
                new CCVector2(50, 50), new CCVector2(100, 50), new CCVector2(100, 100), new CCVector2(50, 100),
            };

            _gpathf = new GraphicsPath(_thickPen, path1, PathType.Closed);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X + 100, path1[i].Y);

            _gpathr = new GraphicsPath(_thickPen, path1, PathType.Closed);

            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X, path1[i].Y + 100);

            _gpath2r = new GraphicsPath(_thickPen, path1);

            path1.Reverse();
            for (int i = 0; i < path1.Count; i++)
                path1[i] = new CCVector2(path1[i].X - 100, path1[i].Y);

            _gpath2f = new GraphicsPath(_thickPen, path1);
        }
        static void Main(string[] args)
        {
            Console.Write("Enter 16-bit signed number: ");
            int number = int.Parse(Console.ReadLine());

            List<int> digits = new List<int>();

            if (number >= 0)
            {
                while (number != 0)
                {
                    digits.Add(number % 2);
                    number /= 2;
                }

                while (digits.Count % 16 != 0)
                {
                    digits.Add(0);
                }
                digits.Reverse();
            }
            else
            {
                number = Math.Abs(number) - 1;

                while (number != 0)
                {
                    digits.Add(number % 2);
                    number /= 2;
                }

                List<int> negativeNumber = new List<int>();
                for (int i = 0; i < digits.Count; i++)
                {
                    if (digits[i] == 0)
                    {
                        negativeNumber.Add(1);
                    }
                    else
                    {
                        negativeNumber.Add(0);
                    }
                }
                digits = negativeNumber;

                while (digits.Count % 16 != 0)
                {
                    digits.Add(1);
                }
                digits.Reverse();
            }
            Console.Write("Binary representation: ");
            foreach (var item in digits)
            {
                Console.Write(item);
            }
            Console.WriteLine();
        }
Example #13
0
        static void Main()
        {
            int number = int.Parse(Console.ReadLine());
            List<int> binNumber = new List<int>();
            StringBuilder binary = new StringBuilder();
            if (number > 0)
            {

                while (number > 0)
                {
                    binNumber.Add(number % 2);
                    number /= 2;
                }
                while (binNumber.Count % 16 != 0)
                {
                    binNumber.Add(0);
                }
                binNumber.Reverse();

                for (int i = 0; i < binNumber.Count; i++)
                {
                    binary.Append(binNumber[i]);
                }

                Console.WriteLine(binary);
            }
            else
            {

                number = Math.Abs(number) - 1;
                while(number>0)
                {
                    binNumber.Add(number % 2);
                    number /= 2;
                }
                while (binNumber.Count % 16 != 0)
                {
                    binNumber.Add(0);
                }
                binNumber.Reverse();
                for (int i = 0; i < binNumber.Count; i++)
                {
                    if (binNumber[i] == 0)
                    {
                        binary.Append(1);
                    }
                    else
                    {
                        binary.Append(0);
                    }
                }
                Console.WriteLine(binary);

            }
        }
Example #14
0
    protected void handleDone(List<FmriRequest> reqList, Table dest, string status, Color bg, Color fg)
    {
        reqList.Reverse();
        foreach (FmriRequest req in reqList)
        {
            TableRow r = new TableRow();
            r.Height = 40;

            TableCell c;

            c = new TableCell();
            c.Text = status;
            c.BackColor = bg;
            c.ForeColor = fg;
            r.Cells.Add(c);

            AddCells(r.Cells, req);

            c = new TableCell();
            c.Text = Convert.ToString(req.TimeExecuted);
            r.Cells.Add(c);

            c = new TableCell();
            if (req.Result.Contains("Out of memory"))
            {
                req.Result = "Out of memory.";
            }
            if (req.Result.Trim() != "OK")
            {
                c.ForeColor = Color.Red;
            }
            c.Text = req.Result;
            r.Cells.Add(c);

            if (req.Result.Trim() == "OK")
            {
                c = new TableCell();
                c.Text = "<a href=\"Results.aspx?id=" + req.AreaStringWithThresholdMD5 + "&id2=" + req.AreaStringMD5 + "\" class=\"small orange awesome\">Results</a>";
                r.Cells.Add(c);

                c = new TableCell();
                c.Text = "<a href=\"Excel/" + req.AreaStringMD5 + ".csv\"\" class=\"small awesome\">Excel</a>&nbsp;&nbsp;<a href=\"Excel/" + req.AreaStringMD5 + ".zip\"\" class=\"small awesome\">Zipped</a>";
                r.Cells.Add(c);

                c = new TableCell();
                c.Text = "<a href=\"Cliques/" + req.AreaStringWithThresholdMD5 + ".txt\"\" class=\"small awesome\">Cliques</a>";
                r.Cells.Add(c);
            }

            dest.Rows.Add(r);
        }
        reqList.Reverse();
    }
Example #15
0
    public static void ConvertFromDec(int number, int baseTo)
    {
        List<int> result = new List<int>();
        if (baseTo > 10)
        {
            while (number > 0)
            {
                result.Add(number % baseTo);
                number = number / baseTo;
            }

            result.Reverse();
            foreach (var item in result)
            {
                switch (item)
                {
                    case 10: Console.Write("A");
                        break;
                    case 11: Console.Write("B");
                        break;
                    case 12: Console.Write("C");
                        break;
                    case 13: Console.Write("D");
                        break;
                    case 14: Console.Write("E");
                        break;
                    case 15: Console.Write("F");
                        break;
                    default: Console.Write(item);
                        break;
                }
            }

            Console.WriteLine();
        }
        else
        {
            while (number > 0)
            {
                result.Add(number % baseTo);
                number = number / baseTo;
            }

            result.Reverse();
            foreach (var item in result)
            {
                Console.Write(item);
            }

            Console.WriteLine();
        }
    }
Example #16
0
        public static void putKeyWordInCache(string keyword,string section)
        {

            if (File.Exists(filePath.KEYWORDFILEPATH))
            {

                StringBuilder temp = new StringBuilder(KEYWORDLENGTH);
                int re = GetPrivateProfileString(section, "history", "", temp, KEYWORDLENGTH, filePath.KEYWORDFILEPATH);
                string t = temp.ToString();
                
                char[] chSplit = ",".ToCharArray();
                string[] key = t.Split(chSplit);
                
                List<string> keyList = new List<string>(key);

                if (keyList.Contains(keyword))
                {
                    if (keyword != keyList[0])
                    {                      
                        keyList.Remove(keyword);
                        keyList.Reverse();
                        keyList.Add(keyword);
                        keyList.Reverse();
                    }
                }
                else
                {
                    if (keyList.Count() == CACHESIZE)
                    {
                        keyList.Remove(keyList[CACHESIZE - 1]);
                    }
                    keyList.Reverse();
                    keyList.Add(keyword);
                    keyList.Reverse();
                }

                string value = null;
                foreach (string s in keyList)
                {
                    if (keyList.Last() != s)
                        value += s + ",";
                    else
                        value += s;
                }

                WritePrivateProfileString(section, "history", value, filePath.KEYWORDFILEPATH);

            }
        }
Example #17
0
 private void exploreXafErrors_Execute(ExecuteEventArgs ea) {
     Project startUpProject = CodeRush.ApplicationObject.Solution.FindStartUpProject();
     Property outPut = startUpProject.ConfigurationManager.ActiveConfiguration.FindProperty(ConfigurationProperty.OutputPath);
     bool isWeb = IsWeb(startUpProject);
     string fullPath = startUpProject.FindProperty(ProjectProperty.FullPath).Value + "";
     string path = Path.Combine(fullPath, outPut.Value.ToString()) + "";
     if (isWeb)
         path = Path.GetDirectoryName(startUpProject.FullName);
     Func<Stream> streamSource = () => {
         var path1 = path + "";
         File.Copy(Path.Combine(path1, "expressAppFrameWork.log"), Path.Combine(path1, "expressAppFrameWork.locked"), true);
         return File.Open(Path.Combine(path1, "expressAppFrameWork.locked"), FileMode.Open, FileAccess.Read, FileShare.Read);
     };
     var reader = new ReverseLineReader(streamSource);
     var stackTrace = new List<string>();
     foreach (var readline in reader) {
         stackTrace.Add(readline);
         if (readline.Trim().StartsWith("The error occured:") || readline.Trim().StartsWith("The error occurred:")) {
             stackTrace.Reverse();
             string errorMessage = "";
             foreach (string trace in stackTrace) {
                 errorMessage += trace + Environment.NewLine;
                 if (trace.Trim().StartsWith("----------------------------------------------------"))
                     break;
             }
             Clipboard.SetText(errorMessage);
             break;
         }
     }
 }
Example #18
0
        public static List<List<int>> GetYarns(int finalSequenceLength, int yarnLength, bool reverse)
        {
            if ((finalSequenceLength - yarnLength) % ( yarnLength -1)  != 0)
            {
                throw new ArgumentException("finalSequenceLength and yarnLength are incompatible");
            }

            var yarnCount = finalSequenceLength / yarnLength;

            var yarns = new List<List<int>>();
            int start = 1;

            int loops = 1 + (finalSequenceLength - yarnLength) / (yarnLength - 1);

            for (int i = 0; i < loops; i++)
            {
                var yarn = Enumerable.Range(start, yarnLength);
                yarns.Add(yarn.ToList());
                start += yarnLength - 1;
            }

            if (reverse)
            {
                yarns.Reverse();
            }

            return yarns;
        }
Example #19
0
    public override void LoadWidget()
    {
        StringDictionary settings = GetSettings();
        int numberOfComments = DEFAULT_NUMBER_OF_COMMENTS;
        if (settings.ContainsKey("numberofcomments"))
            numberOfComments = int.Parse(settings["numberofcomments"]);

        if (HttpRuntime.Cache["widget_recentcomments"] == null)
        {
            List<Comment> comments = new List<Comment>();

            foreach (Post post in Post.Posts)
            {
                if (post.IsVisible)
                {
                    comments.AddRange(post.Comments.FindAll(delegate(Comment c) { return c.IsApproved && c.Email.Contains("@"); }));
                }
            }

            comments.Sort();
            comments.Reverse();

            int max = Math.Min(comments.Count, numberOfComments);
            List<Comment> list = comments.GetRange(0, max);
            HttpRuntime.Cache.Insert("widget_recentcomments", list);
        }

        string content = RenderComments((List<Comment>)HttpRuntime.Cache["widget_recentcomments"], settings);

        LiteralControl html = new LiteralControl(content); //new LiteralControl((string)HttpRuntime.Cache["widget_recentcomments"]);
        phPosts.Controls.Add(html);
    }
Example #20
0
 void OnEnable()
 {
     // TODO: optimize, to avoid sorting all objects each validation
     // sort ascending by drop chance, for easier loot spawning
     lootTable?.Sort((x, y) => y.dropChance.CompareTo(x.dropChance));
     lootTable?.Reverse();
 }
Example #21
0
    static void Main(string[] args)
    {
        Console.Write("Write a decimal number to convert to hex: ");
        int num = int.Parse(Console.ReadLine());
        int remainder;

        List<int> hexNumber = new List<int>();

        do
        {
            remainder = num % 16;
            hexNumber.Add(remainder);
            num = num / 16;
        } while (num != 0);

        hexNumber.Reverse();

        Console.Write("\nThe hex representation of the number you entered is: ");
        for (int i = 0; i < hexNumber.Count; i++)
        {
            if (hexNumber[i] > 9)
            {
                Console.Write("{0} ", (char)(hexNumber[i]+55)); // you look at the ASCII table you will see that from 65 -> the symbols are "A,B,C...."
            }
            else
            Console.Write("{0} ", hexNumber[i]);
        }
        Console.WriteLine("\n");
    }
Example #22
0
        public Position GetNextPosition(Position playerPosition)
        {
            _positions = Waypoints.ToList();

            if (_position == _positions.Count)
            {
                if (StraightRoute)
                {
                    Waypoints = new ObservableCollection<Position>(Waypoints.Reverse());
                    _positions.Reverse();
                }
                _position = 0;
            }

            var distance = Distance(playerPosition, _positions[_position]);

            if (distance > 15)
            {
                var closest = _positions.OrderBy(x => Distance(playerPosition, x)).FirstOrDefault();
                _position = _positions.IndexOf(closest);
            }

            var newPosition = _positions[_position];

            _position++;

            return newPosition;
        }
        public string GetTitle()
        {
            string title = "";

            if (ParentFrame == null)
            {
                title = "DefaultContent";
            }
            else
            {
                List<string> frameTitles = new List<string>();
                var frame = this;
                while (frame.ParentFrame != null)
                {
                    string frameTitle = !String.IsNullOrEmpty(frame.LocatorNameOrId)
                                        ? frame.LocatorNameOrId
                                        : frame.Index.ToString();
                    frameTitles.Add(frameTitle);
                    frame = frame.ParentFrame;
                }

                frameTitles.Reverse();

                title = String.Join(".", frameTitles);
            }

            return title;
        }
        public override void Start()
        {
            if (_actuator.Actuators.Count < 2)
            {
                return;
            }

            Frames.Clear();

            var orderedActuators = new List<IStateMachine>(_actuator.Actuators);
            if (!_isForward)
            {
                orderedActuators.Reverse();
            }

            double frameLength = _duration.TotalMilliseconds/(orderedActuators.Count - 1);

            for (int i = 0; i < orderedActuators.Count; i++)
            {
                var actuator = orderedActuators[i];
                var offset = TimeSpan.FromMilliseconds(frameLength * i);

                WithFrame(new Frame().WithTargetState(actuator, _targetState).WithStartTime(offset));
            }

            var lastFrame = new Frame().WithStartTime(_duration);
            foreach (var actuator in _actuator.Actuators)
            {
                lastFrame.WithTargetState(actuator, _targetState);
            }

            WithFrame(lastFrame);
            base.Start();
        }
        public PathViewModel(RepositoryNavigationRequest request, AbstractTreeNode node)
        {
            Elements = new List<Element>();

            CurrentItem = new Element(
                new RepositoryNavigationRequest(request) { Path = node.Path },
                request.Treeish,
                node);

            var currentNode = node;

            while (currentNode.Parent != null)
            {
                currentNode = currentNode.Parent;
                if (currentNode.Parent != null)
                {
                    Elements.Add(
                        new Element(new RepositoryNavigationRequest(request) { Path = currentNode.Path },
                        request.Treeish,
                        currentNode));
                }
            }

            Elements = new List<Element>(Elements.Reverse());
            Root = new Element(request, request.Treeish, currentNode);
            IsRootEqualToCurrentItem = (currentNode == node);
        }
 static void Main(string[] args)
 {
     using (StreamReader reader = File.OpenText(args[0]))
         while (!reader.EndOfStream)
         {
             string line = reader.ReadLine();
             if (null == line)
                 continue;
             string[] Timestamps = line.Trim().Split(' ');
             Dictionary<int, string> output = new Dictionary<int, string>();
             List<int> timediff = new List<int>();
             foreach(string item in Timestamps)
             {
                 string[] hhmmss = item.Split(':');
                 int time = Convert.ToInt32(hhmmss[0]) * 3600 + Convert.ToInt32(hhmmss[1]) * 60 + Convert.ToInt32(hhmmss[2]);
                 output.Add(time,item);
                 timediff.Add(time);
             }
             timediff.Sort();
             timediff.Reverse();
             foreach(var item in timediff)
             {
                 Console.Write(output[item]+' ');
             }
             Console.WriteLine();
         }
 }
Example #27
0
        /* Patter for combinations (from largest to smallest)
        10 * 10
        10 * 9
        9 * 9
        10 * 8
        9 * 8
        10 * 7
        8 * 8
        9 * 7

        8 * 7
        7 * 7
        7 * 6
        */
        static void Main(string[] args)
        {
            int result = 0;
            int min = 800; // Speed things up... don't test all the numbers.
            int max = 999;
            List<int> products = new List<int>(max * max);
            for (int ii = max; ii >= min; ii--) // Only 3 digit numbers
            {
                for (int jj = ii; jj > min; jj--)
                {
                    int product = ii * jj;
                    if (!products.Contains(product))
                    {
                        products.Add(product);
                    }
                }
            }

            products.Sort();
            products.Reverse();

            foreach( int product in products)
            {
                if (is_palindrom(product))
                {
                    result = product;
                    break;
                }
            }

            Console.WriteLine(result);
            Console.WriteLine("Press ENTER to Exit");
            Console.ReadLine();
        }
        public List <CodeSnippet> Get()
        {
            List <CodeSnippet> codeSnippetList = codeSnippets.Find(codeSnippet => true).ToList();

            codeSnippetList?.Reverse();
            return(codeSnippetList);
        }
Example #29
0
        private List <MethodInfo>?GetMethodsWithAttribute(
            Type attribute,
            // currently the only way to preserve base, non-public methods is to use All
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type?t)
        {
            List <MethodInfo>?mi = null;

            // Traverse the hierarchy to find all methods with the particular attribute
            Type?baseType = t;

            while (baseType != null && baseType != typeof(object))
            {
                // Get all methods which are declared on this type, instance and public or nonpublic
                MethodInfo[] mis = baseType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
                foreach (MethodInfo m in mis)
                {
                    // For each method find if attribute is present, the return type is void and the method is not virtual
                    if (m.IsDefined(attribute, false))
                    {
                        mi ??= new List <MethodInfo>();
                        mi.Add(m);
                    }
                }
                baseType = baseType.BaseType;
            }
            mi?.Reverse(); // We should invoke the methods starting from base

            return(mi);
        }
Example #30
0
        public static IEnumerable<Page> Breadcrumb()
        {
            List<Page> breadcrumbPages = new List<Page>();
            var defaultPage = ServiceFactory.PageManager.GetDefaultPage(Page_Context.Current.PageRequestContext.Page.Site);
            if (defaultPage == Page_Context.Current.PageRequestContext.Page)
            {
                return breadcrumbPages;
            }
            var currentPage = Page_Context.Current.PageRequestContext.Page.Parent;
            while (currentPage != null)
            {
                currentPage = currentPage.LastVersion(Page_Context.Current.PageRequestContext.Site).AsActual();

                if (currentPage.Navigation != null
                    && currentPage.Navigation.ShowInCrumb.Value == true && currentPage.Published.HasValue && currentPage.Published.Value == true)
                {
                    breadcrumbPages.Add(currentPage);
                }

                currentPage = currentPage.Parent;
            }
            if (breadcrumbPages.LastOrDefault() != defaultPage)
            {
                defaultPage = defaultPage.AsActual();

                if (defaultPage.Navigation != null
                && defaultPage.Navigation.ShowInCrumb.Value == true && defaultPage.Published.HasValue && defaultPage.Published.Value == true)
                {
                    breadcrumbPages.Add(defaultPage);
                }
            }

            breadcrumbPages.Reverse();
            return breadcrumbPages;
        }
Example #31
0
        public static List<string> PathToDirectoryList(string path)
        {
            var namestack = new List<string>();

            if (path == Path.GetPathRoot(path))
            {
                namestack.Add(path);
                return namestack;
            }

            while (true)
            {
                var currentlevel = Path.GetFileName(path) ?? string.Empty;
                if (currentlevel.Length > 0)
                {
                    path = path.Remove(path.Length - currentlevel.Length);
                }
                namestack.Add(currentlevel);
                if (path == Path.GetPathRoot(path))
                {
                    namestack.Add(path);
                    break;
                }
                path = path.TrimEnd('\\');
            }
            namestack.Reverse();
            return namestack;
        }
 /// <summary>
 ///     Formats the given parameters to call a function.
 /// </summary>
 /// <param name="parameters">An array of parameters.</param>
 /// <returns>The mnemonics to pass the parameters.</returns>
 public string FormatParameters(IntPtr[] parameters)
 {
     // Declare a var to store the mnemonics
     var ret = new StringBuilder();
     var paramList = new List<IntPtr>(parameters);
     // Store the first parameter in the ECX register
     if (paramList.Count > 0)
     {
         ret.AppendLine("mov ecx, " + paramList[0]);
         paramList.RemoveAt(0);
     }
     // Store the second parameter in the EDX register
     if (paramList.Count > 0)
     {
         ret.AppendLine("mov edx, " + paramList[0]);
         paramList.RemoveAt(0);
     }
     // For each parameters (in reverse order)
     paramList.Reverse();
     foreach (var parameter in paramList)
     {
         ret.AppendLine("push " + parameter);
     }
     // Return the mnemonics
     return ret.ToString();
 }
                private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node)
                {
                    var path = new List<int>();
                    var root = _tree.GetRoot();

                    while (node != root)
                    {
                        for (; node.Parent != null; node = node.Parent)
                        {
                            var index = GetChildIndex(node);
                            path.Add(index);
                        }

                        // if we were part of structure trivia, continue searching until we get to the true root
                        if (node.IsStructuredTrivia)
                        {
                            var trivia = node.ParentTrivia;
                            var triviaIndex = GetTriviaIndex(trivia);
                            path.Add(triviaIndex);
                            var tokenIndex = GetChildIndex(trivia.Token);
                            path.Add(tokenIndex);
                            node = trivia.Token.Parent;
                            continue;
                        }
                        else if (node != root)
                        {
                            throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root);
                        }
                    }

                    path.Reverse();
                    return path.ToImmutableArray();
                }
Example #34
0
        private void DoPath(Map map, Unit unit, Vec2Double target)
        {
            var pathF = new PathFinderFast(map.MGrid, map);

            _path = pathF.FindPath(new Vector2I((int)unit.Position.X, (int)unit.Position.Y), new Vector2I((int)target.X, (int)target.Y), 1, 2, 5, 10);
            _path?.Reverse();
            _i          = 0;
            _pathLength = 0;
        }
Example #35
0
        public static void SimulateModifiedKeyStroke(IEnumerable <VirtualKeyCode> modifierKeyCodes,
                                                     VirtualKeyCode keyCode)
        {
            List <VirtualKeyCode> modifierKeyCodesList = modifierKeyCodes?.ToList();

            modifierKeyCodesList?.ForEach(SimulateKeyDown);
            SimulateKeyPress(keyCode);
            modifierKeyCodesList?.Reverse <VirtualKeyCode>().ToList().ForEach(SimulateKeyUp);
        }
Example #36
0
    internal override void OnValidate()
    {
        base.OnValidate();

        sprite = AssetHandler.LoadNearbyAssetWithSameName <Sprite>(this);
        // TODO: optimize, to avoid sorting all objects each validation
        // sort ascending by drop chance, for easier loot spawning
        lootTable?.Sort((x, y) => y.dropChance.CompareTo(x.dropChance));
        lootTable?.Reverse();
    }
Example #37
0
        public ActionResult Dialog(string receiverUser, int?id = 0)
        {
            if (id < 0)
            {
                id = 0;
            }
            int page = id ?? 0;

            if (receiverUser.ToLower() == User.Identity.Name.ToLower() || !context.Users.Any(u => u.UserName == receiverUser))
            {
                return(RedirectToAction("Index"));
            }
            var sender = context.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

            if (!sender.Contacts.Any(u => u.UserName == receiverUser) || !sender.Contacts2.Any(u => u.UserName == receiverUser))
            {
                return(RedirectToAction("Index"));
            }
            ViewBag.interlocutor = receiverUser;
            history = new List <MessageViewModel>();
            var receiver = context.Users.FirstOrDefault(x => x.UserName == receiverUser);
            var room     = context.ChatRooms.FirstOrDefault(r => r.Companions.Any(u => u.UserName == sender.UserName) && r.Companions.Any(u => u.UserName == receiver.UserName));

            if (room == null)
            {
                history = null;
            }
            else
            {
                var itemToSkip = page * pageSize;
                var messages   = context.Messages.Where(a => a.ChatRoomId == room.ChatRoomId).OrderByDescending(m => m.MessageId).Skip(itemToSkip).Take(pageSize).ToList();
                foreach (var mess in messages)
                {
                    //var attachment = context.Attachments.Where(a => a.AttachmentId == mess.AttachmentId).FirstOrDefault();
                    history.Add(new MessageViewModel()
                    {
                        From   = mess.ApplicationUser.UserName,
                        Date   = mess.SentTime,
                        Text   = mess.Text,
                        IsRead = mess.IsRead
                    });
                    if (!mess.IsRead && mess.ApplicationUser.UserName != User.Identity.Name)
                    {
                        context.Messages.First(m => mess.MessageId == m.MessageId).IsRead = true;
                    }
                }
                context.SaveChanges();
            }
            history?.Reverse();
            if (Request.IsAjaxRequest())
            {
                return(PartialView("_Messages", history));
            }
            return(PartialView(history));
        }
Example #38
0
        public async Task GetMessages()
        {
            IsLoading = true;

            HttpContent resContent = await MainWindowViewModel.ServerService.GetMessages(_channelId);

            IsLoading = false;

            if (resContent == null)
            {
                return;
            }

            List <Message> messages = await resContent.ReadAsAsync(typeof(List <Message>)) as List <Message>;

            messages?.Reverse();

            //DisplayMessages(ConvertMessagesTimestamps(messages));
        }
Example #39
0
        /// <summary>
        /// internal function to reconstruct the plan by tracing from last node to initial node
        /// </summary>
        /// <returns>The plan.</returns>
        private static Stack <GOAPAction> ReconstructPlan(GOAPNode goalNode, List <GOAPNode> selectedNodes)
        {
            var totalActionsInPlan = goalNode.Depth - 1;
            var plan = new Stack <GOAPAction>(totalActionsInPlan);

            var curnode = goalNode;

            for (var i = 0; i <= totalActionsInPlan - 1; i++)
            {
                // optionally add the node to the List if we have been passed one
                selectedNodes?.Add(curnode.Clone());
                plan.Push(curnode.Action);
                curnode = curnode.Parent;
            }

            // our nodes went from the goal back to the start so reverse them
            selectedNodes?.Reverse();

            return(plan);
        }
        public List <bool> GetCode(Node nodeWord)
        {
            List <bool> code     = new List <bool>();
            Node        node     = nodeWord;
            Node        prevNode = nodeWord;

            while (node != Root)
            {
                node = node.Parent;
                if (node?.Right == prevNode)
                {
                    code.Add(true);
                }
                if (node?.Left == prevNode)
                {
                    code.Add(false);
                }
                prevNode = node;
            }
            code?.Reverse();
            return(code);
        }
Example #41
0
        public List <bool> GetCode(NodeHT nodeLeaf)
        {
            List <bool> code     = new List <bool>();
            NodeHT      node     = nodeLeaf;
            NodeHT      nodePrev = node;

            while (node != Root)
            {
                node = node.Parent;
                if (node?.Right == nodePrev)
                {
                    code.Add(true);
                }
                if (node?.Left == nodePrev)
                {
                    code.Add(false);
                }
                nodePrev = node;
            }
            code?.Reverse();
            return(code);
        }
Example #42
0
 private void BackShiftPosition()
 {
     heroes.Reverse();
     FrontShiftPosition();
     heroes.Reverse();
 }
Example #43
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Fill in the children for a particular book. This is typically done when it gets
        /// expanded or when we need a list including the children. Separating it from the
        /// initial load saves a lot of time when we have a long list of books.
        /// </summary>
        /// <param name="bookNode">The book node.</param>
        /// <returns><c>true</c> if the dummy node was replaced by real child node(s)</returns>
        /// <remarks>protected virtual for unit tests</remarks>
        /// ------------------------------------------------------------------------------------
        protected virtual bool FillInBookChildren(TreeNode bookNode)
        {
            var book       = bookNode.Tag as IScrBook;
            var bookNum    = book?.CanonicalNum ?? (int)bookNode.Tag;
            var owningForm = FindForm();

            while (owningForm != null && !owningForm.Visible)
            {
                owningForm = owningForm.Owner;
            }
            if (owningForm == null)
            {
                owningForm = Form.ActiveForm ?? Application.OpenForms[0];
            }

            if (m_associatedPtText != null)
            {
                // Update main text, if possible/needed.
                if (m_associatedPtText.BookPresent(bookNum))
                {
                    // PT has it.
                    // If we don't have it, OR if our copy is stale, then get updated copy.
                    if (book == null || !m_associatedPtText.IsCheckSumCurrent(bookNum, book.ImportedCheckSum))
                    {
                        // Get new/fresh version from PT.
                        var importedBook = ImportBook(owningForm, bookNum);
                        if (importedBook != null)
                        {
                            book         = importedBook;
                            bookNode.Tag = importedBook;
                        }
                    }
                }
                if (book == null)
                {
                    // No book, so don't fret about a back translation
                    return(false);
                }

                // Update back translation
                IScrText btProject = ParatextHelper.GetBtsForProject(m_associatedPtText).FirstOrDefault();
                if (btProject != null && btProject.BookPresent(book.CanonicalNum) && !btProject.IsCheckSumCurrent(book.CanonicalNum, book.ImportedBtCheckSum.get_String(book.Cache.DefaultAnalWs).Text))
                {
                    // The BT for this book node is out-of-date with the Paratext BT data
                    ImportBackTranslation(owningForm, bookNum, btProject);
                }
            }

            bookNode.Nodes.Clear();             // Gets rid of dummy.
            // Add Title node.
            if (book.TitleOA != null)
            {
                var titleNode = new TreeNode(ResourceHelper.GetResourceString("kstidScriptureTitle"))
                {
                    Name = book.TitleOA.ToString(),
                    Tag  = book.TitleOA
                };
                bookNode.Nodes.Add(titleNode);
            }

            // Add Sections.
            foreach (var section in book.SectionsOS)
            {
                var chapterVerseBridge = m_scr.ChapterVerseBridgeAsString(section);
                // Include the heading text if it's not empty.  See LT-8764.
                var cTotal = section.HeadingOA?.ParagraphsOS.Cast <IScrTxtPara>().Sum(para => para.Contents.Length);
                if (cTotal > 0)
                {
                    var sFmt = ResourceHelper.GetResourceString("kstidSectionHeading");
                    var node = new TreeNode(string.Format(sFmt, chapterVerseBridge))
                    {
                        Name = string.Format(sFmt, section),
                        Tag  = section.HeadingOA                        // expect an StText
                    };
                    bookNode.Nodes.Add(node);
                }
                var sectionNode = new TreeNode(chapterVerseBridge)
                {
                    Name = section.ToString(),
                    Tag  = section.ContentOA                    // expect an StText
                };
                bookNode.Nodes.Add(sectionNode);
            }

            // Add Footnotes in reverse order, so we can insert them in the proper order.
            var footnotes = new List <IScrFootnote>(book.FootnotesOS);

            footnotes.Reverse();
            foreach (var scrFootnote in footnotes)
            {
                // insert under the relevant section, if any (LTB-408)
                IScrSection containingSection;
                IStText     containingTitle = null;
                if (!scrFootnote.TryGetContainingSection(out containingSection) && !scrFootnote.TryGetContainingTitle(out containingTitle))
                {
                    continue;
                }
                var nodeName     = m_scr.ContainingRefAsString(scrFootnote);
                var footnoteNode = new TreeNode(nodeName)
                {
                    Tag  = scrFootnote,
                    Name = "Footnote"
                };

                // see if we can lookup the node of this section.
                var nodeIndex = bookNode.Nodes.IndexOfKey(containingSection?.ToString() ?? containingTitle.ToString());
                if (nodeIndex >= 0)
                {
                    bookNode.Nodes.Insert(nodeIndex + 1, footnoteNode);
                }
                else
                {
                    bookNode.Nodes.Add(footnoteNode);                           // insert at end.
                }
            }
            return(true);
        }
Example #44
0
File: 2.cs Project: qifanyyy/CLCDSA
        private _ANSWER solve(string s, string t)
        {
            var ans = new Triplet <long, long, long>(long.MaxValue, long.MaxValue, long.MaxValue);

            //0: s>t
            //1: s=t
            //1: t<s
            var dp = Enumerate(3, x => new Triplet <long, long, long>(long.MaxValue, 0, 0));

            dp[1].I = 0;
            for (int i = 0; i < s.Length; i++)
            {
                var next = Enumerate(3, x => new Triplet <long, long, long>(long.MaxValue, 0, 0));

                for (int u = 0; u < 10; u++)
                {
                    if (s[i] != u + '0' && s[i] != '?')
                    {
                        continue;
                    }
                    for (int v = 0; v < 10; v++)
                    {
                        if (t[i] != v + '0' && t[i] != '?')
                        {
                            continue;
                        }
                        if (u < v)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                long d;
                                int  to;
                                Triplet <long, long, long> neq;
                                if (k == 0)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 - Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 0;
                                }
                                else if (k == 1)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 2;
                                }
                                else
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 + Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 2;
                                }
                                next[to] = Triplet.Min(next[to], neq);
                            }
                        }
                        else if (u == v)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                long d;
                                int  to;
                                Triplet <long, long, long> neq;
                                if (k == 0)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 - Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 0;
                                }
                                else if (k == 1)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 1;
                                }
                                else
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 + Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 2;
                                }
                                next[to] = Triplet.Min(next[to], neq);
                            }
                        }
                        else
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                long d;
                                int  to;
                                Triplet <long, long, long> neq;
                                if (k == 0)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 + Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 0;
                                }
                                else if (k == 1)
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 0;
                                }
                                else
                                {
                                    if (dp[k].I == long.MaxValue)
                                    {
                                        continue;
                                    }
                                    d   = dp[k].I * 10 - Math.Abs(v - u);
                                    neq = new Triplet <long, long, long>(d, dp[k].J * 10 + u, dp[k].K * 10 + v);
                                    to  = 2;
                                }
                                next[to] = Triplet.Min(next[to], neq);
                            }
                        }
                    }
                }
                dp = next;
            }
            for (int i = 0; i < 3; i++)
            {
                ans = Triplet.Min(ans, dp[i]);
            }
            var a = new List <long>();
            var b = new List <long>();

            for (int i = 0; i < s.Length; i++)
            {
                a.Add(ans.J % 10);
                b.Add(ans.K % 10);
                ans.J /= 10;
                ans.K /= 10;
            }
            a.Reverse(); b.Reverse();
            return(new _ANSWER(ans.I, a.AsJoinedString(""), b.AsJoinedString("")));
        }
Example #45
0
        public virtual void AddMessage(MessageModel msg)
        {
            // OPT: typical message length
            var line      = new StringBuilder(512);
            int msgLength = 0;

            switch (msg.MessageType)
            {
            case MessageType.Normal:
                HasMessage = true;
                break;

            case MessageType.Event:
                HasEvent = true;
                break;
            }
            bool hasHighlight = false;

            foreach (MessagePartModel msgPart in msg.MessageParts)
            {
                if (msgPart.IsHighlight)
                {
                    HasHighlight = true;
                }
                // TODO: implement other types
                if (msgPart is UrlMessagePartModel)
                {
                    var urlPart    = (UrlMessagePartModel)msgPart;
                    var escapedUrl = StflApi.EscapeRichText(urlPart.Url);
                    line.Append(String.Format("<url>{0}</url>", escapedUrl));
                    msgLength += urlPart.Url.Length;
                }
                else if (msgPart is TextMessagePartModel)
                {
                    var txtPart = (TextMessagePartModel)msgPart;
                    if (String.IsNullOrEmpty(txtPart.Text))
                    {
                        continue;
                    }

                    var tags = new List <string>();
                    if (txtPart.ForegroundColor != TextColor.None)
                    {
                        var palette               = TextColorPalettes.LinuxConsole;
                        var foregroundColor       = txtPart.ForegroundColor;
                        var backgroundColorString = (string)Frontend.FrontendConfig[Frontend.UIName + "/Interface/TerminalBackgroundColor"];
                        if (!String.IsNullOrEmpty(backgroundColorString))
                        {
                            foregroundColor = TextColorTools.GetBestTextColor(
                                foregroundColor,
                                TextColor.Parse(backgroundColorString)
                                );
                        }
                        var color = TextColorTools.GetNearestColor(
                            foregroundColor,
                            palette
                            );
                        var colorNumber = palette.IndexOf(color);
                        tags.Add(String.Format("color{0}", colorNumber));
                    }
                    // HACK: STFL doesn't support applying multiple styles at
                    // the same time and thus simply overwrites any previous
                    // style. As a workaround we only apply one style with the
                    // highest priority in this order:
                    // color >> underline >> bold >> italic
                    if (txtPart.Underline && tags.Count == 0)
                    {
                        tags.Add("u");
                    }
                    if (txtPart.Bold && tags.Count == 0)
                    {
                        tags.Add("b");
                    }
                    if (txtPart.Italic && tags.Count == 0)
                    {
                        tags.Add("i");
                    }

                    string escapedText = StflApi.EscapeRichText(txtPart.Text);
                    if (tags.Count > 0)
                    {
                        tags.Reverse();
                        string markup = escapedText;
                        foreach (string tag in tags)
                        {
                            markup = String.Format("<{0}>{1}</{2}>",
                                                   tag, markup, tag);
                        }
                        line.Append(markup);
                    }
                    else
                    {
                        line.Append(escapedText);
                    }
                    msgLength += txtPart.Text.Length;
                }
                else if (msgPart is ImageMessagePartModel)
                {
                    var    imgPart        = (ImageMessagePartModel)msgPart;
                    string escapedAltText = StflApi.EscapeRichText(imgPart.AlternativeText);
                    line.Append(escapedAltText);
                    msgLength += escapedAltText.Length;
                }
            }

            string timestamp;

            try {
                timestamp = msg.TimeStamp.ToLocalTime().ToString((string)Frontend.UserConfig["Interface/Notebook/TimestampFormat"]);
            } catch (FormatException e) {
                timestamp = "Timestamp Format ERROR: " + e.Message;
            }
            var finalMsg = String.Format("{0} {1}", timestamp, line.ToString());

            MessageTextView.AppendLine(finalMsg);

            ScrollToEnd();
        }
Example #46
0
    public void GeneratePathTo(int x, int y)
    {
        // Clear out our unit's old path.
        selectedUnit.GetComponent <Unit>().currentPath = null;

        if (UnitCanEnterTile(x, y) == false)
        {
            // We probably clicked on a mountain or something, so just quit out.
            return;
        }

        Dictionary <Node, float> dist = new Dictionary <Node, float>();
        Dictionary <Node, Node>  prev = new Dictionary <Node, Node>();

        // Setup the "Q" -- the list of nodes we haven't checked yet.
        List <Node> unvisited = new List <Node>();

        Node source = graph[
            selectedUnit.GetComponent <Unit>().tileX,
            selectedUnit.GetComponent <Unit>().tileY
                      ];

        Node target = graph[
            x,
            y
                      ];

        dist[source] = 0;
        prev[source] = null;

        // Initialize everything to have INFINITY distance, since
        // we don't know any better right now. Also, it's possible
        // that some nodes CAN'T be reached from the source,
        // which would make INFINITY a reasonable value
        foreach (Node v in graph)
        {
            if (v != source)
            {
                dist[v] = Mathf.Infinity;
                prev[v] = null;
            }

            unvisited.Add(v);
        }

        while (unvisited.Count > 0)
        {
            // "u" is going to be the unvisited node with the smallest distance.
            Node u = null;

            foreach (Node possibleU in unvisited)
            {
                if (u == null || dist[possibleU] < dist[u])
                {
                    u = possibleU;
                }
            }

            if (u == target)
            {
                break;                  // Exit the while loop!
            }

            unvisited.Remove(u);

            foreach (Node v in u.neighbours)
            {
                //float alt = dist[u] + u.DistanceTo(v);
                float alt = dist[u] + CostToEnterTile(u.x, u.y, v.x, v.y);
                if (alt < dist[v])
                {
                    dist[v] = alt;
                    prev[v] = u;
                }
            }
        }

        // If we get there, the either we found the shortest route
        // to our target, or there is no route at ALL to our target.

        if (prev[target] == null)
        {
            // No route between our target and the source
            return;
        }

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

        Node curr = target;

        // Step through the "prev" chain and add it to our path
        while (curr != null)
        {
            currentPath.Add(curr);
            curr = prev[curr];
        }

        // Right now, currentPath describes a route from out target to our source
        // So we need to invert it!

        currentPath.Reverse();

        selectedUnit.GetComponent <Unit>().currentPath = currentPath;
    }
        public void InitializeContentList()
        {
            this.ReleaseContentList();
            if (!UnityEngine.Object.op_Inequality((UnityEngine.Object) this.m_ContentController, (UnityEngine.Object)null))
            {
                return;
            }
            this.m_ContentSource = new MultiInvitationSendWindow.Content.ItemSource();
            List <FriendData> list     = new List <FriendData>((IEnumerable <FriendData>)MonoSingleton <GameManager> .Instance.Player.Friends);
            MyPhoton          instance = PunMonoSingleton <MyPhoton> .Instance;

            if (UnityEngine.Object.op_Inequality((UnityEngine.Object)instance, (UnityEngine.Object)null))
            {
                List <MyPhoton.MyPlayer> roomPlayerList = instance.GetRoomPlayerList();
                for (int index1 = 0; index1 < roomPlayerList.Count; ++index1)
                {
                    if (roomPlayerList[index1] != null && !string.IsNullOrEmpty(roomPlayerList[index1].json))
                    {
                        JSON_MyPhotonPlayerParam param = JSON_MyPhotonPlayerParam.Parse(roomPlayerList[index1].json);
                        if (param != null)
                        {
                            int index2 = list.FindIndex((Predicate <FriendData>)(prop => prop.UID == param.UID));
                            if (index2 != -1)
                            {
                                list.RemoveAt(index2);
                            }
                        }
                    }
                }
            }
            for (int index = 0; index < list.Count; ++index)
            {
                FriendData data = list[index];
                bool       flag = false;
                if (data != null)
                {
                    if (MultiInvitationSendWindow.m_Invited.FindIndex((Predicate <string>)(prop => prop == data.UID)) != -1)
                    {
                        flag = true;
                    }
                    else if (!data.MultiPush)
                    {
                        flag = true;
                    }
                    else if (TimeManager.GetUnixSec(DateTime.Now) - data.LastLogin > 86400L)
                    {
                        flag = true;
                    }
                }
                else
                {
                    flag = true;
                }
                if (flag)
                {
                    list.RemoveAt(index);
                    --index;
                }
            }
            SortUtility.StableSort <FriendData>(list, (Comparison <FriendData>)((p1, p2) => (!p1.IsFavorite ? p1.LastLogin : long.MaxValue).CompareTo(!p2.IsFavorite ? p2.LastLogin : long.MaxValue)));
            list.Reverse();
            for (int index = 0; index < list.Count; ++index)
            {
                FriendData friend = list[index];
                if (friend != null)
                {
                    MultiInvitationSendWindow.Content.ItemSource.ItemParam itemParam = new MultiInvitationSendWindow.Content.ItemSource.ItemParam(friend);
                    if (itemParam.IsValid())
                    {
                        this.m_ContentSource.Add(itemParam);
                    }
                }
            }
            this.m_ContentController.Initialize((ContentSource)this.m_ContentSource, Vector2.get_zero());
        }
Example #48
0
        /// <summary>
        /// Every 30s queries mail server for new email.
        /// When there are new emails available it first download all mail headers and publishes them to the stream.
        /// Afterwards start downloading all mail content for just downloaded mail headers.
        /// </summary>
        /// <param name="cancel"></param>
        /// <returns></returns>
        private async Task RunCheckForNewMailAsyncLoop(CancellationToken cancel)
        {
            // Create mail client.
            IMailClient client = (new TrivialMailDllFactory()).Build(_serverType);

            try
            {
                // Publish Connecting state.
                _controllerStateStream.OnNext(ControllerState.Connecting);
                client.Connect(_serverEncryption, _host);

                // Publish LoggingIn state.
                _controllerStateStream.OnNext(ControllerState.LoggingIn);
                client.Login(_user, _password);

                // Publish Connected state.
                _controllerStateStream.OnNext(ControllerState.Connected);

                // Main loop
                while (!cancel.IsCancellationRequested)
                {
                    // If disconnect or not encrypted (when should be) then reconnect.
                    if (client.IsConnected && (_serverEncryption == MailServerEncryption.Unencrypted || client.IsEncrypted))
                    {
                        // MailHeaderList contains new headers which will be published to subscribers.
                        List <MailHeaderEntity> mailHeaderEntities = new List <MailHeaderEntity>();

                        using (IMailStorage <MailHeaderEntity> storage = _mailHeaderStorageFactory())
                        {
                            // 1. Get from mail server all uids (emails).
                            // ToDo: for Imap this could be improved.
                            List <string> newUids = client.GetAllUids().ToList();

                            // 2. Distinct list of uids which are not yet stored in the database.
                            // Let's reverse and start checking with the most recent email (the latest uid).
                            newUids.Reverse();
                            List <string> uidList = new List <string>();
                            foreach (var uid in newUids)
                            {
                                if (!storage.Exists(x => x.Uid == uid))
                                {
                                    uidList.Add(uid);
                                }
                                else
                                {
                                    break;
                                }
                                // Note: if any first exists, break the loop other emails are probably downloaded.
                            }

                            if (uidList.Count > 0)
                            {
                                // 3. Download mail headers.
                                foreach (var uid in uidList)
                                {
                                    // Download message header.
                                    var header = client.GetHeadersByUid(uid);

                                    // Note: MailDll documentation states that header can be null.
                                    if (header == null)
                                    {
                                        throw new ArgumentNullException(nameof(header), $"Downloaded an empty email header ({uid}).");
                                    }

                                    var email            = new MailBuilder().CreateFromEml(header);
                                    var emailFrom        = email?.From.FirstOrDefault();
                                    var mailHeaderEntity = new MailHeaderEntity()
                                    {
                                        Uid            = uid,
                                        Date           = email?.Date ?? DateTime.MinValue,
                                        Subject        = email?.Subject,
                                        MailFromEntity = new MailFromEntity()
                                        {
                                            Address    = emailFrom?.Address,
                                            Name       = emailFrom?.Name,
                                            LocalPart  = emailFrom?.LocalPart,
                                            DomainPart = emailFrom?.DomainPart
                                        }
                                    };

                                    mailHeaderEntities.Add(mailHeaderEntity);
                                }

                                // 4. Insert all new mail headers into the storage.
                                storage.Insert(mailHeaderEntities);
                            }
                        }

                        // For all new email headers publish them to the subscribers and download the content.
                        // Note: This whole block is taken out from above using() to release storage handle asap.
                        if (mailHeaderEntities.Count > 0)
                        {
                            // 5. Publish all new mail headers to the stream.
                            mailHeaderEntities.ForEach(mailHeaderEntity => { _mailHeaderStream.OnNext(new MailHeader(mailHeaderEntity)); });

                            // 6. Start downloading content loop
                            // It's not done in above foreach loop to not to keep storage open for too long
                            // when running over slow internet connection.
                            RunDownloadContentAsyncLoop(cancel, mailHeaderEntities.Select(x => x.Uid).ToList());
                        }
                    }
                    else
                    {
                        break;
                    }

                    // Check for new email again in 30s
                    await Observable.Return(0).Delay(TimeSpan.FromSeconds(30), Scheduler.CurrentThread).ToTask(cancel);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, $"RunCheckForNewMailAsyncLoop");
            }
            finally
            {
                client?.Close();

                if (!cancel.IsCancellationRequested)
                {
                    // Publish Disconnected state.
                    _controllerStateStream.OnNext(ControllerState.Disconnected);
                }
            }
        }
Example #49
0
        public Vector3 Psyche()
        {
            updateInpt();
            List <Vector3> Targets  = location(Inpt);
            List <Vector3> Choices  = location(Inpt.getObjectsInRadius(me, stat[3]));
            List <Vector3> thoughts = new List <Vector3>();

            int[] val = new int[Choices.Count];
            int   j   = 0;

            for (int i = 0; i < val.Length; i++)
            {
                val[i] = 0;
            }
            foreach (Vector3 option in Choices)
            {
                for (int x = 0; x < Inpt.getXDim(); x++)
                {
                    for (int y = 0; y < Inpt.getYDim(); y++)
                    {
                        for (int z = 0; z < Inpt.getZDim(); z++)
                        {
                            alpha   = alpha.setXYZ(x, y, z);
                            val[j] += Logos(Inpt.getObjectAt(alpha), alpha, option);
                        }
                    }
                }
                val[j] += Logos(option, paths(option, Targets));
                j++;
            }
            List <int> temp = new List <int>();

            temp.AddRange(val);
            temp.Sort();
            temp.Reverse();
            for (int i = 0; i < val.Length; i++)
            {
                if (val[i] == temp[0])
                {
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                    thoughts.Add(Choices[i]);
                }
                try
                {
                    if (val[i] == temp[1])
                    {
                        thoughts.Add(Choices[i]);
                        thoughts.Add(Choices[i]);
                        thoughts.Add(Choices[i]);
                    }
                }
                catch { }
                try
                {
                    if (val[i] == temp[2])
                    {
                        thoughts.Add(Choices[i]);
                    }
                }
                catch { }
            }
            return(thoughts[Rand.Next(0, thoughts.Count)]);
        }
Example #50
0
        //private static readonly log4net.ILog log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try //Comment out this try/catch when debugging
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                string           year   = (string)e.Argument;
                var excelApp            = new Excel.Application();

                var    projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
                string filePath    = Path.Combine(projectPath, (string)ConfigurationManager.AppSettings["UIS Template"]);

                excelApp.Workbooks.Add(filePath);

                string        country    = ConfigurationManager.AppSettings["Country"];
                SqlConnection emisDBConn = new SqlConnection(
                    string.Format("Data Source={0};Initial Catalog={1};User id={2};Password={3};",
                                  ConfigurationManager.AppSettings["Data Source"],
                                  ConfigurationManager.AppSettings["Initial Catalog"],
                                  ConfigurationManager.AppSettings["User id"],
                                  ConfigurationManager.AppSettings["Password"]));
                emisDBConn.Open();

                // Create #StudentsTable
                SqlCommand DbDropCommand = new SqlCommand("IF OBJECT_ID('tempdb.dbo.#StudentsTable', 'U') IS NOT NULL DROP TABLE dbo.#StudentsTable;", emisDBConn);
                DbDropCommand.ExecuteNonQuery();

                SqlCommand DbCreateTableCommand
                    = new SqlCommand(@"CREATE TABLE dbo.#StudentsTable (
                                    ISCED_TOP varchar(300), 
                                    ISCED varchar(300), 
                                    SCHOOLTYPE Varchar(1000), 
                                    GENDER varchar(200), 
                                    AGE int, 
                                    REPEATER varchar(1000), 
                                    CLASS decimal, 
                                    ECE varchar(600), COUNT int)",
                                     emisDBConn);
                DbCreateTableCommand.ExecuteNonQuery();

                string StudentBaseSQL = File.ReadAllText(@Path.Combine(projectPath, "SQL", (string)ConfigurationManager.AppSettings["StudentBaseSQLPath"]));
                StudentBaseSQL = @"insert into dbo.#StudentsTable (ISCED_TOP, ISCED, SCHOOLTYPE, GENDER, AGE, REPEATER, CLASS, ECE, COUNT) " + String.Format(StudentBaseSQL, year);

                SqlCommand DbInsertCommand = new SqlCommand(StudentBaseSQL, emisDBConn);
                DbInsertCommand.ExecuteNonQuery();

                // Create #TeachersTable
                DbDropCommand = new SqlCommand("IF OBJECT_ID('tempdb.dbo.#TeacherBaseTable', 'U') IS NOT NULL DROP TABLE dbo.#TeacherBaseTable;", emisDBConn);
                DbDropCommand.ExecuteNonQuery();

                DbCreateTableCommand
                    = new SqlCommand(@"CREATE TABLE dbo.#TeacherBaseTable (
                                    ISCED varchar(300), 
                                    SCHOOLTYPE Varchar(1000), 
                                    GENDER varchar(200), 
                                    QUALIFIED varchar(10), 
                                    TRAINED varchar(10), 
                                    COUNT int)",
                                     emisDBConn);
                DbCreateTableCommand.ExecuteNonQuery();

                string TeacherBaseSQL = System.IO.File.ReadAllText(@Path.Combine(projectPath, "SQL", (string)ConfigurationManager.AppSettings["TeacherBaseSQLPath"]));
                TeacherBaseSQL = @"insert into dbo.#TeacherBaseTable (ISCED, SCHOOLTYPE, GENDER, TRAINED, QUALIFIED, COUNT) " + String.Format(TeacherBaseSQL, year);

                DbInsertCommand = new SqlCommand(TeacherBaseSQL, emisDBConn);
                DbInsertCommand.ExecuteNonQuery();

                List <Action <Excel.Application, SqlConnection, string, string> > sheets = new List <Action <Excel.Application, SqlConnection, string, string> > {
                };

                List <string> ssheets = ConfigurationManager.AppSettings["Sheets"].Replace(" ", string.Empty).Split(',').ToList();

                Dictionary <String, Action <Excel.Application, SqlConnection, string, string> > actionMap
                    = new Dictionary <String, Action <Excel.Application, SqlConnection, string, string> >()
                    {
                    { "A2", sheetA2 },
                    { "A3", sheetA3 },
                    { "A5", sheetA5 },
                    { "A6", sheetA6 },
                    { "A7", sheetA7 },
                    { "A9", sheetA9 },
                    { "A10", sheetA10 },
                    };

                foreach (String sheet in ssheets)
                {
                    sheets.Add(actionMap[sheet]);
                }

                sheets.Reverse(); // Leaves Excel open on first sheet, and progressbar will initially update faster
                for (int i = 0; i < sheets.Count; i++)
                {
                    Action <Excel.Application, SqlConnection, string, string> fun = sheets[i];
                    fun(excelApp, emisDBConn, year, country);
                    double progress = i * (100 / sheets.Count());
                    (sender as BackgroundWorker).ReportProgress((int)progress);
                }
                excelApp.Visible = true;
                excelApp.ActiveWorkbook.SaveAs("UIS_Export.xlsx");
                e.Result = null;
            }
            catch (Exception ex)  // Change to a file based log
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #51
0
        /// <summary>
        /// Updates the toolbar items.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="controller">The controller.</param>
        public static void UpdateToolbarItems(this Page page, UINavigationController controller)
        {
            try
            {
                if (page == null || controller == null)
                {
                    return;
                }

                if (controller.IsBeingDismissed)
                {
                    return;
                }

                var navController = controller.VisibleViewController;
                if (navController == null)
                {
                    return;
                }

                if (navController.NavigationItem?.RightBarButtonItems != null)
                {
                    for (var i = 0; i < navController.NavigationItem.RightBarButtonItems.Length; ++i)
                    {
                        navController.NavigationItem.RightBarButtonItems[i].Dispose();
                    }
                }

                if (navController.ToolbarItems != null)
                {
                    for (var i = 0; i < navController.ToolbarItems.Length; ++i)
                    {
                        navController.ToolbarItems[i].Dispose();
                    }
                }

                var toolbarItems = page.GetToolbarItems();
                if (toolbarItems == null)
                {
                    return;
                }

                List <UIBarButtonItem> primaries   = null;
                List <UIBarButtonItem> secondaries = null;

                foreach (var toolbarItem in toolbarItems)
                {
                    var barButtonItem = toolbarItem.ToUIBarButtonItem(toolbarItem.Order == ToolbarItemOrder.Secondary);
                    if (toolbarItem is IconToolbarItem iconItem)
                    {
                        if (!iconItem.IsVisible)
                        {
                            continue;
                        }

                        var icon = Iconize.FindIconForKey(iconItem.Icon);
                        if (icon != null)
                        {
                            using (var image = icon.ToUIImage(22f))
                            {
                                barButtonItem.Image = image;
                                if (iconItem.IconColor != Color.Default)
                                {
                                    barButtonItem.TintColor = iconItem.IconColor.ToUIColor();
                                }
                            }
                        }
                    }

                    if (toolbarItem.Order == ToolbarItemOrder.Secondary)
                    {
                        (secondaries = secondaries ?? new List <UIBarButtonItem>()).Add(barButtonItem);
                    }
                    else
                    {
                        (primaries = primaries ?? new List <UIBarButtonItem>()).Add(barButtonItem);
                    }
                }

                primaries?.Reverse();

                navController.NavigationItem.SetRightBarButtonItems(primaries == null ? new UIBarButtonItem[0] : primaries.ToArray(), false);
                navController.ToolbarItems = (secondaries == null ? new UIBarButtonItem[0] : secondaries.ToArray());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService(rockContext);
            var groupTypeService     = new GroupTypeService(rockContext);
            var groupService         = new GroupService(rockContext);

            var groupPaths       = new List <GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable().Where(gl => gl.Group.IsActive);
            int groupTypeId;

            // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter
            int?groupTypeIdPageParam = this.PageParameter("groupTypeId").AsIntegerOrNull();

            if (groupTypeIdPageParam.HasValue)
            {
                groupTypeId = groupTypeIdPageParam ?? Rock.Constants.All.Id;
            }
            else
            {
                groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id;
            }

            if (groupTypeId != Rock.Constants.All.Id)
            {
                var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents(groupTypeId).Select(a => a.Id);

                // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor)
                groupLocationQry = groupLocationQry.Where(a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains(a.Group.GroupTypeId));

                groupPaths = groupTypeService.GetAllAssociatedDescendentsPath(groupTypeId).ToList();
            }
            else
            {
                // if no specific GroupType is specified, show all GroupTypes with GroupTypePurpose of Checkin Template and their descendents (since this blocktype is specifically for Checkin)
                int        groupTypePurposeCheckInTemplateId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.GROUPTYPE_PURPOSE_CHECKIN_TEMPLATE)).Id;
                List <int> descendantGroupTypeIds            = new List <int>();
                foreach (var templateGroupType in groupTypeService.Queryable().Where(a => a.GroupTypePurposeValueId == groupTypePurposeCheckInTemplateId))
                {
                    groupPaths.AddRange(groupTypeService.GetAllAssociatedDescendentsPath(templateGroupType.Id).ToList());
                    foreach (var childGroupType in groupTypeService.GetChildGroupTypes(templateGroupType.Id))
                    {
                        descendantGroupTypeIds.Add(childGroupType.Id);
                        descendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(childGroupType.Id).Select(a => a.Id).ToList());
                    }
                }

                groupLocationQry = groupLocationQry.Where(a => descendantGroupTypeIds.Contains(a.Group.GroupTypeId));
            }

            if (gGroupLocationSchedule.SortProperty != null)
            {
                groupLocationQry = groupLocationQry.Sort(gGroupLocationSchedule.SortProperty);
            }
            else
            {
                groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name);
            }

            var qryList = groupLocationQry
                          .Where(a => a.Location != null)
                          .Select(a =>
                                  new
            {
                GroupLocationId = a.Id,
                a.Location,
                GroupId        = a.GroupId,
                GroupName      = a.Group.Name,
                ScheduleIdList = a.Schedules.Select(s => s.Id),
                GroupTypeId    = a.Group.GroupTypeId
            }).ToList();

            var locationService  = new LocationService(rockContext);
            int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id;

            if (parentLocationId != Rock.Constants.All.Id)
            {
                var currentAndDescendantLocationIds = new List <int>();
                currentAndDescendantLocationIds.Add(parentLocationId);
                currentAndDescendantLocationIds.AddRange(locationService.GetAllDescendents(parentLocationId).Select(a => a.Id));

                qryList = qryList.Where(a => currentAndDescendantLocationIds.Contains(a.Location.Id)).ToList();
            }

            // put stuff in a datatable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("GroupLocationId");
            dataTable.Columns.Add("GroupId");
            dataTable.Columns.Add("GroupName");
            dataTable.Columns.Add("GroupPath");
            dataTable.Columns.Add("LocationName");
            dataTable.Columns.Add("LocationPath");
            foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
            {
                dataTable.Columns.Add(field.DataField, typeof(bool));
            }

            var locationPaths = new Dictionary <int, string>();

            foreach (var row in qryList)
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"]       = groupService.GroupAncestorPathName(row.GroupId);
                dataRow["GroupPath"]       = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault();
                dataRow["LocationName"]    = row.Location.Name;

                if (row.Location.ParentLocationId.HasValue)
                {
                    int locationId = row.Location.ParentLocationId.Value;

                    if (!locationPaths.ContainsKey(locationId))
                    {
                        var locationNames  = new List <string>();
                        var parentLocation = locationService.Get(locationId);
                        while (parentLocation != null)
                        {
                            locationNames.Add(parentLocation.Name);
                            parentLocation = parentLocation.ParentLocation;
                        }
                        if (locationNames.Any())
                        {
                            locationNames.Reverse();
                            locationPaths.Add(locationId, locationNames.AsDelimited(" > "));
                        }
                        else
                        {
                            locationPaths.Add(locationId, string.Empty);
                        }
                    }

                    dataRow["LocationPath"] = locationPaths[locationId];
                }

                foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
                {
                    int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty));
                    dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId);
                }

                dataTable.Rows.Add(dataRow);
            }

            gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Read <GroupLocation>().Id;
            gGroupLocationSchedule.DataSource   = dataTable;
            gGroupLocationSchedule.DataBind();
        }
        /**
         * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
         */
        void addShape(Shape shape, Option options)
        {
            int curveSegments = options.curveSegments;

            //Material material = options.material;
            //var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
            ExtrudeGeometry.WorldUVGenerator uvgen = options.UVGenerator;
            if (uvgen == null)
            {
                uvgen = new ExtrudeGeometry.WorldUVGenerator();
            }

            //BoundingBox shapebb = this.shapebb;
            //

            int i, l;

            int shapesOffset = this.vertices.Count;
            ShapeAndHoleObject shapePoints = shape.extractPoints(curveSegments);

            List <Vector3>         vertices = shapePoints.shapeVertices;
            List <List <Vector3> > holes    = shapePoints.holes;

            bool reverse = !Shape.Utils.isClockWise(vertices);

            if (reverse)
            {
                //vertices = vertices.reverse();
                vertices.Reverse();

                // Maybe we should also check if holes are in the opposite direction, just to be safe...

                for (i = 0, l = holes.Count; i < l; i++)
                {
                    List <Vector3> hole = holes[i];

                    if (Shape.Utils.isClockWise(hole))
                    {
                        //holes[ i ] = hole.reverse();
                        hole.Reverse();
                        holes[i] = hole;
                    }
                }

                reverse = false;
            }

            List <List <int> > faces = Shape.Utils.triangulateShape(vertices, holes);

            // Vertices
            //var contour = vertices;

            for (i = 0, l = holes.Count; i < l; i++)
            {
                List <Vector3> hole = holes[i];
                //vertices = vertices.concat( hole );
                vertices.AddRange(hole);
            }

            Vector3    vert;
            int        vlen = vertices.Count;
            List <int> face;
            int        flen = faces.Count;

            //var cont;
            //int clen = contour.Count;

            for (i = 0; i < vlen; i++)
            {
                vert = vertices[i];

                this.vertices.Add(new Vector3(vert.x, vert.y, 0));
            }

            for (i = 0; i < flen; i++)
            {
                face = faces[i];

                int a = face[0] + shapesOffset;
                int b = face[1] + shapesOffset;
                int c = face[2] + shapesOffset;

                Face3 f = new Face3(a, b, c);
                f.uvs = uvgen.generateBottomUV(this, shape, a, b, c).ToArray();
                this.faces.Add(f);

                //this.faceVertexUvs.Add( new List<Vector2>( new Vector2[]{ new Vector2(0.0f, 0.0f), new Vector2(0.0f, 0.0f), new Vector2(0.0f, 0.0f) })); // debug
            }
        }
Example #54
0
        private void enumElements(Browser browser, MSHTML.IHTMLElement baseelement, IESelector anchor, bool doEnum, int X, int Y)
        {
            MSHTML.IHTMLElement element  = baseelement;
            MSHTML.HTMLDocument document = browser.Document;
            var pathToRoot = new List <MSHTML.IHTMLElement>();

            while (element != null)
            {
                if (pathToRoot.Contains(element))
                {
                    break;
                }
                try
                {
                    pathToRoot.Add(element);
                }
                catch (Exception)
                {
                }
                try
                {
                    element = element.parentElement;
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "");
                    return;
                }
            }
            // Log.Selector(string.Format("IEselector::create pathToRoot::end {0:mm\\:ss\\.fff}", sw.Elapsed));
            pathToRoot.Reverse();
            if (anchor != null)
            {
                // var hasIframe = anchor.Where(x => x.Properties.Where(y=>y.Name=="tagName" && y.Value== "IFRAME").Count()>0).Count() > 0;
                var iframeidx = 0;
                for (var i = 0; i < anchor.Count(); i++)
                {
                    if (anchor[i].Properties.Where(y => y.Name == "tagName" && y.Value == "IFRAME").Count() > 0)
                    {
                        iframeidx = i;
                        break;
                    }
                }
                var anchorlist = anchor.Where(x => x.Enabled && x.Selector == null).ToList();
                //if (iframeidx>-1)
                //{
                //    for (var i = 0; i < iframeidx; i++)
                //    {
                //        pathToRoot.Remove(pathToRoot[0]);
                //    }
                //}
                for (var i = (iframeidx); i < anchorlist.Count(); i++)
                {
                    //if (((IESelectorItem)anchorlist[i]).Match(pathToRoot[0]))
                    if (IESelectorItem.Match(anchorlist[i], pathToRoot[0]))
                    {
                        pathToRoot.Remove(pathToRoot[0]);
                    }
                    else
                    {
                        Log.Selector("Element does not match the anchor path");
                        return;
                    }
                }
            }

            if (pathToRoot.Count == 0)
            {
                Log.Error("Element is same as annchor");
                return;
            }
            element = pathToRoot.Last();
            //
            // Log.Selector(string.Format("IEselector::remove anchor if needed::end {0:mm\\:ss\\.fff}", sw.Elapsed));
            IESelectorItem item;

            if (anchor == null && Items.Count == 0)
            {
                item         = new IESelectorItem(browser.Document);
                item.Enabled = true;
                //item.canDisable = false;
                Items.Add(item);
            }
            for (var i = 0; i < pathToRoot.Count(); i++)
            {
                var o = pathToRoot[i];
                item = new IESelectorItem(browser, o);
                if (i == 0 || i == (pathToRoot.Count() - 1))
                {
                    item.canDisable = false;
                }
                foreach (var p in item.Properties)
                {
                    int idx = p.Value.IndexOf(".");
                    if (p.Name == "className" && idx > -1)
                    {
                        int idx2 = p.Value.IndexOf(".", idx + 1);
                        if (idx2 > idx)
                        {
                            p.Value = p.Value.Substring(0, idx2 + 1) + "*";
                        }
                    }
                }
                if (doEnum)
                {
                    item.EnumNeededProperties(o, o.parentElement);
                }

                Items.Add(item);
            }
            if (frameTags.Contains(baseelement.tagName.ToUpper()))
            {
                //var ele2 = baseelement as MSHTML.IHTMLElement2;
                //var col2 = ele2.getClientRects();
                //var rect2 = col2.item(0);
                //X -= rect2.left;
                //Y -= rect2.top;
                var frame = baseelement as MSHTML.HTMLFrameElement;
                var fffff = frame.contentWindow;
                MSHTML.IHTMLWindow2 window = frame.contentWindow;
                MSHTML.IHTMLElement el2    = null;
                foreach (string frameTag in frameTags)
                {
                    MSHTML.IHTMLElementCollection framesCollection = document.getElementsByTagName(frameTag);
                    foreach (MSHTML.IHTMLElement _frame in framesCollection)
                    {
                        // var _f = _frame as MSHTML.HTMLFrameElement;
                        el2 = browser.ElementFromPoint(_frame, X, Y);
                        //var _wb = _f as SHDocVw.IWebBrowser2;
                        //document = _wb.Document as MSHTML.HTMLDocument;
                        //el2 = document.elementFromPoint(X, Y);
                        if (el2 != null)
                        {
                            var tag = el2.tagName;
                            // var html = el2.innerHTML;
                            Log.Selector("tag: " + tag);

                            //browser.elementx += _frame.offsetLeft;
                            //browser.elementy += _frame.offsetTop;
                            //browser.frameoffsetx += _frame.offsetLeft;
                            //browser.frameoffsety += _frame.offsetTop;


                            enumElements(browser, el2, anchor, doEnum, X, Y);
                            return;
                        }
                    }
                }
            }
        }
Example #55
0
        private void Refresh()
        {
            GameUtility.DestroyGameObjects <ListItemEvents>(this.mItems);
            if (Object.op_Equality((Object)this.ItemTemplate, (Object)null) || Object.op_Equality((Object)this.ItemContainer, (Object)null))
            {
                return;
            }
            GameManager instance = MonoSingleton <GameManager> .Instance;

            ChapterParam[]      chapters         = instance.Chapters;
            List <ChapterParam> chapterParamList = new List <ChapterParam>((IEnumerable <ChapterParam>)chapters);

            QuestParam[] availableQuests = instance.Player.AvailableQuests;
            long         serverTime      = Network.GetServerTime();
            ChapterParam chapterParam    = (ChapterParam)null;

            for (int index = chapterParamList.Count - 1; index >= 0; --index)
            {
                if ((string)GlobalVars.SelectedSection != chapterParamList[index].section)
                {
                    chapterParamList.RemoveAt(index);
                }
            }
            if (!string.IsNullOrEmpty((string)GlobalVars.SelectedChapter))
            {
                chapterParam = instance.FindArea((string)GlobalVars.SelectedChapter);
                for (int index = chapterParamList.Count - 1; index >= 0; --index)
                {
                    if (chapterParamList[index].parent == null || chapterParamList[index].parent.iname != (string)GlobalVars.SelectedChapter)
                    {
                        chapterParamList.RemoveAt(index);
                    }
                }
            }
            else
            {
                for (int index = chapterParamList.Count - 1; index >= 0; --index)
                {
                    if (chapterParamList[index].parent != null)
                    {
                        chapterParamList.RemoveAt(index);
                    }
                }
            }
            for (int index = chapterParamList.Count - 1; index >= 0; --index)
            {
                if (!this.ChapterContainsPlayableQuest(chapterParamList[index], chapters, availableQuests, serverTime))
                {
                    chapterParamList.RemoveAt(index);
                }
            }
            List <TowerParam> towerParamList = new List <TowerParam>();

            foreach (TowerParam tower in instance.Towers)
            {
                bool flag = false;
                for (int index = 0; index < availableQuests.Length; ++index)
                {
                    if (availableQuests[index].type == QuestTypes.Tower && availableQuests[index].IsDateUnlock(serverTime))
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag && (string.IsNullOrEmpty((string)GlobalVars.SelectedSection) || "WD_DAILY" == (string)GlobalVars.SelectedSection))
                {
                    towerParamList.Add(tower);
                }
            }
            if (this.Descending)
            {
                chapterParamList.Reverse();
            }
            for (int index = 0; index < towerParamList.Count; ++index)
            {
                TowerParam     data            = towerParamList[index];
                ListItemEvents listItemEvents1 = (ListItemEvents)null;
                if (!string.IsNullOrEmpty(data.prefabPath))
                {
                    StringBuilder stringBuilder = GameUtility.GetStringBuilder();
                    stringBuilder.Append("QuestChapters/");
                    stringBuilder.Append(data.prefabPath);
                    listItemEvents1 = AssetManager.Load <ListItemEvents>(stringBuilder.ToString());
                }
                if (Object.op_Equality((Object)listItemEvents1, (Object)null))
                {
                    listItemEvents1 = this.ItemTemplate;
                }
                QuestParam quest = MonoSingleton <GameManager> .Instance.FindQuest(data.iname);

                ListItemEvents listItemEvents2 = (ListItemEvents)Object.Instantiate <ListItemEvents>((M0)listItemEvents1);
                DataSource.Bind <TowerParam>(((Component)listItemEvents2).get_gameObject(), data);
                DataSource.Bind <QuestParam>(((Component)listItemEvents2).get_gameObject(), quest);
                ((Component)listItemEvents2).get_transform().SetParent(this.ItemContainer.get_transform(), false);
                ((Component)listItemEvents2).get_gameObject().SetActive(true);
                listItemEvents2.OnSelect = new ListItemEvents.ListItemEvent(this.OnTowerSelect);
                this.mItems.Add(listItemEvents2);
            }
            int num = 0;

            for (int index1 = 0; index1 < chapterParamList.Count; ++index1)
            {
                ChapterParam   data            = chapterParamList[index1];
                ListItemEvents listItemEvents1 = (ListItemEvents)null;
                if (!string.IsNullOrEmpty(data.prefabPath))
                {
                    StringBuilder stringBuilder = GameUtility.GetStringBuilder();
                    stringBuilder.Append("QuestChapters/");
                    stringBuilder.Append(data.prefabPath);
                    listItemEvents1 = AssetManager.Load <ListItemEvents>(stringBuilder.ToString());
                }
                if (Object.op_Equality((Object)listItemEvents1, (Object)null))
                {
                    listItemEvents1 = this.ItemTemplate;
                }
                ListItemEvents listItemEvents2 = (ListItemEvents)Object.Instantiate <ListItemEvents>((M0)listItemEvents1);
                DataSource.Bind <ChapterParam>(((Component)listItemEvents2).get_gameObject(), data);
                int total     = 0;
                int completed = 0;
                foreach (QuestParam availableQuest in MonoSingleton <GameManager> .Instance.Player.AvailableQuests)
                {
                    if (!(availableQuest.ChapterID != data.iname) && availableQuest.bonusObjective != null)
                    {
                        if (availableQuest.difficulty == QuestDifficulties.Elite)
                        {
                            ++num;
                        }
                        if (availableQuest.difficulty == GlobalVars.QuestDifficulty)
                        {
                            total += availableQuest.bonusObjective.Length;
                            for (int index2 = 0; index2 < availableQuest.bonusObjective.Length; ++index2)
                            {
                                if ((availableQuest.clear_missions & 1 << index2) != 0)
                                {
                                    ++completed;
                                }
                            }
                        }
                    }
                }
                SGChapterItem component = (SGChapterItem)((Component)listItemEvents2).GetComponent <SGChapterItem>();
                if (Object.op_Inequality((Object)component, (Object)null))
                {
                    component.SetProgress(total, completed);
                }
                ((Component)listItemEvents2).get_transform().SetParent(this.ItemContainer.get_transform(), false);
                ((Component)listItemEvents2).get_gameObject().SetActive(true);
                listItemEvents2.OnSelect = new ListItemEvents.ListItemEvent(this.OnNodeSelect);
                this.mItems.Add(listItemEvents2);
            }
            if (Object.op_Inequality((Object)this.BackButton, (Object)null))
            {
                if (chapterParam != null)
                {
                    this.BackButton.SetActive(true);
                }
                else if (!string.IsNullOrEmpty((string)GlobalVars.SelectedSection))
                {
                    this.BackButton.SetActive(!this.IsSectionHidden((string)GlobalVars.SelectedSection));
                }
            }
            FlowNode_GameObject.ActivateOutputLinks((Component)this, 50);
        }
Example #56
0
        private List <SyncromaticsWaypoint> SubdivideWaypoints(List <SyncromaticsWaypoint> syncWaypoints)
        {
            List <SyncromaticsWaypoint> newWaypoints = new List <SyncromaticsWaypoint>();

            for (int i = 0; i < syncWaypoints.Count; i += 2)
            {
                Coordinate firstLocation = new Coordinate(syncWaypoints[i].Latitude, syncWaypoints[i].Longitude);

                Coordinate secondLocation;
                if (i == syncWaypoints.Count - 1)
                {
                    secondLocation = new Coordinate(syncWaypoints[0].Latitude, syncWaypoints[0].Longitude);
                }
                else
                {
                    secondLocation = new Coordinate(syncWaypoints[i + 1].Latitude, syncWaypoints[i + 1].Longitude);
                }

                double distance = firstLocation.DistanceTo(secondLocation);
                if (distance > 20)
                {
                    double longDifference = firstLocation.Longitude - secondLocation.Longitude;
                    double latDifference  = firstLocation.Latitude - secondLocation.Latitude;

                    newWaypoints.Add(new SyncromaticsWaypoint()
                    {
                        Latitude  = syncWaypoints[i].Latitude,
                        Longitude = syncWaypoints[i].Longitude
                    });

                    //for every 20 meters between these two waypoints, add a new one.
                    double maxInterval = (int)Math.Floor(distance / 20) + 1;
                    List <SyncromaticsWaypoint> testlist = new List <SyncromaticsWaypoint>();
                    for (double j = 1; j < maxInterval; j++)
                    {
                        double newLat  = secondLocation.Latitude + (latDifference * (j / maxInterval));
                        double newLong = secondLocation.Longitude + (longDifference * (j / maxInterval));

                        testlist.Add(new SyncromaticsWaypoint()
                        {
                            Latitude  = newLat,
                            Longitude = newLong
                        });
                    }
                    //reverse() required because otherwise stoppath calculation breaks due to reversed headings.
                    testlist.Reverse();
                    testlist.ForEach(x => newWaypoints.Add(x));

                    newWaypoints.Add(new SyncromaticsWaypoint()
                    {
                        Latitude  = syncWaypoints[i == syncWaypoints.Count - 1 ? 0 : i + 1].Latitude,
                        Longitude = syncWaypoints[i == syncWaypoints.Count - 1 ? 0 : i + 1].Longitude
                    });
                }
                else
                {
                    newWaypoints.Add(new SyncromaticsWaypoint()
                    {
                        Latitude  = syncWaypoints[i].Latitude,
                        Longitude = syncWaypoints[i].Longitude
                    });

                    //TODO: adding the last element again can sometimes cause a weird path (e.g. on route c at MSC) because it goes the wrong direction.

                    newWaypoints.Add(new SyncromaticsWaypoint()
                    {
                        Latitude  = syncWaypoints[i == syncWaypoints.Count - 1 ? 0 : i + 1].Latitude,
                        Longitude = syncWaypoints[i == syncWaypoints.Count - 1 ? 0 : i + 1].Longitude
                    });
                }
            }

            return(newWaypoints);
        }
Example #57
0
        /// <summary>
        /// Construct Voronoi region for given vertex.
        /// </summary>
        /// <param name="region"></param>
        private void ConstructCell(VoronoiRegion region)
        {
            var vertex = region.Generator as Vertex;

            var vpoints = new List <Point>();

            Otri f      = default(Otri);
            Otri f_init = default(Otri);
            Otri f_next = default(Otri);
            Otri f_prev = default(Otri);

            Osub sub = default(Osub);

            // Call f_init a triangle incident to x
            vertex.tri.Copy(ref f_init);

            f_init.Copy(ref f);
            f_init.Onext(ref f_next);

            // Check if f_init lies on the boundary of the triangulation.
            if (f_next.tri.id == Mesh.DUMMY)
            {
                f_init.Oprev(ref f_prev);

                if (f_prev.tri.id != Mesh.DUMMY)
                {
                    f_init.Copy(ref f_next);
                    // Move one triangle clockwise
                    f_init.Oprev();
                    f_init.Copy(ref f);
                }
            }

            // Go counterclockwise until we reach the border or the initial triangle.
            while (f_next.tri.id != Mesh.DUMMY)
            {
                // Add circumcenter of current triangle
                vpoints.Add(points[f.tri.id]);

                region.AddNeighbor(f.tri.id, regions[f.Apex().id]);

                if (f_next.Equals(f_init))
                {
                    // Voronoi cell is complete (bounded case).
                    region.Add(vpoints);
                    return;
                }

                f_next.Copy(ref f);
                f_next.Onext();
            }

            // Voronoi cell is unbounded
            region.Bounded = false;

            Vertex torg, tdest, tapex;
            Point  intersection;
            int    sid, n = mesh.triangles.Count;

            // Find the boundary segment id (we use this id to number the endpoints of infinit rays).
            f.Lprev(ref f_next);
            f_next.Pivot(ref sub);
            sid = sub.seg.hash;

            // Last valid f lies at the boundary. Add the circumcenter.
            vpoints.Add(points[f.tri.id]);
            region.AddNeighbor(f.tri.id, regions[f.Apex().id]);

            // Check if the intersection with the bounding box has already been computed.
            if (!rayPoints.TryGetValue(sid, out intersection))
            {
                torg         = f.Org();
                tapex        = f.Apex();
                intersection = IntersectionHelper.BoxRayIntersection(bounds, points[f.tri.id], torg.y - tapex.y, tapex.x - torg.x);

                // Set the correct id for the vertex
                intersection.id = n + rayIndex;

                points[n + rayIndex] = intersection;
                rayIndex++;

                rayPoints.Add(sid, intersection);
            }

            vpoints.Add(intersection);

            // Now walk from f_init clockwise till we reach the boundary.
            vpoints.Reverse();

            f_init.Copy(ref f);
            f.Oprev(ref f_prev);

            while (f_prev.tri.id != Mesh.DUMMY)
            {
                vpoints.Add(points[f_prev.tri.id]);
                region.AddNeighbor(f_prev.tri.id, regions[f_prev.Apex().id]);

                f_prev.Copy(ref f);
                f_prev.Oprev();
            }

            // Find the boundary segment id.
            f.Pivot(ref sub);
            sid = sub.seg.hash;

            if (!rayPoints.TryGetValue(sid, out intersection))
            {
                // Intersection has not been computed yet.
                torg  = f.Org();
                tdest = f.Dest();

                intersection = IntersectionHelper.BoxRayIntersection(bounds, points[f.tri.id], tdest.y - torg.y, torg.x - tdest.x);

                // Set the correct id for the vertex
                intersection.id = n + rayIndex;

                rayPoints.Add(sid, intersection);

                points[n + rayIndex] = intersection;
                rayIndex++;
            }

            vpoints.Add(intersection);
            region.AddNeighbor(intersection.id, regions[f.Dest().id]);

            // Add the new points to the region (in counter-clockwise order)
            vpoints.Reverse();
            region.Add(vpoints);
        }
Example #58
0
        private static IDataLoader ApplyTransformsCore(IHost host, IDataLoader srcLoader,
                                                       KeyValuePair <string, string>[] tagData, Func <IHostEnvironment, int, IDataView, IDataView> createTransform)
        {
            Contracts.AssertValue(host, "host");
            host.AssertValue(srcLoader, "srcLoader");
            host.AssertNonEmpty(tagData);
            host.AssertValue(createTransform, "createTransform");

            // If the loader is a composite, we need to start with its underlying pipeline end.
            var         exes      = new List <TransformEx>();
            var         composite = srcLoader as CompositeDataLoader;
            IDataView   srcView;
            IDataLoader pipeStart;

            if (composite != null)
            {
                srcView = composite.View;
                exes.AddRange(composite._transforms);
                pipeStart = composite._loader;
            }
            else
            {
                srcView = pipeStart = srcLoader;
            }

            IDataView view = srcView;

            using (var ch = host.Start("Transforms"))
            {
                int count        = Utils.Size(tagData);
                var newlyCreated = new List <TransformEx>();
                for (int i = 0; i < count; i++)
                {
                    // REVIEW: this might cause silent automatic tag conflicts if the pipeline is short-circuited.
                    // Maybe it's better to allow empty tags?
                    var tag = tagData[i].Key;
                    if (string.IsNullOrEmpty(tag))
                    {
                        tag = GenerateTag(exes.Count);
                    }

                    var newDataView = createTransform(host, i, view);
                    // Append the newly created transforms to the exes list.
                    // If the newTransform is a 'no-op' transform, i.e. equal to the original view,
                    // the exes array will not be modified: there's no reason to record details of a no-op transform,
                    // especially since this would overwrite the useful details of the upstream transform.
                    newlyCreated.Clear();
                    IDataView curDataView = newDataView;
                    while (true)
                    {
                        var cur = curDataView as IDataTransform;
                        if (cur == null)
                        {
                            // We reached all the way back to the pipe start. The exes accumulated so far are irrelevant.
                            ch.Check(curDataView == pipeStart,
                                     "The transform has corrupted the chain (chain no longer starts with the same loader).");
                            exes.Clear();
                            break;
                        }

                        int index = exes.FindLastIndex(x => x.Transform == cur);
                        if (index >= 0)
                        {
                            // We found a transform in exes to attach to.
                            if (index < exes.Count - 1)
                            {
                                // The transform short-circuited some of the existing ones, remove them.
                                exes.RemoveRange(index + 1, exes.Count - index - 1);
                            }
                            break;
                        }

                        newlyCreated.Add(new TransformEx(tag, tagData[i].Value, cur));
                        curDataView = cur.Source;
                    }

                    newlyCreated.Reverse();
                    exes.AddRange(newlyCreated);

                    view = newDataView;
                }
            }

            return(view == srcView ? srcLoader : new CompositeDataLoader(host, exes.ToArray()));
        }
Example #59
0
        /// <summary>
        /// Checks that the polygon being made is valid.
        /// </summary>
        private void ValidatePoly()
        {
            if (tempNodes.Count >= 2)
            {
                // Checks if the polygon will overlap another.
                List <Vector> tempArray = new List <Vector>(tempNodes);
                if (nodeSelect != originNode)
                {
                    tempArray.Add(nodeSelect);
                }

                Vector checkPoint = new Vector((tempArray.ElementAt(0).X + tempArray.ElementAt(1).X + tempArray.ElementAt(2).X) / 3,
                                               (tempArray.ElementAt(0).Y + tempArray.ElementAt(1).Y + tempArray.ElementAt(2).Y) / 3);
                Plane2D plane = new Plane2D(tempArray.ElementAt(0), tempArray.ElementAt(1));

                if (plane.CheckCollision(checkPoint) == true)
                {
                    tempArray.Reverse();
                }

                List <Plane2D> tempPlanes = new List <Plane2D>();
                for (int i = 0; i < tempArray.Count; ++i)
                {
                    if (i == tempArray.Count - 1)
                    {
                        tempPlanes.Add(new Plane2D(tempArray[i], tempArray[0]));
                    }
                    else
                    {
                        tempPlanes.Add(new Plane2D(tempArray[i], tempArray[i + 1]));
                    }
                }

                List <Vector> vSet = new List <Vector>();

                foreach (Polygon p in polygons)
                {
                    foreach (Edge ed in p.edges)
                    {
                        vSet.Add(ed.start);
                    }
                }

                foreach (Vector v in vSet)
                {
                    bool isValid = false;

                    foreach (Plane2D pl in tempPlanes)
                    {
                        if (tempArray.Any(vec => vec == v) == true || pl.CheckCollision(v) == true)
                        {
                            isValid = true;
                        }
                    }

                    if (isValid == false)
                    {
                        nodeSelect = tempNodes.ElementAt(tempNodes.Count - 1);
                        MessageBox.Show("The polygon will overlap with another.", "Invalid edge");

                        return;
                    }
                }
            }

            if (tempNodes.Count < 3)
            {
                tempNodes.Add(nodeSelect);
                return;
            }

            int tailNode = tempNodes.Count - 1;

            if (tempNodes.Count == 3)
            {
                Vector checkPoint = new Vector((tempNodes.ElementAt(0).X + tempNodes.ElementAt(1).X + tempNodes.ElementAt(2).X) / 3,
                                               (tempNodes.ElementAt(0).Y + tempNodes.ElementAt(1).Y + tempNodes.ElementAt(2).Y) / 3);
                Plane2D plane = new Plane2D(tempNodes.ElementAt(0), tempNodes.ElementAt(1));

                if (plane.CheckCollision(checkPoint) == true)
                {
                    polyPositive = false;
                }
                else
                {
                    polyPositive = true;
                }
            }

            // Checks if Polygon is convex by comparing with the other temp nodes.
            Plane2D checkPlane;

            if (nodeSelect != originNode)
            {
                if (polyPositive == true)
                {
                    checkPlane = new Plane2D(tempNodes.ElementAt(tailNode), nodeSelect);
                }
                else
                {
                    checkPlane = new Plane2D(nodeSelect, tempNodes.ElementAt(tailNode));
                }

                for (int i = 0; i < tailNode - 1; ++i)
                {
                    if (checkPlane.CheckCollision(tempNodes.ElementAt(i)) == true)
                    {
                        nodeSelect = tempNodes.ElementAt(tailNode);
                        MessageBox.Show("Polygon needs to be convex.", "Invalid edge");

                        return;
                    }
                }
            }
            else
            {
                if (polyPositive == true)
                {
                    checkPlane = new Plane2D(tempNodes.ElementAt(tailNode), nodeSelect);
                }
                else
                {
                    checkPlane = new Plane2D(nodeSelect, tempNodes.ElementAt(tailNode));
                }

                for (int i = 1; i < tailNode; ++i)
                {
                    if (checkPlane.CheckCollision(tempNodes.ElementAt(i)) == true)
                    {
                        tempNodes.RemoveAt(tailNode);
                        nodeSelect = tempNodes.ElementAt(tailNode - 1);
                        MessageBox.Show("Polygon needs to be convex.", "Invalid edge");

                        return;
                    }
                }
            }

            // Adds selected node if it passes all the validation checks.
            if (nodeSelect != originNode)
            {
                tempNodes.Add(nodeSelect);
            }

            // Removes uneeded nodes that were inlined with the current node.
            Vector cur          = tempNodes.ElementAt(tailNode) - tempNodes.ElementAt(tailNode - 1);
            Vector prev         = tempNodes.ElementAt(tailNode - 1) - tempNodes.ElementAt(tailNode - 2);
            float  crossProduct = (float)(prev.X * cur.Y - prev.Y * cur.X);

            if (crossProduct == 0)
            {
                tempNodes.RemoveAt(tailNode - 1);
            }

            // One last check to see if the polygon already exists. Then stores the polygon once it is complete.
            if (tempNodes.Count >= 3 && nodeSelect == originNode)
            {
                foreach (Polygon p in polygons)
                {
                    int edgeCount = p.edges.Count;

                    for (int i = 0; i < p.edges.Count; ++i)
                    {
                        foreach (Vector v in tempNodes)
                        {
                            if (v == p.edges.ElementAt(i).start)
                            {
                                edgeCount--;
                                if (edgeCount == 0)
                                {
                                    originNode = new Vector(double.NaN, double.NaN);
                                    nodeSelect = new Vector(double.NaN, double.NaN);
                                    tempNodes.Clear();
                                    polyPositive = true;

                                    MessageBox.Show("Polygon is a duplicate and/or overlaps another.", "Invalid Polygon");

                                    return;
                                }
                            }
                        }
                    }
                }

                var nodeArray = tempNodes.ToArray();

                if (polyPositive == false)
                {
                    Array.Reverse(nodeArray);
                }

                polygons.Add(new Polygon(nodeArray));

                originNode = new Vector(double.NaN, double.NaN);
                nodeSelect = new Vector(double.NaN, double.NaN);
                tempNodes.Clear();
                polyPositive = true;
            }
        }
Example #60
0
    public List <Vector2Int> CalculatePath(Vector2Int startPos, Vector2Int endPos)
    {
        List <Vector2Int> path        = new List <Vector2Int>();
        Collection <Node> openNodes   = new Collection <Node>();
        Collection <Node> closedNodes = new Collection <Node>();


        Node startNode = new Node(null, startPos);

        startNode.HCost = getHeuristic(startPos, endPos);
        openNodes.Add(startNode);

        Node endNode = new Node(null, endPos);

        while (openNodes.Count > 0)
        {
            var currentNode = openNodes.OrderBy(node => node.FCost).First();
            openNodes.Remove(currentNode);
            closedNodes.Add(currentNode);

            if (currentNode == endNode)
            {
                Node current = currentNode;
                while (current != startNode)
                {
                    path.Add(current.Position);
                    current = current.Parent;
                }
                path.Add(startPos);

                path.Reverse();
                return(path);
            }

            List <Node> children = new List <Node>();
            foreach (var newPoint in pointsAround)
            {
                var nodePosition = currentNode.Position + newPoint;
                if (MazeGenerator.IsPointOutsideOfMaze(map, nodePosition))
                {
                    continue;
                }
                if (map[nodePosition.y, nodePosition.x])
                {
                    continue;
                }
                var newNode = new Node(currentNode, nodePosition);

                children.Add(newNode);
            }

            foreach (var child in children)
            {
                var modifiableChild = child;
                if (nodeContains(closedNodes, child))
                {
                    continue;
                }
                modifiableChild.GCost = currentNode.GCost + 1;
                if (nodeContainsAndHaveLessG(openNodes, modifiableChild))
                {
                    continue;
                }
                modifiableChild.HCost = getHeuristic(child.Position, endPos);

                openNodes.Add(modifiableChild);
            }
        }
        return(default);