public static void AddToMenu(Menu menu,
            string uniqueId,
            HealthCheckType checkType,
            HealthValueType valueType,
            string prefix = null,
            int value = 30,
            int minValue = 0,
            int maxValue = 100)
        {
            try
            {
                if (Menues.ContainsKey(uniqueId))
                {
                    throw new ArgumentException(
                        string.Format("HealthHealthger: UniqueID \"{0}\" already exist.", uniqueId));
                }

                menu.AddItem(
                    new MenuItem(
                        menu.Name + ".health-" + uniqueId,
                        (!string.IsNullOrEmpty(prefix) ? prefix + " " : string.Empty) +
                        (checkType == HealthCheckType.Minimum ? "Min. Health" : "Max. Health") +
                        (valueType == HealthValueType.Percent ? " %" : string.Empty)).SetValue(
                            new Slider(value, minValue, maxValue)));

                Menues[uniqueId] = new Tuple<Menu, HealthCheckType, HealthValueType>(menu, checkType, valueType);
            }
            catch (Exception ex)
            {
                Global.Logger.AddItem(new LogItem(ex));
            }
        }
 public void IntegerAverageOnTwoTuple()
 {
     var sut = new Tuple<int, int>(1, 2);
       double expected = sut.AsEnumerable().Cast<int>().Average();
       double actual = sut.Average(x => (int) x);
       Assert.AreEqual(expected, actual);
 }
