/// <summary>
        /// Convert List of Trades to List of Completed Trades
        /// </summary>
        /// <param name="TradesOnly"></param>
        /// <returns></returns>
        public static List<CompletedTrade> CreateList(List<Trade> TradesOnly)
        {
            var CompList = new List<CompletedTrade>();
            var even = TradesOnly.Count % 2;
            int back = even == 2 ? 0 : 1;

            for (int x = 0; x < TradesOnly.Count - back; x += 2)
            {
                CompletedTrade t = new CompletedTrade();
                t.OpenTrade = TradesOnly[x];
                t.CloseTrade = TradesOnly[x + 1];
                CompList.Add(t);
            }

            if (TradesOnly.Last() != CompList.Last().CloseTrade)
            {
                CompletedTrade last = new CompletedTrade();

                last.OpenTrade = TradesOnly.Last();
                last.CloseTrade.TimeStamp = last.OpenTrade.TimeStamp;
                last.CloseTrade.BuyorSell = Trade.BuySell.None;
                last.CloseTrade.Reason = Trade.Trigger.None;
                last.CloseTrade.CurrentDirection = last.OpenTrade.CurrentDirection;
                last.CloseTrade.TradedPrice = last.OpenTrade.TradedPrice;
                CompList.Add(last);
            }



            return CompList;
        }
Example #2
0
        public static PointCollection FindConvexPolygon(List<Point> points)
        {
            List<Point> top = new List<Point>();
            List<Point> bottom = new List<Point>();

            IEnumerable<Point> finalTop;
            IEnumerable<Point> finalBottom;

            points.Sort((x, y) => { return (int) (x.X - y.X); });

            double deltaX = points.Last().X - points.First().X;
            double deltaY = points.Last().Y - points.First().Y;
            double denominator = (Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));

            for (int i = 1; i < points.Count - 1; i++)
                if (MinimumDistanceBetweenPointAndLine2D(points.First(), points.Last(), points[i], deltaX, deltaY,
                                                         denominator))
                    bottom.Add(points[i]);
                else
                    top.Add(points[i]);

            top.Insert(0, points.First());
            top.Add(points.Last());
            bottom.Insert(0, points.First());
            bottom.Add(points.Last());

            finalTop = ConvexHullCore(top, true);
            finalBottom = ConvexHullCore(bottom, false);

            return new PointCollection(finalTop.Union(finalBottom.Reverse()));
        }
 /// <summary>
 /// Maak een mooie samenvatting van de opgegeven nummers
 /// </summary>
 /// Probeer de nummers samen te vatten door een bereik te tonen.
 /// Waar niet mogelijk toon daar gewoon komma gescheiden nummers.
 /// Als het in beeld is dan wordt de eerste in ieder geval los getoond.
 /// <remarks>
 /// </remarks>
 private static string LiedVerzen(ILiturgieDisplay regelDisplay, bool toonEersteLos, IEnumerable<ILiturgieContent> vanDelen = null)
 {
     if (regelDisplay.VersenGebruikDefault.Gebruik || vanDelen == null || (!toonEersteLos && regelDisplay.VolledigeContent))
         return !string.IsNullOrEmpty(regelDisplay.VersenGebruikDefault.Tekst) ? regelDisplay.VersenGebruikDefault.Tekst : null;
     var over = vanDelen.Where(v => v.Nummer.HasValue).Select(v => v.Nummer.Value).ToList();
     if (!over.Any())
         return null;
     var builder = new StringBuilder();
     if (toonEersteLos)
     {
         builder.Append(over.First()).Append(", ");
         over.RemoveAt(0);
     }
     while (over.Any())
     {
         var nieuweReeks = new List<int> { over.First() };
         over.RemoveAt(0);
         while (over.Any() && over[0] == nieuweReeks.Last() + 1)
         {
             nieuweReeks.Add(over[0]);
             over.RemoveAt(0);
         }
         if (nieuweReeks.Count == 1)
             builder.Append(nieuweReeks[0]);
         else if (nieuweReeks.Count == 2)
             builder.Append(string.Join(", ", nieuweReeks));
         else
             builder.AppendFormat("{0} - {1}", nieuweReeks.First(), nieuweReeks.Last());
         builder.Append(", ");
     }
     return builder.ToString().TrimEnd(',', ' ');
 }