Example #3
0
        private static void InsertSeparator(Tuple<ICommandItem, Menu> previous, Tuple<ICommandItem, Menu> current)
        {
            // Get lineage of each
            IMenu[] previousLineage = previous.Item2.Lineage().Reverse<IMenu>().ToArray<IMenu>();
            IMenu[] currentLineage = current.Item2.Lineage().Reverse<IMenu>().ToArray<IMenu>();

            // Find lowest common ancestor
            // (Assumes common ancestor exists)
            int minLength = Math.Min(previousLineage.Length, currentLineage.Length);

            IMenuItem insertBefore = null;
            IList<IMenuItem> collection = null;
        
            for (int i = 0; i < minLength; i++)
            {
                if (previousLineage[i] != currentLineage[i])
                {
                    insertBefore = currentLineage[i];
                    collection = ((Menu)currentLineage[i - 1]).ChildCollection;
                }
            }

            if (insertBefore == null)
            {
                insertBefore = minLength < currentLineage.Length ? currentLineage[minLength] as IMenuItem
                    : current.Item1;
                collection = ((Menu)currentLineage[minLength - 1]).ChildCollection;
            }

            int idx = collection.IndexOf(insertBefore);
            System.Diagnostics.Debug.Assert(idx >= 0);
            collection.Insert(idx, new Separator());
        }
        static void Main(string[] args)
        {
            Tuple<string, int>[] tuples = new Tuple<string, int>[] {
                new Tuple<string, int>("a", 3),
                new Tuple<string, int>("b", 2),
                new Tuple<string, int>("b", 5) };

            MapReduce<string, int> letters = new MapReduce<string, int>(tuples);
            IEnumerable<Tuple<string, int>> newmap;

            letters.Map<string, int>((input) =>
                {
                    return new Tuple<string, int>[] { new Tuple<string, int>(input.Item1, input.Item2 * input.Item2) };
                }, out newmap);

            IEnumerable<Tuple<string, int>> reduction = letters.Reduce<string, int>(newmap, (key, values) =>
                {
                    int total = 0;
                    foreach (var item in values)
                    {
                        total += item;
                    }
                    return total;
                });

            foreach (var item in reduction)
            {
                Console.WriteLine("{0} = {1}", item.Item1, item.Item2);
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
Example #5
0
        static void Main(string[] args)
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();
            Tuple<uint, BigInteger> max = new Tuple<uint, BigInteger>(0, 0);
            for (uint i = 2; i <= 1000; i++)
            {
                if ((uint)Math.Sqrt(i) != Math.Sqrt(i))
                {
                    BigInteger xSolution = getMinimumSolution((int)i);
                    if (xSolution > max.Item2)
                    {
                        max = new Tuple<uint, BigInteger>(i, xSolution);
                    }
                  //  Console.WriteLine(i + " => " + xSolution);
                }
                
            }

            Console.WriteLine("Answer = " + max.Item1 + " => " + max.Item2);
            Console.WriteLine("DONE in " + sw.ElapsedMilliseconds + " s" );
                Console.ReadKey();
            

         

        }
        private static bool AddExtension( XElement extensions, Func<string, bool> resolveOption, Tuple<string, string, Func<XElement>> mapping )
        {
            Contract.Requires( extensions != null );
            Contract.Requires( resolveOption != null );
            Contract.Requires( mapping != null );

            var option = mapping.Item1;

            // the option is not enabled
            if ( !resolveOption( option ) )
                return false;

            var category = mapping.Item2;

            // the extension is already configured
            if ( extensions.Elements( ExtensionName ).Any( e => ( (string) e.Attribute( "Category" ) ) == category ) )
                return false;

            // create and add extension
            var factory = mapping.Item3;
            var extension = factory();

            extensions.Add( extension );
            return true;
        }
 public ItemsWithConflictingHighestScoreException(Tuple<IValueProvider, IProbe>[] itemsWithConflictingScore, int highestScore)
     : base(string.Format(
         "items: {0} with conflicting highest score of {1} exists, cannot determine default", string.Concat(itemsWithConflictingScore.Select(x=>x.Item1.ToString())), highestScore))
 {
     ItemsWithConflictingScore = itemsWithConflictingScore;
     HighestScore = highestScore;
 }
        public override void Update(object sender, Tuple<Sale, SaleState> item)
        {
            using (SalesDBEntities context = new SalesDBEntities())
            {
                Product product = context.Products
                    .Where(p => p.ProductID == item.Item1.ProductID)
                    .SingleOrDefault<Product>();

                switch (item.Item2)
                {
                    case SaleState.SALE_ADD:
                        product.TotalSalesAmount += item.Item1.Quantity;
                        break;
                    case SaleState.SALE_UPDATE:
                        product.TotalSalesAmount = item.Item1.Quantity;
                        break;
                    case SaleState.SALE_DELETE:
                        product.TotalSalesAmount -= item.Item1.Quantity;
                        break;
                    default:
                        break;
                }   
                context.SaveChanges();
            }
        }
        public ActionResult GetPostByCategory(int id,int ?page)
        {
            _pagingHandler.PageIndex = page ?? 1;
            var postList = _pagingHandler.GetPagingList(c=>c.CategoryId==id,c => new PostModel()
            {
                Title = c.Title,
                DateTime = c.DateTime,
                ShortDescription = c.ShortDescription,
                FullName = c.User.FirstName + " " + c.User.LastName,
                Id = c.Id
            }, c => c.DateTime, ListSortDirection.Descending).ToList();

            var pagingModel = new PagingModel()
            {
                HasNextPage = _pagingHandler.HasNextPage,
                HasPreviousPage = _pagingHandler.HasPreviousPage,
                PageIndex = _pagingHandler.PageIndex,
                IsFirstPage = _pagingHandler.IsFirstPage,
                IsLastPage = _pagingHandler.IsLastPage,
                PageCount = _pagingHandler.PageCount,
                PageNumber = _pagingHandler.PageNumber,
                PageSize = _pagingHandler.PageSize
            };

            var model = new Tuple<List<PostModel>, PagingModel>(postList, pagingModel);
            return View("_ListPost", model);
        }
        static public List<Tuple<String, double>> readPriceList()
        {
            List<Tuple<String, double>> priceList = new List<Tuple<String, double>>();

            try
            {
                string[] lines = System.IO.File.ReadAllLines("PriceData.txt");

                foreach (String line in lines)
                {
                    String[] split_string = line.Split('[');
                    split_string[1] = split_string[1].Trim(']');
                    Tuple<String, double> pair = new Tuple<String, double>(split_string[0], Convert.ToDouble(split_string[1]));
                    priceList.Add(pair);
                }
            }

            // This can catch either a file not found exception, or a format exception for the double conversion
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return priceList;
        }
Example #11
0
        public void Draw(SpriteBatch sbatch)
        {
            for (int i = 0; i < size + 1; i++)
            {

                Tuple<Vector2, Vector2> line4 = new Tuple<Vector2, Vector2>(gridEdgeCoords(new Vector2(i, 0)), gridEdgeCoords(new Vector2(i, size))); //CartesianCoords(new Vector2(x, 0)), CartesianCoords(new Vector2(x, (float) rows-1))

                float angle4 = (float)Math.Atan2(line4.Item2.Y - line4.Item1.Y, line4.Item2.X - line4.Item1.X);
                float length4 = Vector2.Distance(line4.Item1, line4.Item2);

                sbatch.Draw(blank, line4.Item1 + new Vector2(0, 0), null, Microsoft.Xna.Framework.Color.Red, angle4, Vector2.Zero, new Vector2(length4, 1.0f), SpriteEffects.None, 0.49f);

            }

            for (int j = 0; j < size + 1; j++)
            {
                Tuple<Vector2, Vector2> line4 = new Tuple<Vector2, Vector2>(gridEdgeCoords(new Vector2(0, j)), gridEdgeCoords(new Vector2(size, j))); //CartesianCoords(new Vector2(x, 0)), CartesianCoords(new Vector2(x, (float) rows-1))

                float angle4 = (float)Math.Atan2(line4.Item2.Y - line4.Item1.Y, line4.Item2.X - line4.Item1.X);
                float length4 = Vector2.Distance(line4.Item1, line4.Item2);

                sbatch.Draw(blank, line4.Item1 + new Vector2(0, 0), null, Microsoft.Xna.Framework.Color.Red, angle4, Vector2.Zero, new Vector2(length4, 1.0f), SpriteEffects.None, 0.49f);

            }
        }
Example #12
0
 public string FormatLine(int id, Tuple<float, float, float> xyz, Tuple<int, int, int> rgb)
 {
     return String.Format(CultureInfo.InvariantCulture,
         "{0} {1} {2} {3} {4} {5}\n",
         xyz.Item1, xyz.Item2, xyz.Item3,
         rgb.Item1, rgb.Item2, rgb.Item3);
 }
Example #13
0
 /// <summary>
 /// Ctor is based on single line from the fed's text report
 /// </summary>
 /// <param name="li"></param>
 internal Bank(dynamic li)
 {
     const string COMMA = ",";
     const string LETTER_Y = "Y";
     UpsertName(KindsOfNames.Legal, li.BankName);
     UpsertName(KindsOfNames.Abbrev, li.BankName);
     Rssd = new ResearchStatisticsSupervisionDiscount { Value = li.BankId };
     UsCityStateZip cityOut;
     if (UsCityStateZip.TryParse(li.Location, out cityOut))
         BusinessAddress = new Tuple<UsStreetPo, UsCityStateZip>(null, cityOut);
     if (FedLrgBnk.TypeOfBankAbbrev3Enum.ContainsKey(li.Chtr))
         BankType = FedLrgBnk.TypeOfBankAbbrev3Enum[li.Chtr];
     var assets = new FinancialAssets { Src = FedLrgBnk.RELEASE_URL };
     decimal conAssts = 0;
     decimal domAssts = 0;
     if (decimal.TryParse(li.ConsolAssets.Replace(COMMA, string.Empty), out conAssts))
         assets.TotalAssets = new Pecuniam(conAssts * ONE_THOUSAND);
     if (decimal.TryParse(li.DomesticAssets.Replace(COMMA, string.Empty), out domAssts))
         assets.DomesticAssets = new Pecuniam(domAssts * ONE_THOUSAND);
     int domBranches = 0;
     int frnBranches = 0;
     int pfo = 0;
     if (int.TryParse(li.NumOfDomBranches.Replace(COMMA, string.Empty), out domBranches))
         assets.DomesticBranches = domBranches;
     if (int.TryParse(li.NumOfFgnBranches.Replace(COMMA, string.Empty), out frnBranches))
         assets.ForeignBranches = frnBranches;
     IsInternational = li.Ibf == LETTER_Y;
     if (int.TryParse(li.PercentFgnOwned, out pfo))
         assets.PercentForeignOwned = Math.Round((double)pfo / 100, 2);
     Assets = new Dictionary<DateTime, FinancialAssets> { { li.RptDate, assets } };
 }
Example #14
0
 static double Distance(Tuple<int, int> coords1, Tuple<int, int> coords2)
 {
     return Math.Sqrt(
         (coords1.Item1 - coords2.Item1) * (coords1.Item1 - coords2.Item1) +
         (coords1.Item2 - coords2.Item2) * (coords1.Item2 - coords2.Item2)
     );
 }
        //
        // GET: /Home/
        public ActionResult Index(string sortOrder, int? page)
        {
            ViewBag.DateSortParm = string.IsNullOrEmpty(sortOrder) ? "date_desc" : "";
            ViewBag.CostSortParm = sortOrder == "Cost" ? "cost_desc" : "Cost";

            var products = WebApiHelper.GetProductsFromServer("api/product/all", Method.GET);

            switch (sortOrder)
            {
                case "date_desc":
                    products = products.OrderBy(s => s.Id).ToList();
                    break;
                case "Cost":
                    products = products.OrderBy(s => s.Price).ToList();
                    break;
                case "cost_desc":
                    products = products.OrderByDescending(s => s.Price).ToList();
                    break;
                default:
                    products = products.OrderByDescending(s => s.Id).ToList();
                    break;
            }

            int pageSize = 10;
            int pageNumber = (page ?? 1);

            IPagedList<DataTransferLayer.Products.Product> pl = products.ToPagedList(pageNumber, pageSize);

            var a = new Tuple<IPagedList<DataTransferLayer.Products.Product>, string>(pl, "");

            return View(a);
        }
Example #16
0
        public Dictionary<Tuple<int, string>, Tuple<string, string>> GetRatesData()
        {
            int count = 0;

            XmlNodeList nodeList = doc.DocumentElement.ChildNodes;

            foreach (XmlNode node in nodeList)
            {
                if (node.Name == "Cube")
                {
                    foreach (XmlNode node2 in node.ChildNodes)
                    {

                        foreach (XmlNode node3 in node2.ChildNodes)
                        {
                            count++;
                            var tuple = new Tuple<string, string>(node3.Attributes[0].Value, node3.Attributes[1].Value);
                            var tuple2 = new Tuple<int, string>(count, node2.Attributes[0].Value);
                            currencies.Add(tuple2, tuple);
                        }
                    }
                }
            }
            return currencies;

            //foreach(KeyValuePair<Tuple<int, string>, Tuple<string, string>> entry in currencies)
            //{
            //    Console.WriteLine(entry.Key.Item1 + " " + entry.Key.Item2 + " " + entry.Value.Item1 + " " + entry.Value.Item2);
            //}
        }
Example #17
0
 public Tuple<TokenType, string> Next()
 {
     EnsureToken();
     var cur = mCurrent;
     mCurrent = null;
     return cur;
 }
        private void OnKeyInputProcessed(object sender, Tuple<KeyInput, ProcessResult> tuple)
        {
            if (_ignoreNextKeyProcessedEvent)
            {
                _ignoreNextKeyProcessedEvent = false;
                return;
            }

            switch (_buffer.ModeKind)
            {
                case ModeKind.Command:
                    _margin.StatusLine = ":" + _buffer.CommandMode.Command;
                    break;
                case ModeKind.Normal:
                    {
                        var mode = _buffer.NormalMode;
                        var search = mode.IncrementalSearch;
                        if (search.InSearch && search.CurrentSearch.IsSome())
                        {
                            var data = search.CurrentSearch.Value;
                            _margin.StatusLine = "/" + data.Text.RawText;
                        }
                        else
                        {
                            _margin.StatusLine = mode.Command;
                        }
                    }
                    break;
                case ModeKind.Disabled:
                    _margin.StatusLine = _buffer.DisabledMode.HelpMessage;
                    break;
            }
        }
		/// <summary>
		/// Serializes the page parameter.
		/// </summary>
		public override object SerializeParameter(object parameter)
		{
			if (parameter.IsNull())
			{
				return null;
			}
			var parameterString = parameter as string;
			if (parameterString.IsNotNull())
			{
				return parameterString;
			}

			// Check for last object
			var last = this.lastObject;
			if (last.Item1 == parameter)
			{
				return last.Item2;
			}

			// Serialize object to json
			var sb = new StringBuilder();
			sb.Append((char)9);
			sb.Append(parameter.GetType().AssemblyQualifiedName);
			sb.Append((char)9);
			string data = JsonConvert.SerializeObject(parameter);
			sb.Append(data);
			parameterString = sb.ToString();

			// Save last object
			this.lastObject = new Tuple<object, string>(parameter, parameterString);

			return parameterString;
		}
Example #20
0
 public static List<Tuple<bool, string>> GetMessageTypes()
 {
     List<Tuple<bool, string>> ret = new List<Tuple<bool, string>>();
     XmlDocument doc = OpenXMLFile();
     XmlNodeList nodeList = doc.GetElementsByTagName("type");
     foreach (XmlNode node in nodeList)
     {
         bool multiLine = false;
         string messageType = string.Empty;
         for(int i = 0; i < node.ChildNodes.Count;i++)
         {
             XmlNode subNode = node.ChildNodes.Item(i);
             if (subNode.Name == "name")
             {
                 messageType = subNode.InnerText;
             }
             if (subNode.Name == "multiline")
             {
                 bool.TryParse(subNode.InnerText, out multiLine);
             }
         }
         Tuple<bool, string> tuple = new Tuple<bool, string>(multiLine, messageType);
         ret.Add(tuple);
     }
     return (ret);
 }
Example #21
0
 public override void addOpcode()
 {
     base.addOpcode();
     Tuple<ParameterType, ParameterType> tuple =
         new Tuple<ParameterType, ParameterType>(_param1.GetType(), _param2.GetType());
     _instruction += (opcodes[tuple]);
 }
        public string AddProduct(string name, double price, string producer)
        {
            Tuple<string, double, string> item = new Tuple<string, double, string>(name, price, producer);

            if (!names.ContainsKey(name))
            {
                names.Add(name, item);
            }
            else
            {
                names[name].Add(item);
            }

            if (!prices.ContainsKey(price))
            {
                prices.Add(price, item);
            }
            else
            {
                prices[price].Add(item);
            }

            if (!producers.ContainsKey(producer))
            {
                producers.Add(producer, item);
            }
            else
            {
                producers[producer].Add(item);
            }

            return "Product added";
        }
Example #23
0
        static void Main()
        {
            rows = int.Parse(Console.ReadLine());
            cols = int.Parse(Console.ReadLine());
            int startRow = int.Parse(Console.ReadLine());
            int startCol = int.Parse(Console.ReadLine());

            matrix = new int[rows, cols];
            matrix[startRow, startCol] = 1;
            var pointValue = new Dictionary<Tuple<int, int>, int>();
            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < cols; col++)
                {
                    var point = new Tuple<int, int>(row, col);
                    int value = matrix[row, col];
                    pointValue.Add(point, value);
                }
            }

            Console.WriteLine("Output:");
            var numbersOfMiddleColumn = VisitAllCells(pointValue, startRow, startCol);
            foreach (var number in numbersOfMiddleColumn)
            {
                Console.WriteLine(number);
            }

            //PrintMatrix();
        }
Example #24
0
        private void RunSelected_Click(object sender, RoutedEventArgs e)
        {
            int nbCases = 0;
            foreach (UnitTestSuite suite in Suites)
            {
                foreach (UnitTestCase c in suite.Cases)
                {
                    if (c.Selected) nbCases++;
                }
            }
            if (nbCases == 0) return;

            PrepareRun(nbCases);

            var tup = new Tuple<IEnumerable<UnitTestSuite>, bool?>(Suites, Verbose.IsChecked);
            var t = Task.Factory.StartNew(async (object parameters) =>
            {
                var p = parameters as Tuple<IEnumerable<UnitTestSuite>, bool?>;
                IEnumerable<UnitTestSuite> suites = p.Item1;
                bool verbose = p.Item2 != null ? (bool)p.Item2 : false;
                foreach (UnitTestSuite suite in suites)
                {
                    foreach (UnitTestCase c in suite.Cases)
                    {
                        if (c.Selected)
                        {
                            await RunUnitTestCase(c, verbose);
                        }
                    }
                }
            }, tup);
        }
Example #25
0
        public static int Main(string[] args)
        {
            List<string> pargs = ndclTools.ParamForm(args);
            if (pargs.FindParam("-h") || pargs.FindParam("--help"))
            {
                outputHelp();
                return 0;
            }
            int timeout;
            if (!getTimeout(pargs, out timeout))
                return 1;

            watch = new FileSystemWatcher();
            if(!getPath(pargs, watch))
                return 1;

            if (pargs.FindParam("-d"))
                watch.Deleted += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-c"))
                watch.Changed += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-C"))
                watch.Created += new FileSystemEventHandler(handler);
            if (!pargs.FindParam("-r"))
                watch.Renamed += new RenamedEventHandler(handler);
            watch.IncludeSubdirectories = pargs.FindParam("-s");

            last = new Tuple<string, DateTime>("", DateTime.Now);

            watch.EnableRaisingEvents = true;
            if (timeout == -1)
                while (Console.Read() != 'q') ;
            else
                System.Threading.Thread.Sleep(timeout);
            return 0;
        }
 public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken,
     string accessTokenSecret)
 {
     _tokens.Remove(requestToken);
     _tokens[accessToken] = new Tuple<string, TokenType>(accessTokenSecret, TokenType.AccessToken);
     _tokenRepository.Save(new Token(accessToken, accessTokenSecret));
 }