Example #4
0
        public static int ReverseMod(int num, int mod)
        {
            if (Math.Abs(num)>mod)
                throw new Exception("Number should be less then mode");
            if (num < 0)
                num = mod + num;

            List<int> dividers = new List<int>();
            int rest = 0;

            int smaller = num;
            int bigger = mod;

            while (rest != 1)
            {
                rest = bigger%smaller;
                dividers.Add(bigger/smaller);

                bigger = smaller;
                smaller = rest;
            }
            List<int> p = new List<int>();
            p.Add(0);
            p.Add(1);
            foreach (var divider in dividers)
            {
                p.Add(-divider*p.Last() + p[p.Count()-2]);
            }
            return p.Last() > 0 ? p.Last() :  mod + p.Last();
        }
Example #5
0
 public void nettoyerTrajectoire()
 {
     int dirX = 0, dirY = 0, oldDirX = 0, oldDirY = 0; // Directions sur les axes X et Y
     List<PositionElement> Sortie = new List<PositionElement>();
     foreach (PositionElement p in _Positions)
     {
         if (Sortie.Count == 0 )
             Sortie.Add(p);
         else
         {
             dirX = Math.Sign(p.X - Sortie.Last().X);
             dirY = Math.Sign(p.Y - Sortie.Last().Y);
             if (dirX != oldDirX || dirY != oldDirY)
             {
                 oldDirX = dirX;
                 oldDirY = dirY;
                 Sortie.Add(p);
             }
             else
             {
                 PositionElement p2 = Sortie[Sortie.Count-1];
                 p2.X = p.X;
                 p2.Y = p.Y;
                 Sortie[Sortie.Count - 1] = p2;
             }
         }
     }
     _Positions = Sortie;
 }
Example #6
0
        static void Main(string[] args)
        {
            // Task: to convert the Dictionary collection "elements"
            //to List with keeping hierarchy of elements
            Dictionary<string, string> elements = new Dictionary<string, string>()
            {
                {"Tissue", "Organ"},
                {"Cell", "Cells"},
                {"System", "Body"},
                {"Cells", "Tissue"},
                {"Organ", "System"},
            };

            List<string> hierarchy = new List<string>();

            string first = elements.Keys.First(el => !elements.ContainsValue(el));
            hierarchy.Add(first);

            while (elements.ContainsKey(hierarchy.Last()))
                hierarchy.Add(elements[hierarchy.Last()]);

            foreach (var item in hierarchy)
                Console.WriteLine(item);

            Console.ReadKey();
        }
        /// <summary>
        /// Reads the specified sub key.
        /// </summary>
        /// <param name="subKeys">The sub key.</param>
        /// <returns></returns>
        protected Object Read(string subKeys)
        {
            Object result = default(Object);

            try
            {
                string[] subKeyNames = subKeys.Split('/');
                List<RegistryKey> registryKeys = new List<RegistryKey>();
                for (int i = 0; i < subKeyNames.Length - 1; i++)
                {
                    RegistryKey currentRegistryKey = default(RegistryKey);
                    if (i == 0)
                    {
                        currentRegistryKey = Registry.CurrentUser.OpenSubKey(subKeyNames[i]);
                    }
                    else
                    {
                        currentRegistryKey = registryKeys[i - 1].OpenSubKey(subKeyNames[i]);
                    }
                    registryKeys.Add(currentRegistryKey);
                    if (registryKeys.Last() != null && subKeyNames.Last() != null)
                    {
                        result = registryKeys.Last().GetValue(subKeyNames.Last());
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return result;
        }
Example #8
0
        private static void HandleCollision(Snake snake, ConsoleRenderer renderer)
        {
            List<GameFieldCoords> snakeElements = new List<GameFieldCoords>();

            foreach (GameFieldCoords element in snake.GetPosition())
            {
                snakeElements.Add(element);
            }

            foreach (GameFieldCoords element in snakeElements)
            {
                if (element.Row >= renderer.GameFieldSize.Row || element.Row < 0
                    || element.Col >= renderer.GameFieldSize.Col || element.Col < 0)
                {
                    snake.IsDestroyed = true;
                }
            }

            for (int element = 0; element < snakeElements.Count - 1; element++)
            {
                if (snakeElements.Last().Row == snakeElements[element].Row
                    && snakeElements.Last().Col == snakeElements[element].Col)
                {
                    snake.IsDestroyed = true;
                }
            }
        }
        public List<GroupedFilesViewModel> Evaluate(int numberOfGroups, string[] directories)
        {
            var groups = new List<GroupedFilesViewModel>();
            var foldersPerGroup = FoldersPerGroupEvaluator.Evaluate(directories.Count(), numberOfGroups);

            var i = 0;
            for (var g = 0; g < numberOfGroups; g++)
            {
                var group = new GroupedFilesViewModel { Files = new List<string>() };
                group.StartDir = directories[i];

                for (var f = 0; f < foldersPerGroup; f++)
                {
                    if (i < directories.Count())
                    {
                        group.Files.AddRange(DirectoryDescendentFilesEvaluator.Evaluate(directories[i]).ToList());
                        i++;
                    }
                }

                group.EndDir = directories[i - 1];
                groups.Add(group);
            }

            if (directories.Count() > i)
            {
                for (var r = i; r < directories.Count(); r++)
                {
                    groups.Last().Files.Add(directories[r]);
                    groups.Last().EndDir = directories[r];
                }
            }

            return groups;
        }
Example #10
0
 /// группирование гэпов; применятся для работы с минутными свечками
 public static List<GapList> CreateGapList(List<GapInfo> gaps, int maxGapListLengthDays = 3, int maxGapCount = 50)
 {
     var result = new List<GapList>();
     foreach (var gap in gaps)
     {
         var requestStart = gap.start;
         while (requestStart < gap.end)
         {
             if(result.Count == 0)
                 result.Add(new GapList(maxGapListLengthDays, maxGapCount));
             var gapList = result.Last();
             if (gapList.GetFreeLengthDays() < 0.01) // 0.01 принято за минимально допустимое GetFreeLengthDays
             {
                 result.Add(new GapList(maxGapListLengthDays, maxGapCount));
                 gapList = result.Last();
             }
             var requestEnd = requestStart.AddDays(gapList.GetFreeLengthDays()).AddMinutes(-1);
             if (requestEnd > gap.end)
                 requestEnd = gap.end;
             gapList.AddGap(new GapInfo {start = requestStart, end = requestEnd});
             requestStart = requestEnd.AddMinutes(1);
         }
     }
     return result;
 }
    public int[] FindBest()
    {
      var remaining = new HashSet<Point>(_cities);
      var first = remaining.First();
      var route = new List<Point> { first };
      remaining.Remove(first);

      var numericRoute = new List<int>{_cities.IndexOf(first)};
      var distance = 0.0d;
      while (remaining.Any())
      {
        var shortest = double.MaxValue;
        Point next = null;
        foreach (var p in remaining)
        {
          var d = Distance(route.Last(), p);
          if (d < shortest)
          {
            shortest = d;
            next = p;
          }
        }
        route.Add(next);
        numericRoute.Add(_cities.IndexOf(next));
        remaining.Remove(next);
        distance += shortest;
    
      }


      distance += Distance(route.First(), route.Last());
      Console.WriteLine("Distance calculated in closestneighbour: " + distance);
      return numericRoute.ToArray();
    }
Example #12
0
        /// <summary>
        /// Calculates Exponential Moving Average (EMA) indicator
        /// </summary>
        /// <param name="input">Input signal</param>
        /// <param name="period">Number of periods</param>
        /// <param name="uisngavg">Start with Average or start with first element</param>
        /// <returns>Object containing operation results</returns>
        public static EMAResult EMA(IEnumerable<double> input, int period, bool usingavg=true)
        {
            var returnValues = new List<double>();

            double multiplier = (2.0 / (period + 1));

            int start = usingavg ? period : 1;

            if ( input.Count() >= start)
            {
                double initialEMA = usingavg ? input.Take(period).Average() : input.First();

                returnValues.Add(initialEMA);

                var copyInputValues = input.ToList();

                for (int i = start; i < copyInputValues.Count; i++)
                {
                    var resultValue = (copyInputValues[i] - returnValues.Last()) * multiplier + returnValues.Last();

                    returnValues.Add(resultValue);
                }
            }

            var result = new EMAResult()
            {
                Values = returnValues,
                StartIndexOffset = start - 1
            };

            return result;
        }
Example #13
0
        private void StartThreads()
        {
            //How many threads do I need?
            int itemCount = ((int)(nudMax.Value - nudMin.Value)) + 1;
            int threadCount = itemCount / (int)nudInterval.Value + 1;
            threadList = new List<Thread>(threadCount);

            //Split up my ranges
            int increment = (int)nudInterval.Value;
            int maximum = (int)nudMax.Value;
            
            int current = (int)nudMin.Value;
            int next = current + increment;

            while (current <= maximum)
            {
                if (next > maximum) next = maximum;
                //Create some threads
                threadList.Add(new Thread(new ParameterizedThreadStart(FindPrimes)));
                threadList.Last().Start(new Limits(current, next));
                threadList.Last().IsBackground = true;
                current = next + 1;
                next = current + increment;
            }
            //Problem!!  If my threads are foreground, we wait here until they are all done.
            //If they are background, they all exit once we get here.
            //We can solve some of these problems with a threadpool.
        }
 public int ModifLikeProduit(List<string> aData)
 {
     DataSet DsJson = new DataSet();
     MyCo NewCo = new MyCo();
     NewCo.UpdateLikeProduit(aData.IndexOf(aData.Last()).ToString(),aData.Last(),ref DsJson);
     return aData.IndexOf(aData.Last());
 }
        private static void ValidateReordering(List<INode> chain1, List<INode> chain2, int closestParentIndex, IDiagInfo diagInfo)
        {
            var invalidNode1 = GetInvalidNode(chain1, closestParentIndex);
            var invalidNode2 = GetInvalidNode(chain2, closestParentIndex);
            if (invalidNode1 == null && invalidNode2 == null)
            {
                return;
            }

            var fixNode1 = invalidNode1 ?? chain1.Last();
            var fixNode2 = invalidNode2 ?? chain2.Last();

            var exceptionMessage = $"There is an uncertainty between {chain1.Last()} (a) and {chain2.Last()} (b)" + Environment.NewLine +
                $"{GetInvalidateString("a", chain1.Last(), invalidNode1)}{GetInvalidateString("b", chain2.Last(), invalidNode2)}" +
                $"To deal with this uncertainty, you can either make {fixNode1} depend on {chain2.Last()} or {fixNode2} depend on {chain1.Last()}";
            var tuples = new List<Tuple<IToken, IDiagInfo>>
                         {
                             GetNodeTuple(fixNode1),
                             GetNodeTuple(chain1.Last()),
                             GetNodeTuple(fixNode2),
                             GetNodeTuple(chain2.Last())
                         };

            throw new DetailedRegistrationException(exceptionMessage, tuples, diagInfo);
        }
Example #16
0
 public IList<Hand> ProcessFile(FileInfo fileInfo)
 {
     DateTime fileStartDate = DateTime.UtcNow;
     string fileStatus = "succes";
     var lastImportDate = _dataRepository.GetImportsRepository().GetLastImportFileDate(fileInfo.Name);
     IList<Hand> hands = new List<Hand>();
     try
     {
         hands = _parser.Parse(fileInfo.FullName, lastImportDate);
         _dataRepository.GetHandsRepository().SaveHandsSqlCommand(hands);
         OnNewFileProcessed(new NewFileProcessedEventArgs(fileInfo.Name, hands.Count, hands.Last()));
     }
     catch (Exception e)
     {
         fileStatus = "fail : " + e.Message + " " + e.StackTrace;
     }
     finally
     {
         DateTime endFileDate = DateTime.UtcNow;
         if (hands.Count > 0)
         {
             var lastHand = hands.Last();
             _dataRepository.GetImportsRepository().LogFileImport(fileInfo, fileStartDate, endFileDate, fileStatus, lastHand);
         }
     }
     return hands;
 }
        private void IdentifyRoutes(List<List<Node>> allRoutes, List<Node> currentList, Graph map)
        {
            foreach (var node in map.Nodes)
            {
                if (currentList.Count > 0)
                    if (!map.EdgeExists(currentList.Last(), node.Value))
                        continue;

                if ((currentList.Select(x => x.Key).Contains(node.Key)))
                    continue;

                if (currentList.Count < map.Nodes.Count - 1)
                {
                    if (!(currentList.Select(x => x.Key).Contains(node.Key)))
                    {
                        var newList = CloneList(currentList);
                        newList.Add(node.Value);
                        IdentifyRoutes(allRoutes, newList, map);
                    }
                }
                else
                {
                    var newList = CloneList(currentList);
                    newList.Add(node.Value);

                    if (!map.EdgeExists(currentList.Last(), currentList.First()))
                        continue;

                    newList.Add(currentList.First());
                    allRoutes.Add(newList);
                }
            }
        }
        // Editors
        void Extend(List<double[]> list, double topLayer)
        {
            double newAltitude = list.Last()[0];
            double dX = list.Last()[0] - list[list.Count - 2][0];
            double[] K = getK(list);

            for (int i = 0; newAltitude < topLayer; i++)
            {
                newAltitude += dX;
                double newPressure = getY(newAltitude, list.Last(), K);
                double[] newKey = { newAltitude, newPressure };

                if (newKey[1] < 0)
                {
                    if (list.Last()[1] == 0)
                        break;
                    else
                        newKey[1] = 0;
                }

                list.Add(newKey);
            }

            // Debug
            PrintCurve(list, "Extend");
        }
Example #19
0
        public async Task InitializeContextAsync()
        {
            //simulates a network delay
            await Task.Delay(TimeSpan.FromSeconds(2.5d));

            Tables = new List<Table>
            {
                new Table() {Description = "Back-Corner Two Top"},
                new Table() {Description = "Front Booth"}
            };

            StandardMenuItems = new List<MenuItem>
            {
                new MenuItem { Title = "French Bread & Fondue Dip", Price = 5.75m },
                new MenuItem { Title = "Curried Chicken and Rice", Price = 9.00m },
                new MenuItem { Title = "Feta-Stuffed Chicken", Price = 8.25m },
                new MenuItem { Title = "Grilled Pork Loin", Price = 11.50m },
                new MenuItem { Title = "Carnitas Tacos", Price = 7.50m },
                new MenuItem { Title = "Fillet Mignon & Asparagus", Price = 15.75m },
                new MenuItem { Title = "T-Bone Steak", Price = 12.25m },
                new MenuItem { Title = "Pineapple and Pear Salad", Price = 6.25m },
                new MenuItem { Title = "Sautéed Broccoli", Price = 3.75m },
                new MenuItem { Title = "Mashed Peas", Price = 3.25m }
            };

            Orders = new ObservableCollection<Order>
            {
                new Order { Complete = false, Expedite = true, SpecialRequests = "Allergic to Shellfish", Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.First() } },
                new Order { Complete = false, Expedite = false, SpecialRequests = string.Empty, Table = Tables.Last(), Items = new List<MenuItem> { StandardMenuItems.Last(), StandardMenuItems.First() } },
            };
        }
Example #20
0
        private void HandleCollision(IHungryCreature creature, IRenderer renderer)
        {
            List<GameFieldCoords> creatureElements = new List<GameFieldCoords>();

            foreach (GameFieldCoords element in creature.GetPosition())
            {
                creatureElements.Add(element);
            }

            foreach (GameFieldCoords element in creatureElements)
            {
                if (element.Row >= renderer.GameFieldSize.Row || element.Row < 0
                    || element.Col >= renderer.GameFieldSize.Col || element.Col < 0)
                {
                    creature.IsDestroyed = true;
                }
            }

            for (int element = 0; element < creatureElements.Count - 1; element++)
            {
                if (creatureElements.Last().Row == creatureElements[element].Row
                    && creatureElements.Last().Col == creatureElements[element].Col)
                {
                    creature.IsDestroyed = true;
                }
            }
        }
        public static List<INFATITrip> CalculateTripsByCarId(Int16 carId)
        {
            DBController dbc = new DBController();

            //Fetch all temporalinformation for a cardId
            List<TemporalInformation> datapoints = dbc.GetTimestampsByCarId(carId);
            dbc.Close();
            //Instantiate the containers for trips and timestamps fetched by a single date at a time
            List<INFATITrip> allTrips = new List<INFATITrip>();
            INFATITrip trip = new INFATITrip(carId);
            allTrips.Add(trip);

            //First case
            allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(0).EntryId, datapoints.ElementAt(0).Timestamp));

            //Starting to iterate over all timestamps
            for (int i = 1; i < datapoints.Count(); i++) {
                //Compare the last seen timestamp to the current, if more than 300 seconds has past, create a new trip and store the current timestamp in it
                if (Math.Abs(ToUnixTime(allTrips.Last().Timestamps.Last().Timestamp) - ToUnixTime(datapoints.ElementAt(i).Timestamp)) <= 180) {
                    allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(i).EntryId, datapoints.ElementAt(i).Timestamp));
                } else {
                    allTrips.Add(new INFATITrip(carId));
                    allTrips.Last().Timestamps.Add(new TemporalInformation(datapoints.ElementAt(i).EntryId, datapoints.ElementAt(i).Timestamp));
                }
            }

            return allTrips;
        }