Example #27
0
        private void ProcessPublicBags(Random rand, Tuple<Player, int>[] dat)
        {
            var lootCount = PublicBag.BaseLootCount + PublicBag.PersonMultiplier*dat.Length;
            if (lootCount < PublicBag.MinLootCount) lootCount = PublicBag.MinLootCount;
            if (lootCount > PublicBag.MaxLootCount) lootCount = PublicBag.MaxLootCount;

            var loots = new HashSet<Item>();
            var pots = new List<Item>();
            for (var i = 0;
                i < lootCount ||
                (loots.Count < PublicBag.MinLootCount &&
                 pots.Count < PublicBag.MinLootCount);
                i++)
            {
                var loot = PublicBag.GetRandomLoot(rand);
                if (loot != null)
                {
                    if (loot.Potion)
                        pots.Add(loot);
                    else
                        loots.Add(loot);
                }
            }
            ShowBags(rand, loots.Concat(pots), null);
        }
Example #28
0
 public void AddSystemCallsAddToGame()
 {
     var result = new Tuple<string, IGame>(null, null);
     var system = new MockSystem((sys, action, game) => result = new Tuple<string, IGame>(action, (IGame) game));
     _game.AddSystem(system, 0);
     Assert.AreEqual(new Tuple<string, IGame>("added", _game), result);
 }
        public Task TestGetSession()
        {
            var response = new Tuple<HttpStatusCode, IDictionary<string, object>>(HttpStatusCode.Accepted,
              new Dictionary<string, object>() {
            { "__type", "Object" },
            { "className", "Session" },
            { "sessionToken", "S0m3Se551on" },
            { "restricted", true }
              });
              var mockRunner = CreateMockRunner(response);

              var controller = new ParseSessionController(mockRunner.Object);
              return controller.GetSessionAsync("S0m3Se551on", CancellationToken.None).ContinueWith(t => {
            Assert.False(t.IsFaulted);
            Assert.False(t.IsCanceled);
            mockRunner.Verify(obj => obj.RunCommandAsync(It.Is<ParseCommand>(command => command.Uri.AbsolutePath == "/1/sessions/me"),
              It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
              It.IsAny<IProgress<ParseDownloadProgressEventArgs>>(),
              It.IsAny<CancellationToken>()), Times.Exactly(1));

            var session = t.Result;
            Assert.AreEqual(2, session.Count());
            Assert.True((bool)session["restricted"]);
            Assert.AreEqual("S0m3Se551on", session["sessionToken"]);
              });
        }
Example #30
0
 public void DoubleMaxOnTwoTuple()
 {
     var sut = new Tuple<double, double>(1, 2);
       double expected = sut.AsEnumerable().Cast<double>().Max();
       double actual = sut.Max(x => (double) x);
       Assert.AreEqual(expected, actual);
 }