Example #22
0
        public IEnumerable<KeyValuePair<string, IStockRealTime>> GetData(IEnumerable<string> stockCodes)
        {
            if (stockCodes == null)
            {
                return new List<KeyValuePair<string, IStockRealTime>>();
            }

            List<List<string>> codePackages = new List<List<string>>();
            foreach(var code in stockCodes)
            {
                if(codePackages.Count < 1 || codePackages.Last().Count > 100)
                {
                    codePackages.Add(new List<string>());
                }

                codePackages.Last().Add(code);
            }

            List<KeyValuePair<string, IStockRealTime>> result = new List<KeyValuePair<string, IStockRealTime>>();
            foreach (var package in codePackages)
            {
                var packageResult = GetDataByPackage(package);
                result.AddRange(packageResult);
            }

            return result;
        }
Example #23
0
        void foo()
        {
            var g = new Stack<int>();
            var c = Enumerable.Range(1, 100).ToList();
            for (int i = 101; i > 2; i--)
            {
                g.Push(i);
            }

            var paisr = new List<clc>();
            int h = 0;
            while (g.Count > 1)
            {
                paisr.Add(new clc() { x = c[h], p = new Pair() { x1 = g.Pop(), x2 = g.Pop() } });
                h++;
                if (g.Count == 1)
                {
                    paisr.Add(new clc() { x = c[h], p = new Pair() { x1 = g.Pop() } });
                    break;
                }
            }

            h = paisr.Count;
            while (paisr.Count > 2)
            {
                var p = paisr.Last();
                var top = paisr.FirstOrDefault(x => x.p.Has(p.x));
                if (top != null)
                {
                    top.p.Addto(p.x, p.p);
                    paisr.Remove(paisr.Last());
                }
            }
            return;
        }
Example #24
0
        private static List<IPerson> GeneratePopulation(int id, ICivilization civilization, int popCount)
        {
            List<IPerson> population = new List<IPerson>();
            for (int n = 0; n < popCount; n++)
            {
                //Thread.Sleep(_Random.Next(200, 700));
                PersonHelper personHelper = new PersonHelper();
                personHelper.Civilization = civilization;
                personHelper.Race = civilization.Race;
                personHelper.Mythology = civilization.Race.Mythos;

                // maybe we should check the population levels before starting the next loop? First thing in the for loop?
                IPopulationCenters popCenter = civilization.PopulationCenters.First(pc => pc.Population.Count < pc.MaxPopulation);
                personHelper.OriginatesFrom = popCenter; // WHAT HAPPENS WHEN WE RUN OUT OF CITIES!?
                personHelper.Father = new Person();
                personHelper.Mother = new Person();
                personHelper.Partner = new Person();

                PersonGen personGen = new PersonGen();

                IPerson person = personGen.GenerateSingle(personHelper);
                population.Add(person);
                popCenter.Population.Add(person);

                if (n < 9) person.SocialStatus = CoreEnums.Status.Highborne;
                WriteToConsole("ID: " + id + "Name: " + population.Last().Name + "; Race: " + population.Last().Race.Name);
            }
            return population;
        }
Example #25
0
        private static List<Command> Parse(string[] args)
        {
            var commands = new List<Command>();

            if (args.Length == 0) commands.Add(new Help());

            foreach (var commandStr in args)
            {
                switch (commandStr)
                {
                    case "/?":
                    case "/help":
                    case "-help":
                        commands.Clear();
                        commands.Add(new Help());
                        return commands;
                    case "-k":
                        commands.Add(new KeyValue());
                        break;
                    case "-ping":
                        commands.Add(new Ping());
                        break;
                    case "-print":
                        commands.Add(new Print());
                        break;
                    default:
                        if (commands.Count > 0 && !(commands.Last() is Ping))
                            commands.Last().AddValue(commandStr);
                        else
                            Console.WriteLine("Command <{0}> is not supported, use CommandParser.exe /? to see set of allowed commands", commandStr);
                        break;
                }
            }
            return commands;
        }
Example #26
0
 public List<Tuple<string, string>> OrderSecurityTokens(AccessCodeSet accessCodeSet, List<Tuple<string, string>> sortedList, string newStartColor)
 {
     var startColor = accessCodeSet.StartColor;
     if (!string.IsNullOrEmpty(newStartColor))
         startColor = newStartColor;
     if (accessCodeSet.TokenList.Count(x => x.Item1.Equals(startColor)) == 1)
     {
         sortedList.Add(accessCodeSet.TokenList.Single(x => x.Item1.Equals(startColor)));
         accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { sortedList.Last() }).ToList();
     }
     else
     {
         var listOfTokensWithSameStartColor = accessCodeSet.TokenList.Where(x => x.Item1.Equals(startColor));
         if (!listOfTokensWithSameStartColor.Any())
             return sortedList;
         foreach (var token in listOfTokensWithSameStartColor)
         {
             if (accessCodeSet.TokenList.Count(x => x.Item1.Equals(token.Item2)) == 1)
             {
                 sortedList.Add(token);
                 accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { token }).ToList();
                 sortedList.Add(accessCodeSet.TokenList.Single(x => x.Item1.Equals(token.Item2)));
                 accessCodeSet.TokenList = accessCodeSet.TokenList.ToList().Except(new List<Tuple<string, string>> { sortedList.Last() }).ToList();
             }
         }
     }
     if (accessCodeSet.TokenList.Any())
         OrderSecurityTokens(accessCodeSet, sortedList, sortedList.Last().Item2);
     return sortedList;
 }
Example #27
0
        private List<Book> GetAllBooks()
        {
            var books = new List<Book>();
            var connectionString = ConfigurationManager.ConnectionStrings["HanHomeworkConnectStr"].ConnectionString;

            using (var connection = new SqlConnection(connectionString))
            {
                const string commandText = "SELECT * FROM book";
                var command = new SqlCommand(commandText, connection);

                connection.Open();
                using (var dataReader = command.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        books.Add(new Book());
                        books.Last().Id = (int)dataReader["Id"];
                        books.Last().BookName = (string)dataReader["bookName"];
                        books.Last().PageCount = (string)dataReader["pageCount"];
                    }
                }
            }

            return books;
        }
        /// <summary>
        /// Creates an enumeration of fits for X and Y coordinates such that each fit improves the previous one. The last fit is the best one.
        /// </summary>
        /// <param name="xs">The X coordinates array</param>
        /// <param name="ys">The corresponding Y coordinates array</param>
        /// <param name="threshold">Error threshold that controls division into intervals</param>
        /// <returns>The enumeration of fits. Each fit is made of the coefficients and the interval breaking indices</returns>
        private static IEnumerable<Fit> EnumerateFits(double[] xs, double[] ys, double threshold)
        {
            Contract.Requires(xs.Length > 0);
            Contract.Requires(xs.Length == ys.Length);
            Contract.Requires(threshold > 0);

            int n = xs.Length;
            var breakIndices = new List<int> { 3 };

            while (breakIndices.Last() < n) // while we haven't reached our optimal division yet
            {
                var breakIndicesArray = breakIndices.ToArray();
                var xIntervals = LSIntervalsFitter.FitIntervals(xs, breakIndicesArray);
                var yIntervals = LSIntervalsFitter.FitIntervals(ys, breakIndicesArray);
                yield return new Fit { xIntervals = xIntervals, yIntervals = yIntervals, breakIndices = breakIndicesArray };

                var xLastIntervalMSE = LastIntervalMSE(xIntervals, xs, breakIndices);
                var yLastIntervalMSE = LastIntervalMSE(yIntervals, ys, breakIndices);

                if (xLastIntervalMSE < threshold && yLastIntervalMSE < threshold) // our current interval is still good enough
                    breakIndices[breakIndices.Count - 1] = breakIndices.Last() + 1;
                else // we need a new interval to approximate well enough
                {
                    var nextIntervalBreak = breakIndices.Last() + 3;
                    if (nextIntervalBreak >= n)
                        breakIndices[breakIndices.Count - 1] = breakIndices.Last() + 1;
                    else
                        breakIndices.Add(nextIntervalBreak);
                }
            }
        }
Example #29
0
        public void Should_Track_Bounds()
        {
            var target = new BoundsTracker();
            var control = default(Rectangle);
            var tree = new Decorator
            {
                Padding = new Thickness(10),
                Content = new Decorator
                {
                    Padding = new Thickness(5),
                    Content = (control = new Rectangle
                    {
                        Width = 15,
                        Height = 15,
                    }),
                }
            };

            tree.Measure(Size.Infinity);
            tree.Arrange(new Rect(0, 0, 100, 100));

            var track = target.Track(control, tree);
            var results = new List<TransformedBounds>();
            track.Subscribe(results.Add);

            Assert.Equal(new Rect(15, 15, 15, 15), results.Last().Bounds);

            tree.Padding = new Thickness(15);
            tree.Measure(Size.Infinity);
            tree.Arrange(new Rect(0, 0, 100, 100), true);

            Assert.Equal(new Rect(20, 20, 15, 15), results.Last().Bounds);
        }
        /// <summary>
        /// 将共享点前移,构成2个图元组成的新的小小的索引。
        /// </summary>
        /// <param name="recognizedPrimitiveIndex0"></param>
        /// <param name="recognizedPrimitiveIndex1"></param>
        /// <param name="drawMode"></param>
        /// <param name="lastIndex0"></param>
        /// <param name="lastIndex1"></param>
        /// <returns></returns>
        private List<uint> ArrangeIndexes(
            RecognizedPrimitiveInfo recognizedPrimitiveIndex0,
            RecognizedPrimitiveInfo recognizedPrimitiveIndex1,
            DrawMode drawMode,
            out uint lastIndex0, out uint lastIndex1)
        {
            var sameIndexList = new List<uint>();
            var array0 = new List<uint>(recognizedPrimitiveIndex0.VertexIds);
            var array1 = new List<uint>(recognizedPrimitiveIndex1.VertexIds);
            array0.Sort(); array1.Sort();
            int p0 = 0, p1 = 0;
            while (p0 < array0.Count && p1 < array1.Count)
            {
                if (array0[p0] < array1[p1])
                { p0++; }
                else if (array0[p0] > array1[p1])
                { p1++; }
                else
                {
                    sameIndexList.Add(array0[p0]);
                    array0.RemoveAt(p0);
                    array1.RemoveAt(p1);
                }
            }

            if (array0.Count == 0 && array1.Count == 0)
            { throw new Exception("Two primitives are totally the same!"); }

            if (array0.Count > 0)
            { lastIndex0 = array0.Last(); }
            else
            {
                if (sameIndexList.Count == 0)
                { throw new Exception("array0 is totally empty!"); }

                lastIndex0 = sameIndexList.Last();
            }

            if (array1.Count > 0)
            { lastIndex1 = array1.Last(); }
            else
            {
                if (sameIndexList.Count == 0)
                { throw new Exception("array1 is totally empty!"); }

                lastIndex1 = sameIndexList.Last();
            }

            if (lastIndex0 == lastIndex1) { throw new Exception(); }

            var result = new List<uint>();
            result.AddRange(sameIndexList);
            result.AddRange(array0);
            result.Add(uint.MaxValue);// primitive restart index
            result.AddRange(sameIndexList);
            result.AddRange(array1);

            return result;
        }