Пример #1
0
        public void FindsCorrectYear()
        {
            var People_1 = new TupleList <int, int>
            {
                { 1900, 2000 },
                { 1950, 2000 },
                { 1900, 1950 },
                { 1925, 1975 }
            };
            var People_2 = new TupleList <int, int>
            {
                { 1911, 1951 },
                { 1935, 1952 },
                { 1985, 1999 },
                { 1965, 1992 },
                { 1947, 1966 }
            };
            var actual_1   = FindYearWithMost(People_1);
            int expected_1 = 1950;
            var actual_2   = FindYearWithMost(People_2);
            int expected_2 = 1951;

            Assert.Equal(actual_1, expected_1);
            Assert.Equal(actual_2, expected_2);
        }
Пример #2
0
        public string Receipt(Format format)
        {
            var totalAmount = 0d;
            var reportLines = new TupleList<Line, string>();
            foreach (var line in _lines)
            {
                var thisAmount = 0d;
                thisAmount += CalculateAmountPlusDiscount(line.Bike, line.Quantity);
                reportLines.Add(line, thisAmount.ToString("C"));
                totalAmount += thisAmount;
            }
            var tax = totalAmount * TaxRate;

            var data = new ReceiptData(Company,
                                       totalAmount.ToString("C"),
                                       reportLines,
                                       tax.ToString("C"),
                                       (totalAmount + tax).ToString("C"));
            if (format == Format.Text)
                return new TextReceipt(data).TransformText();
            else if (format == Format.HTML)
                return new HtmlReceipt(data).TransformText();
            else if (format == Format.PDF)
            {
                return new PdfReceipt(data).TransformText();
            }
            else
                throw new Exception("Unsupported format type!");
        }
Пример #3
0
        public static Agent ChooseAgent()
        {
            Console.WriteLine("[1] Use custom seed.");
            Console.WriteLine("Press any other key to generate a seed.");
            int seed;

            if (Console.ReadKey().Key == ConsoleKey.D1)
            {
                Console.Clear();
                Console.WriteLine("Enter seed(signed int):");
                int.TryParse(Console.ReadLine(), out seed);
            }
            else
            {
                seed = new Random(Environment.TickCount).Next(0, int.MaxValue);
            }
            //Console.WriteLine(seed);
            game = new Game(5, 5, 20, seed);

            Console.WriteLine("[1] Player agent.");
            Console.WriteLine("[2] PeaceFullRandomAgent.");
            Console.WriteLine("[3] BloodthirstyAgent.");
            Console.WriteLine("[4] PrioritizeNewNodeAgent.");
            Console.WriteLine("[5] GoalAgent.");

            Agent agent;

            switch (Console.ReadKey().Key)
            {
            case ConsoleKey.D1:
                agent = new PlayerAgent(game);
                break;

            case ConsoleKey.D2:
                agent = new PeaceFullRandomAgent(game, seed);
                break;

            case ConsoleKey.D3:
                agent = new BloodthirstyAgent(game, seed);
                break;

            case ConsoleKey.D4:
                agent = new PrioritizeNewNodesAgent(game, seed);
                break;

            case ConsoleKey.D5:
                //TupleList<string, int> goals = new TupleList<string, int> { { "exit", 100 }};
                TupleList <string, int> goals = new TupleList <string, int> {
                    { "reachup", 3 }, { "reachdown", 1 }, { "kill", 4 }, { "exit", 0 }
                };
                agent = new GoalAgent(game, seed, goals);
                break;

            //other key
            default:
                agent = new PlayerAgent(game);
                break;
            }
            return(agent);
        }
Пример #4
0
        private void AssertAreObjectTypeDiffEqual(
            TupleList <ObjectClass, ObjectClass> expectedOcDiff,
            TupleList <ObjectClass, ObjectClass> actualOcDiff)
        {
            Assert.AreEqual(expectedOcDiff.Count, actualOcDiff.Count);
            for (int i = 0; i < expectedOcDiff.Count; i++)
            {
                ObjectClass expectedOc1 = expectedOcDiff[i].item1;
                ObjectClass expectedOc2 = expectedOcDiff[i].item2;
                ObjectClass actualOc1   = actualOcDiff[i].item1;
                ObjectClass actualOc2   = actualOcDiff[i].item2;

                if (expectedOc1 == null)
                {
                    Assert.IsNull(actualOc1);
                }
                else
                {
                    Assert.AreEqual(0, expectedOc1.FullCompareTo(actualOc1));
                }

                if (expectedOc2 == null)
                {
                    Assert.IsNull(actualOc2);
                }
                else
                {
                    Assert.AreEqual(0, expectedOc2.FullCompareTo(actualOc2));
                }
            }
        }
Пример #5
0
        void SetMenuItems()
        {
            //Set the name and callback function of the menu items
            menuItems = new TupleList <string, Func <bool> >
            {
                { new LocalizedString("STL").Translated, null },
                { new LocalizedString(" Import from Zip").Translated, importQueueFromZipMenu_Click },
                { new LocalizedString(" Export to Zip").Translated, exportQueueToZipMenu_Click },
                { new LocalizedString("GCode").Translated, null },
                { new LocalizedString(" Export to Folder").Translated, exportGCodeToFolderButton_Click },
                //{" Export to SD Card", exportToSDCardButton_Click},
                { new LocalizedString("Extra").Translated, null },
                { new LocalizedString(" Create Part Sheet").Translated, createPartsSheetsButton_Click },
            };

            BorderDouble padding = MenuDropList.MenuItemsPadding;

            //Add the menu items to the menu itself
            foreach (Tuple <string, Func <bool> > item in menuItems)
            {
                if (item.Item2 == null)
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                MenuDropList.AddItem(item.Item1);
            }

            MenuDropList.Padding = padding;
        }
        public void SubmitsTraces(string packageVersion)
        {
            int agentPort = TcpPortProvider.GetOpenPort();

            using (var agent = new MockTracerAgent(agentPort))
                using (var processResult = RunSampleAndWaitForExit(agent.Port, arguments: $"{TestPrefix}", packageVersion: packageVersion))
                {
                    Assert.True(processResult.ExitCode >= 0, $"Process exited with code {processResult.ExitCode}");

                    // note: ignore the INFO command because it's timing is unpredictable (on Linux?)
                    var spans = agent.WaitForSpans(11)
                                .Where(s => s.Type == "redis" && s.Resource != "INFO")
                                .OrderBy(s => s.Start)
                                .ToList();

                    var host = Environment.GetEnvironmentVariable("SERVICESTACK_REDIS_HOST") ?? "localhost:6379";
                    var port = host.Substring(host.IndexOf(':') + 1);
                    host = host.Substring(0, host.IndexOf(':'));

                    foreach (var span in spans)
                    {
                        Assert.Equal("redis.command", span.Name);
                        Assert.Equal("Samples.ServiceStack.Redis-redis", span.Service);
                        Assert.Equal(SpanTypes.Redis, span.Type);
                        Assert.Equal(host, span.Tags.GetValueOrDefault("out.host"));
                        Assert.Equal(port, span.Tags.GetValueOrDefault("out.port"));
                        Assert.False(span.Tags?.ContainsKey(Tags.Version), "External service span should not have service version tag.");
                    }

                    var expected = new TupleList <string, string>
                    {
                        { "ROLE", "ROLE" },
                        { "SET", $"SET {TestPrefix}ServiceStack.Redis.INCR 0" },
                        { "PING", "PING" },
                        { "DDCUSTOM", "DDCUSTOM COMMAND" },
                        { "ECHO", "ECHO Hello World" },
                        { "SLOWLOG", "SLOWLOG GET 5" },
                        { "INCR", $"INCR {TestPrefix}ServiceStack.Redis.INCR" },
                        { "INCRBYFLOAT", $"INCRBYFLOAT {TestPrefix}ServiceStack.Redis.INCR 1.25" },
                        { "TIME", "TIME" },
                        { "SELECT", "SELECT 0" },
                    };

                    for (int i = 0; i < expected.Count; i++)
                    {
                        var e1 = expected[i].Item1;
                        var e2 = expected[i].Item2;

                        var a1 = i < spans.Count
                                 ? spans[i].Resource
                                 : string.Empty;
                        var a2 = i < spans.Count
                                 ? spans[i].Tags.GetValueOrDefault("redis.raw_command")
                                 : string.Empty;

                        Assert.True(e1 == a1, $@"invalid resource name for span #{i}, expected ""{e1}"", actual ""{a1}""");
                        Assert.True(e2 == a2, $@"invalid raw command for span #{i}, expected ""{e2}"" != ""{a2}""");
                    }
                }
        }
Пример #7
0
        private void SetMenuItems(DropDownMenu dropDownMenu)
        {
            menuItems = new TupleList <string, Func <bool> >();

            if (ActiveTheme.Instance.IsTouchScreen)
            {
                menuItems.Add(new Tuple <string, Func <bool> >("Remove All".Localize(), clearAllMenu_Select));
            }

            menuItems.Add(new Tuple <string, Func <bool> >("Send".Localize(), sendMenu_Selected));
            menuItems.Add(new Tuple <string, Func <bool> >("Add To Library".Localize(), addToLibraryMenu_Selected));

            BorderDouble padding = dropDownMenu.MenuItemsPadding;

            //Add the menu items to the menu itself
            foreach (Tuple <string, Func <bool> > item in menuItems)
            {
                if (item.Item2 == null)
                {
                    dropDownMenu.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    dropDownMenu.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                dropDownMenu.AddItem(item.Item1);
            }

            dropDownMenu.Padding = padding;
        }
Пример #8
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var incomingBitrate = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.IncomingBitrateMetricName, StringComparison.OrdinalIgnoreCase));

            if (incomingBitrate != null)
            {
                var encodedBitrate = telemetryTuples.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.EncodedBitrateMetricName, StringComparison.OrdinalIgnoreCase));
                if (encodedBitrate != null)
                {
                    var currentIncomingBitrateValue = incomingBitrate.Value;
                    var currentEncodedBitrateValue  = encodedBitrate.Value;

                    decimal value = (currentIncomingBitrateValue == 0) ? 0 : 1;
                    if (currentEncodedBitrateValue != 0)
                    {
                        value = Math.Round(Math.Abs(1 - (currentIncomingBitrateValue / currentEncodedBitrateValue)), 3);
                    }

                    var newMetric = new Tuple <decimal, Metric>(
                        value,
                        BitrateRatioMetric);

                    result.Add(newMetric);
                }
            }

            return(result);
        }
Пример #9
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var totalRequestRate = telemetryTuples
                                   .Where(t => t.MetricName.Equals(MetricConstants.TotalRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                   .Select(
                t =>
            {
                var newMetric = new Tuple <decimal, Metric>(
                    Math.Round((t.Value * 60) / monitoringIntervalInSeconds, 3),
                    TotalRequestsRateMetric);

                return(newMetric);
            });

            result.AddRange(totalRequestRate);

            var failedRequestRate = telemetryTuples
                                    .Where(t => t.MetricName.Equals(MetricConstants.FailedRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                    .Select(
                t =>
            {
                var newMetric = new Tuple <decimal, Metric>(
                    Math.Round((t.Value * 60) / monitoringIntervalInSeconds, 3),
                    FailedRequestsRateMetric);

                return(newMetric);
            });

            result.AddRange(failedRequestRate);

            return(result);
        }
Пример #10
0
		public MenuBase(string menuName)
		{
			MenuDropList = new DropDownMenu(menuName.ToUpper(), Direction.Down, pointSize: 10);
			MenuDropList.MenuItemsPadding = new BorderDouble(0);
			MenuDropList.Margin = new BorderDouble(0);
			MenuDropList.Padding = new BorderDouble(0);

			MenuDropList.DrawDirectionalArrow = false;
			MenuDropList.MenuAsWideAsItems = false;

			menuItems = GetMenuItems();
			BorderDouble padding = MenuDropList.MenuItemsPadding;
			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in menuItems)
			{
				MenuDropList.MenuItemsPadding = new BorderDouble(8, 4, 8, 4) * TextWidget.GlobalPointSizeScaleRatio;
				MenuDropList.AddItem(item.Item1, pointSize: 10);
			}
			MenuDropList.Padding = padding;


			AddChild(MenuDropList);
			this.Width = GetChildrenBoundsIncludingMargins().Width;
			this.Height = 22 * TextWidget.GlobalPointSizeScaleRatio;
			this.Margin = new BorderDouble(0);
			this.Padding = new BorderDouble(0);
			this.VAnchor = Agg.UI.VAnchor.ParentCenter;
			this.MenuDropList.SelectionChanged += new EventHandler(MenuDropList_SelectionChanged);
			this.MenuDropList.OpenOffset = new Vector2(0, 0);
		}
Пример #11
0
        private static void RunCommands(TupleList <string, Func <object> > commands)
        {
            foreach (var cmd in commands)
            {
                var f = cmd.Item2;
                if (f == null)
                {
                    continue;
                }

                object result;
                try
                {
                    result = f();
                }
                catch (Exception e)
                {
                    while (e.InnerException != null)
                    {
                        e = e.InnerException;
                    }
                    result = e.Message;
                }

                if (result is Task task)
                {
                    result = TaskResult(task);
                }

                Console.WriteLine($"{cmd.Item1}: {result}");
            }
        }
Пример #12
0
        public static int FindYearWithMost(TupleList <int, int> people)
        {
            //takes a TupleList of birth and end years of people between 1900 and 2000 and returns the year with the most people
            //creates a dictionary with a key for each year from 1900 to 2000 with all the values set to 0
            Dictionary <int, int> Years = new Dictionary <int, int>();

            for (int year = 1900; year <= 2000; year++)
            {
                Years.Add(year, 0);
            }
            //goes through each tuple in people
            foreach (var person in people)
            {
                //for each set of years it increments the value of each year from their birth year to their end year in the Years dictionary by 1
                for (int year = person.Item1; year <= person.Item2; year++)
                {
                    Years[year]++;
                }
            }
            //a line of code i found online
            //uses the aggregate method to find the key of the max value in the Years dictionary
            int YearWithMost = Years.Aggregate((x, y) => x.Value > y.Value ? x : y).Key;

            return(YearWithMost);
        }
Пример #13
0
        private static Dictionary <int, TupleList <long, short> > ReadWordModel(string inFile)
        {
            using (BinaryReader brWordMap = new BinaryReader(File.OpenRead(inFile)))
            {
                Dictionary <int, TupleList <long, short> > model = new Dictionary <int, TupleList <long, short> >();

                int numWords = brWordMap.ReadInt32();

                for (int i = 0; i < numWords; i++)
                {
                    int wordIdx     = brWordMap.ReadInt32();
                    int numSegments = brWordMap.ReadInt32();

                    TupleList <long, short> segmentInfo = new TupleList <long, short>();
                    for (int j = 0; j < numSegments; j++)
                    {
                        long  offset   = brWordMap.ReadInt64();
                        short location = brWordMap.ReadInt16();
                        segmentInfo.Add(offset, location);
                    }
                    model.Add(wordIdx, segmentInfo);
                }

                return(model);
            }
        }
Пример #14
0
        private void AssertAreAttributeTypeDiffEqual(
            TupleList <AttributeType, AttributeType> expectedAtDiff,
            TupleList <AttributeType, AttributeType> actualAtDiff)
        {
            Assert.AreEqual(expectedAtDiff.Count, actualAtDiff.Count);
            for (int i = 0; i < expectedAtDiff.Count; i++)
            {
                AttributeType expectedAt1 = expectedAtDiff[i].item1;
                AttributeType expectedAt2 = expectedAtDiff[i].item2;
                AttributeType actualAt1   = actualAtDiff[i].item1;
                AttributeType actualAt2   = actualAtDiff[i].item2;

                if (expectedAt1 == null)
                {
                    Assert.IsNull(actualAt1);
                }
                else
                {
                    Assert.AreEqual(0, expectedAt1.FullCompareTo(actualAt1));
                }

                if (expectedAt2 == null)
                {
                    Assert.IsNull(actualAt2);
                }
                else
                {
                    Assert.AreEqual(0, expectedAt2.FullCompareTo(actualAt2));
                }
            }
        }
Пример #15
0
        public override float GetOutput(TupleList <float, float> inputs)
        {
            float  sum = inputs.WeightedSum();
            double x   = coefficients['x'].coValue;

            return((float)Math.Sqrt(sum * x));
        }
Пример #16
0
        private TupleList <TCurrent, Metric> GenerateMetrics <TCurrent>(
            MetricType type,
            List <TCurrent> telemetry,
            Func <string, DateTime, Metric, decimal, TCurrent> createNewMetric)
            where TCurrent : ITelemetry
        {
            var calculatedMetrics  = new TupleList <TCurrent, Metric>();
            var filteredStrategies = strategies.Where(s => s.Type == type).ToArray();

            var telemetryGroups = telemetry.GroupBy(t => t.GroupId);

            foreach (var telemetryGroup in telemetryGroups)
            {
                var allMetrics = telemetryGroup.ToList();
                var timestamp  = allMetrics.First().Timestamp;
                foreach (var strategy in filteredStrategies)
                {
                    var newMetricValueTuples = strategy.CalculateMetrics(allMetrics);
                    var newMetrics           = newMetricValueTuples.Select(
                        nmvt => new Tuple <TCurrent, Metric>(
                            createNewMetric(telemetryGroup.Key, timestamp, nmvt.Item2, nmvt.Item1),
                            nmvt.Item2));

                    allMetrics.AddRange(newMetrics.Select(nmvt => nmvt.Item1));
                    calculatedMetrics.AddRange(newMetrics);
                }
            }

            return(calculatedMetrics);
        }
Пример #17
0
        public void GetDiffTest()
        {
            SchemaComparableList <TestSchemaComparable> scList1 =
                new SchemaComparableList <TestSchemaComparable>(testList1);

            SchemaComparableList <TestSchemaComparable> scList2 =
                new SchemaComparableList <TestSchemaComparable>(testList2);

            TupleList <TestSchemaComparable, TestSchemaComparable> diff = scList1.GetDiff(scList2);

            Assert.AreEqual("C-CCC", diff[0].Item1.full);
            Assert.AreEqual("C-CC", diff[0].Item2.full);

            Assert.AreEqual("D-DDD", diff[1].Item1.full);
            Assert.AreEqual("D-DD", diff[1].Item2.full);

            Assert.IsNull(diff[2].Item1);
            Assert.AreEqual("E-EEE", diff[2].Item2.full);

            Assert.AreEqual("F-FFF", diff[3].Item1.full);
            Assert.IsNull(diff[3].Item2);

            Assert.AreEqual("G-GGG", diff[4].Item1.full);
            Assert.IsNull(diff[4].Item2);
        }
Пример #18
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetryTuples)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var totalRequests = telemetryTuples
                                .Where(t => t.MetricName.Equals(MetricConstants.TotalRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                .Sum(t => t.Value);

            var totalRequestRatio = new Tuple <decimal, Metric>(100m, TotalRequestsRatioMetric);

            result.Add(totalRequestRatio);

            var failedRequests = telemetryTuples
                                 .Where(t => t.MetricName.Equals(MetricConstants.FailedRequestsMetricName, StringComparison.OrdinalIgnoreCase))
                                 .Sum(t => t.Value);

            decimal failedRequestsRatio = 0m;

            if (totalRequests != 0)
            {
                failedRequestsRatio = Math.Round(failedRequests * 100 / totalRequests, 3);
            }
            result.Add(new Tuple <decimal, Metric>(failedRequestsRatio, FailedRequestsRatioMetric));

            return(result);
        }
Пример #19
0
        public void AreWithinSameIntervalTest()
        {
            var referenceDT = new DateTime(2011, 1, 1, 1, 0, 0);
            var testDTs     =
                new TupleList <DateTime, bool[]>
            {
                // DateTime To Test                         Interval:    Day   Hour  Min   Sec
                { new DateTime(2011, 1, 1, 1, 0, 0, 999), new[] { true, true, true, true } },
                { new DateTime(2011, 1, 1, 1, 0, 1), new[] { true, true, true, false } },
                { new DateTime(2011, 1, 1, 1, 0, 59), new[] { true, true, true, false } },
                { new DateTime(2011, 1, 1, 1, 1, 0), new[] { true, true, false, false } },
                { new DateTime(2011, 1, 1, 1, 59, 59), new[] { true, true, false, false } },
                { new DateTime(2011, 1, 1, 2, 0, 0), new[] { true, false, false, false } },
                { new DateTime(2011, 1, 1, 23, 59, 59), new[] { true, false, false, false } },
                { new DateTime(2011, 1, 2, 0, 0, 0), new[] { false, false, false, false } },
            };

            foreach (var test in testDTs)
            {
                int boolIndex = 0;
                foreach (var interval in new[] { Interval.Day, Interval.Hour, Interval.Minute, Interval.Second })
                {
                    Assert.AreEqual(test.Item2[boolIndex++], interval.AreWithinSameInterval(referenceDT, test.Item1));
                }
            }
        }
Пример #20
0
        private DropDownMenu GetSliceOptionsMenuDropList()
        {
            if (sliceOptionsMenuDropList == null)
            {
                sliceOptionsMenuDropList = new DropDownMenu("Options".Localize() + "... ")
                {
                    HoverColor        = new RGBA_Bytes(0, 0, 0, 50),
                    NormalColor       = new RGBA_Bytes(0, 0, 0, 0),
                    BorderColor       = new RGBA_Bytes(ActiveTheme.Instance.SecondaryTextColor, 100),
                    BackgroundColor   = new RGBA_Bytes(0, 0, 0, 0),
                    BorderWidth       = 1,
                    MenuAsWideAsItems = false,
                    AlignToRightEdge  = true,
                };
                sliceOptionsMenuDropList.VAnchor          |= VAnchor.ParentCenter;
                sliceOptionsMenuDropList.SelectionChanged += new EventHandler(MenuDropList_SelectionChanged);

                //Set the name and callback function of the menu items
                slicerOptionsMenuItems = new TupleList <string, Func <bool> >
                {
                    { "Import".Localize(), ImportSettingsMenu_Click },
                    { "Export".Localize(), () => { WizardWindow.Show <ExportSettingsPage>("ExportSettingsPage", "Export Settings"); return(true); } },
                    { "Settings History".Localize(), () => { WizardWindow.Show <PrinterProfileHistoryPage>("PrinterProfileHistory", "Profile History"); return(true); } },
                    { "Reset to defaults".Localize(), () => { UiThread.RunOnIdle(ResetToDefaults); return(true); } },
                };

                //Add the menu items to the menu itself
                foreach (Tuple <string, Func <bool> > item in slicerOptionsMenuItems)
                {
                    sliceOptionsMenuDropList.AddItem(item.Item1);
                }
            }

            return(sliceOptionsMenuDropList);
        }
Пример #21
0
        private void EventPublisher_ManipulatorChanged(object sender, ManipulatorEventArgs e)
        {
            // Visual indication of current manipulator
            var manipulators = new TupleList <ManipulatorManagerTypes, ToolStripButton>
            {
                { ManipulatorManagerTypes.Default, ToolStripDefaultManipulator },
                { ManipulatorManagerTypes.Polygon, ToolStripPolygonManipulator },
                { ManipulatorManagerTypes.Attack, ToolStripAttackManipulator }
            };

            foreach (var manipulator in manipulators)
            {
                manipulator.Item2.Checked = manipulator.Item1 == e.ManipulatorType;
            }

            var manipulators2 = new TupleList <ManipulatorManagerTypes, ToolStripMenuItem>
            {
                { ManipulatorManagerTypes.Default, MenuMapInteractionDefault },
                { ManipulatorManagerTypes.Polygon, MenuMapInteractionPolygon },
                { ManipulatorManagerTypes.Attack, MenuMapInteractionPlanAttacks }
            };

            foreach (var manipulator in manipulators2)
            {
                manipulator.Item2.Checked = manipulator.Item1 == e.ManipulatorType;
            }

            if (e.ManipulatorType == ManipulatorManagerTypes.Attack)
            {
                var pane = GetNavigationPane(NavigationPanes.Attack);
                LeftNavigation.SelectNavigationPage(pane.Key);
            }
        }
Пример #22
0
        private void AssertAreMetadataEqual(
            TupleList <AttributeMetadata, AttributeMetadata> expectedMdDiff,
            TupleList <AttributeMetadata, AttributeMetadata> actualMdDiff)
        {
            Assert.AreEqual(expectedMdDiff.Count, actualMdDiff.Count);
            for (int i = 0; i < expectedMdDiff.Count; i++)
            {
                AttributeMetadata expectedMd1 = expectedMdDiff[i].item1;
                AttributeMetadata expectedMd2 = expectedMdDiff[i].item2;
                AttributeMetadata actualMd1   = actualMdDiff[i].item1;
                AttributeMetadata actualMd2   = actualMdDiff[i].item2;

                if (expectedMd1 == null)
                {
                    Assert.IsNull(actualMd1);
                }
                else
                {
                    Assert.AreEqual(0, expectedMd1.FullCompareTo(actualMd1));
                }

                if (expectedMd2 == null)
                {
                    Assert.IsNull(actualMd2);
                }
                else
                {
                    Assert.AreEqual(0, expectedMd2.FullCompareTo(actualMd2));
                }
            }
        }
Пример #23
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetry)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();


            var totalRequests = telemetry.FirstOrDefault(t => t.MetricName.Equals(MetricConstants.TotalRequestsMetricName, StringComparison.OrdinalIgnoreCase));

            if (totalRequests != null)
            {
                var totalRequestsCount = totalRequests.Value;

                result.AddRange(
                    telemetry
                    .Where(t => Regex.IsMatch(t.MetricName, MetricConstants.HttpStatusCodeReqeustsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
                    .Select(
                        t =>
                {
                    decimal value = 0;
                    if (totalRequestsCount != 0)
                    {
                        value = Math.Round(t.Value * 100 / totalRequestsCount, 3);
                    }

                    var newMetric = new Tuple <decimal, Metric>(
                        value,
                        GetHttpStatusCodeRatioMetric(t.MetricName));

                    return(newMetric);
                }));
            }

            return(result);
        }
Пример #24
0
        public void GetAllSchemaDefinitionDiffsTest()
        {
            TupleList <AttributeType, AttributeType> expectedAtDiff = new TupleList <AttributeType, AttributeType>()
            {
                new Tuple <AttributeType, AttributeType>(
                    new AttributeType("( 2.5.18.4 NAME 'modifiersName' DESC 'RFC4512: name of last modifier' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 NO-USER-MODIFICATION USAGE directoryOperation )"),
                    new AttributeType("( 2.5.18.4 NAME 'modifiersName' DESC 'RFC4512: name of last modifier' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )")),
                new Tuple <AttributeType, AttributeType>(
                    new AttributeType("( VMWare.DIR.attribute.999.11 NAME 'serverIdASDASDASD' DESC 'An ID used in SID allocation relative to this server' SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )"),
                    null)
            };
            TupleList <ObjectClass, ObjectClass> expectedOcDiff = new TupleList <ObjectClass, ObjectClass>()
            {
                new Tuple <ObjectClass, ObjectClass>(
                    new ObjectClass("( VMWare.tagging.objectclass.3 NAME 'ASDFASDFASDF' DESC 'VMware CIS - tagging service tag' SUP top KIND-UNKNOWN MUST ( cn $ serverIdASDASDASD $ vmwTaggingTagName $ vmwTaggingTagVersion ) MAY ( vmwTaggingObjectState $ vmwTaggingTagDescription $ vmwTaggingTagUsedBy ) )"),
                    null),
                new Tuple <ObjectClass, ObjectClass>(
                    new ObjectClass("( VMWare.CA.objectclass.1 NAME 'vmwCertificationAuthority' SUP top STRUCTURAL AUX ( ASDFASDFASDF $ pkiCA ) MUST cn MAY cACertificateDN )"),
                    new ObjectClass("( VMWare.CA.objectclass.1 NAME 'vmwCertificationAuthority' SUP top STRUCTURAL AUX pkiCA MUST cn MAY cACertificateDN )")),
                new Tuple <ObjectClass, ObjectClass>(
                    new ObjectClass("( VMWare.tagging.objectclass.3 NAME 'vmwTaggingTagModel' DESC 'VMware CIS - tagging service tag' SUP top STRUCTURAL MUST ( cn $ vmwTaggingTagName $ vmwTaggingTagVersion ) MAY ( priorValue $ vmwTaggingAuthzUri $ vmwTaggingObjectState $ vmwTaggingTagDescription $ vmwTaggingTagUsedBy ) )"),
                    new ObjectClass("( VMWare.tagging.objectclass.3 NAME 'vmwTaggingTagModel' DESC 'VMware CIS - tagging service tag' SUP top STRUCTURAL MUST ( cn $ vmwTaggingTagName $ vmwTaggingTagVersion ) MAY ( vmwTaggingObjectState $ vmwTaggingTagDescription $ vmwTaggingTagUsedBy ) )"))
            };

            IDictionary <String, SchemaDefinitionDiff> diffs        = conn.GetAllSchemaDefinitionDiffs();
            TupleList <AttributeType, AttributeType>   actualAtDiff = diffs[host2].GetAttributeTypeDiff();
            TupleList <ObjectClass, ObjectClass>       actualOcDiff = diffs[host2].GetObjectClassDiff();

            AssertAreAttributeTypeDiffEqual(expectedAtDiff, actualAtDiff);
            AssertAreObjectTypeDiffEqual(expectedOcDiff, actualOcDiff);
            Assert.IsNull(diffs[host3]);
        }
Пример #25
0
        public TupleList <decimal, Metric> CalculateMetrics <TCurrent>(List <TCurrent> telemetry)
            where TCurrent : ITelemetry
        {
            var result = new TupleList <decimal, Metric>();

            var errorRequestCounts = telemetry.Where(t =>
                                                     Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsRatioMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                                     !t.MetricName.Equals(MetricConstants.Http412MetricName, StringComparison.OrdinalIgnoreCase))
                                     .ToArray();
            decimal failedRequestCount     = 0;
            decimal failedRequestBytesSent = 0;

            if (errorRequestCounts.Length > 0)
            {
                failedRequestCount = errorRequestCounts.Sum(t => t.Value);
            }

            var errorRequestBytes = telemetry.Where(t =>
                                                    Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                                    t.MetricName.EndsWith(MetricConstants.HttpStatusCodeBytesSentMetricNameSuffix, StringComparison.OrdinalIgnoreCase) &&
                                                    !t.MetricName.Equals(MetricConstants.Http412MetricName + MetricConstants.HttpStatusCodeBytesSentMetricNameSuffix, StringComparison.OrdinalIgnoreCase))
                                    .ToArray();

            if (errorRequestBytes.Length > 0)
            {
                failedRequestBytesSent = errorRequestBytes.Sum(t => t.Value);
            }

            var newMetric = new Tuple <decimal, Metric>(failedRequestCount, FailedRequestsMetric);

            result.Add(newMetric);
            result.Add(new Tuple <decimal, Metric>(failedRequestBytesSent, FailedRequestsBytesSentMetric));

            // get the weighted server and e2e latency.
            var requestTimes = telemetry.Where(t =>
                                               Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                               t.MetricName.EndsWith(MetricConstants.HttpStatusCodeServerLatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase) &&
                                               !t.MetricName.Equals(MetricConstants.Http412MetricName + MetricConstants.HttpStatusCodeServerLatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var serverLatency = errorRequestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            if (failedRequestCount > 0)
            {
                serverLatency = Math.Round(serverLatency / failedRequestCount, 3);
            }
            result.Add(new Tuple <decimal, Metric>(serverLatency, ServerLatencyMetric));

            requestTimes = telemetry.Where(t =>
                                           Regex.IsMatch(t.MetricName, MetricConstants.FailedRequestsMetricRegularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) &&
                                           t.MetricName.EndsWith(MetricConstants.HttpStatusCodeE2ELatencyMetricNameSuffix, StringComparison.OrdinalIgnoreCase));
            var e2eLatency = errorRequestCounts.Zip(requestTimes, (m1, m2) => m1.Value * m2.Value).Sum();

            if (failedRequestCount > 0)
            {
                e2eLatency = Math.Round(e2eLatency / failedRequestCount, 3);
            }
            result.Add(new Tuple <decimal, Metric>(e2eLatency, E2ELatencyMetric));

            return(result);
        }
Пример #26
0
 public Store(string _Name, TupleList <Vector3, float> _ShopKeeperSpawnData, TupleList <Vector3, float> _RobberSpawnData, TupleList <Vector3, float> _ShopliftingSecuritySpawnData, TupleList <Vector3, float> _ShopliftingOffenderSpawnData)
 {
     this.Name = _Name;
     this.ShopKeeperSpawnData          = _ShopKeeperSpawnData;
     this.RobberSpawnData              = _RobberSpawnData;
     this.ShopliftingSecuritySpawnData = _ShopliftingSecuritySpawnData;
     this.ShopliftingOffenderSpawnData = _ShopliftingOffenderSpawnData;
 }
Пример #27
0
        public override float GetOutput(TupleList <float, float> inputs)
        {
            double a = coefficients['a'].coValue;
            double b = coefficients['b'].coValue;
            float  x = inputs.WeightedSum();

            return((float)(a * x + b));
        }
Пример #28
0
        public static void Train(string outModelFilePattern, string trainingFile, int modelVersion, int minGram, int maxGram, AccentConverter converter, bool learnKnownWordsOnly = true)
        {
            TupleList <string, string> files = new TupleList <string, string>
            {
                { Path.GetDirectoryName(trainingFile), Path.GetFileName(trainingFile) }
            };

            Train(outModelFilePattern, files, modelVersion, minGram, maxGram, converter, learnKnownWordsOnly);
        }
Пример #29
0
 public SchemaMetadataDiff(
     SchemaComparableList <SchemaEntry> baseAtEntries,
     SchemaComparableList <SchemaEntry> baseOcEntries,
     SchemaComparableList <SchemaEntry> otherAtEntries,
     SchemaComparableList <SchemaEntry> otherOcEntries)
 {
     attributeTypeDiff = baseAtEntries.GetDiff(otherAtEntries);
     objectClassDiff   = baseOcEntries.GetDiff(otherOcEntries);
 }
		private void SetMenuItems()
		{
			menuItems = new TupleList<string, Func<bool>>();

#if !__ANDROID__
			menuItems.Add(new Tuple<string, Func<bool>>("Design".Localize(), null));
			menuItems.Add(new Tuple<string, Func<bool>>(" Export to Zip".Localize(), exportQueueToZipMenu_Click));
			menuItems.Add(new Tuple<string, Func<bool>>("G-Code".Localize(), null));
			menuItems.Add(new Tuple<string, Func<bool>>(" Export to Folder or SD Card".Localize(), exportGCodeToFolderButton_Click));
			//menuItems.Add(new Tuple<string, Func<bool>>("X3G", null));
			//menuItems.Add(new Tuple<string, Func<bool>>("Export to Folder".Localize(), exportX3GButton_Click));
#endif

			if (ActiveSliceSettings.Instance.GetValue<bool>(SettingsKey.has_sd_card_reader))
			{
				menuItems.Add(new Tuple<string, Func<bool>>("SD Card", null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Load Files".Localize(), loadFilesFromSDButton_Click));
				menuItems.Add(new Tuple<string, Func<bool>>(" Eject SD Card".Localize(), ejectSDCardButton_Click));
			}

			// The pdf export library is not working on the mac at the moment so we don't include the
			// part sheet export option on mac.
			if (OsInformation.OperatingSystem == OSType.Windows)
			{
				menuItems.Add(new Tuple<string, Func<bool>>("Other".Localize(), null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Create Part Sheet".Localize(), createPartsSheetsButton_Click));
				menuItems.Add(new Tuple<string, Func<bool>>(" Remove All".Localize(), removeAllFromQueueButton_Click));
			}
			else
			{
				// mac cannot export to pdf
				menuItems.Add(new Tuple<string, Func<bool>>("Other".Localize(), null));
				menuItems.Add(new Tuple<string, Func<bool>>(" Remove All".Localize(), removeAllFromQueueButton_Click));
			}

			BorderDouble padding = MenuDropList.MenuItemsPadding;
			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in menuItems)
			{
				if (item.Item2 == null)
				{
					MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
				}
				else
				{
					MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
				}

				MenuItem menuItem = MenuDropList.AddItem(item.Item1);
				if(item.Item2 == null)
				{
					menuItem.Enabled = false;
				}
			}

			MenuDropList.Padding = padding;
		}
Пример #31
0
        private void SetMenuItems()
        {
            menuItems = new TupleList <string, Func <bool> >();

#if !__ANDROID__
            menuItems.Add(new Tuple <string, Func <bool> >("Design".Localize(), null));
            menuItems.Add(new Tuple <string, Func <bool> >(" Export to Zip".Localize(), exportQueueToZipMenu_Click));
            menuItems.Add(new Tuple <string, Func <bool> >("G-Code".Localize(), null));
            menuItems.Add(new Tuple <string, Func <bool> >(" Export to Folder or SD Card".Localize(), exportGCodeToFolderButton_Click));
            //menuItems.Add(new Tuple<string, Func<bool>>("X3G", null));
            //menuItems.Add(new Tuple<string, Func<bool>>("Export to Folder".Localize(), exportX3GButton_Click));
#endif

            if (ActiveSliceSettings.Instance.GetValue <bool>(SettingsKey.has_sd_card_reader))
            {
                menuItems.Add(new Tuple <string, Func <bool> >("SD Card".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Load Files".Localize(), loadFilesFromSDButton_Click));
                menuItems.Add(new Tuple <string, Func <bool> >(" Eject SD Card".Localize(), ejectSDCardButton_Click));
            }

            // The pdf export library is not working on the mac at the moment so we don't include the
            // part sheet export option on mac.
            if (OsInformation.OperatingSystem == OSType.Windows)
            {
                menuItems.Add(new Tuple <string, Func <bool> >("Other".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Create Part Sheet".Localize(), createPartsSheetsButton_Click));
                menuItems.Add(new Tuple <string, Func <bool> >(" Remove All".Localize(), removeAllFromQueueButton_Click));
            }
            else
            {
                // mac cannot export to pdf
                menuItems.Add(new Tuple <string, Func <bool> >("Other".Localize(), null));
                menuItems.Add(new Tuple <string, Func <bool> >(" Remove All".Localize(), removeAllFromQueueButton_Click));
            }

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple <string, Func <bool> > item in menuItems)
            {
                if (item.Item2 == null)
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                MenuItem menuItem = MenuDropList.AddItem(item.Item1);
                if (item.Item2 == null)
                {
                    menuItem.Enabled = false;
                }
            }

            MenuDropList.Padding = padding;
        }
Пример #32
0
        public override float GetOutput(TupleList <float, float> inputs)
        {
            float sum = inputs.WeightedSum();
            float x   = 1.0f;
            float y   = .0f;
            float mod = 1.0f;

            return((x * sum + y) % mod);
        }
Пример #33
0
    private static List <string> alternatePhonetics(string system)
    {
        TupleList <string, string, bool> substitutions = new TupleList <string, string, bool>
        {
            { @"(^| )([A-Z])([A-Z][ +-])", @"$1$2 $3", false },
            { @" *\+ *", @" ", true },
            { @" *\+ *", @" + ", false },
            { @"([a-z])-", @"$1 ", false },
            { @" *- *", @" ", true },
            { @" *- *", @" - ", false },

            { @"\. ", @" ", false },

            { @"([A-Za-z])([0-9])", @"$1 $2", false },
            { @"([0-9])([A-Za-z])", @"$1 $2", false },

            { @"^A([a-z] )", @"A $1", true },
            { @"\bD([jxz])", @"$1", true },
            { @"\bHs", @"S", true },
            { @"\bKv", @"Kev", true },
            { @"\bMb", @"Emb", true },
            { @"mii\b", @"mee", true },
            { @"\bN([dgj])", @"En$1", true },
            { @"\bNg", @"N", true },
            { @"\bNj", @"Y", true },
            { @"\bPsa", @"Sa", true },
            { @"\bPt", @"Pet", true },
            { @"\bT([cjpz])", @"$1", true },
            { @"\bTl", @"Tel", true },
            { @"\bXpi", @"Spee", true },
            { @"\bZm", @"Zem", true },
        };
        List <string> alternates = new List <string>();

        foreach (Tuple <string, string, bool> rule in substitutions)
        {
            string search    = rule.Item1;
            string replace   = rule.Item2;
            bool   addPhrase = rule.Item3;
            Regex  rgx       = new Regex(search);
            string result    = rgx.Replace(system, replace);
            if (system != result)
            {
                if (addPhrase)
                {
                    alternates.Add(result);
                }
                else
                {
                    system = result;
                }
            }
        }
        alternates.Add(system);
        return(alternates);
    }
Пример #34
0
 public void MergeSort(TupleList<Vector2, float> listToSort, int begin, int end)
 {
     if (begin < end)
     {
         int mid = (end + begin) / 2;
         MergeSort(listToSort, begin, mid);
         MergeSort(listToSort, mid + 1, end);
         Merge(listToSort, begin, end, mid);
     }
 }
 public ReceiptData(string company,
     string totalAmount,
     TupleList<Line, string> reportLines,
     string tax,
     string total)
 {
     this.company = company;
     this.totalAmount = totalAmount;
     this.reportLines = reportLines;
     this.tax = tax;
     this.total = total;
 }
		public DynamicDropDownMenu(GuiWidget buttonView, Direction direction = Direction.Down, double pointSize = 12)
			: base(buttonView, direction, pointSize)
		{
			menuItems = new TupleList<string, Func<bool>>();
			TextColor = RGBA_Bytes.Black;
			NormalArrowColor = RGBA_Bytes.Black;
			HoverArrowColor = RGBA_Bytes.Black;

			BorderWidth = 1;
			BorderColor = new RGBA_Bytes(ActiveTheme.Instance.PrimaryTextColor, 200);

			this.SelectionChanged += new EventHandler(AltChoices_SelectionChanged);
		}
Пример #37
0
        void SetMenuItems()
        {
            // The pdf export library is not working on the mac at the moment so we don't include the 
            // part sheet export option on mac.
            if (MatterHackers.Agg.UI.WindowsFormsAbstract.GetOSType() == WindowsFormsAbstract.OSType.Mac)
            {
                //Set the name and callback function of the menu items
                menuItems = new TupleList<string, Func<bool>> 
                {
                {"STL", null},
                {new LocalizedString(" Import from Zip").Translated, importQueueFromZipMenu_Click},
                {new LocalizedString(" Export to Zip").Translated, exportQueueToZipMenu_Click},
                {"GCode", null},
                {new LocalizedString(" Export to Folder").Translated, exportGCodeToFolderButton_Click},
                };
            }
            else
            {
                //Set the name and callback function of the menu items
                menuItems = new TupleList<string, Func<bool>> 
                {
                {"STL", null},
                {new LocalizedString(" Import from Zip").Translated, importQueueFromZipMenu_Click},
                {new LocalizedString(" Export to Zip").Translated, exportQueueToZipMenu_Click},
                {"GCode", null},
                {new LocalizedString(" Export to Folder").Translated, exportGCodeToFolderButton_Click},
                {new LocalizedString("Extra").Translated, null},
                {new LocalizedString(" Create Part Sheet").Translated, createPartsSheetsButton_Click},
                };
            }

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple<string, Func<bool>> item in menuItems)
            {
                if (item.Item2 == null)
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
                }
                else
                {
                    MenuDropList.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
                }

                MenuDropList.AddItem(item.Item1);
            }

            MenuDropList.Padding = padding;
        }
Пример #38
0
        private HtmlDocument LoadHtml(string path, TupleList<string, string> replace = null)
        {
            var template = new HtmlDocument();
            var htmlFile = String.Join("", File.ReadAllLines(String.Format(@"{0}\{1}", Environment.CurrentDirectory, path)));
            if(replace != null)
            {
                foreach (var item in replace)
                {
                    htmlFile = htmlFile.Replace(item.Item1, item.Item2);
                }
            }
            template.LoadHtml(String.Join("", htmlFile));

            return template;
        }
Пример #39
0
        public Wiki(string baseUri, string apiPath, string ns = null, string propsFilePath = null)
        {
            Files = new TupleList<string, CompilationUnitSyntax>();
            TypeManager = new TypeManager(this);

            Namespace = ns ?? "LinqToWiki.Generated";
            EntitiesNamespace = Namespace + ".Entities";

            m_modulesSource = new ModulesSource(new WikiInfo("LinqToWiki.Codegen.App", baseUri, apiPath), propsFilePath);

            CreatePageClass();
            CreateWikiClass(baseUri, apiPath);
            CreateQueryActionClass();
            CreateEnumsFile();
        }
		public SplitButton Generate(TupleList<string, Func<bool>> buttonList, Direction direction = Direction.Down, string imageName = null)
		{
			this.imageName = imageName;

			DynamicDropDownMenu menu = CreateMenu(direction);
			menu.Margin = new BorderDouble();
			Button button = CreateButton(buttonList[0]);

			for (int index = 1; index < buttonList.Count; index++)
			{
				menu.addItem(buttonList[index].Item1, buttonList[index].Item2);
			}

			SplitButton splitButton = new SplitButton(button, menu);

			return splitButton;
		}
Пример #41
0
        public void Merge(TupleList<Vector2, float> listToSort, int begin, int end, int mid)
        {
            int lengthbeginpart = mid - begin + 1;
            int lengthendpart = end - mid;

            TupleList<Vector2, float> beginlist = new TupleList<Vector2, float>();
            TupleList<Vector2, float> endlist = new TupleList<Vector2, float>();

            for (int i = 0; i < lengthbeginpart; i++)
            {
                beginlist.Add(listToSort[i + begin]);
            }
            for (int i = 0; i < lengthendpart; i++)
            {
                endlist.Add(listToSort[mid + i + 1]);
            }

            beginlist.Add(new Vector2(float.MaxValue), float.MaxValue);
            endlist.Add(new Vector2(float.MaxValue), float.MaxValue);

            int indexbegin = 0;
            int indexend = 0;

            for (int i = begin; i <= end; i++)
            {
                if (beginlist[indexbegin].Item2 < endlist[indexend].Item2)
                {
                    listToSort[i] = beginlist[indexbegin];
                    indexbegin++;
                }
                else
                {
                    listToSort[i] = endlist[indexend];
                    indexend++;
                }
            }
        }
Пример #42
0
        private void PopulateZipCodeBoundries(List<GeographicModel> regionList)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                if (regionList.Count() == 0)
                {
                    log.Warn("regionList is Empty!");
                }
                else
                {
                    log.DebugFormat("Getting Boundaries for {0} regions!", regionList.Count());
                }
                using (var connection = GetConnection())
                {
                    using (SqlCommand cmd = new SqlCommand("IRM.spGeographicExplorerGetZipCodeBoundries", connection))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        //Fill param table with indexes of the selected Gender.
                        var ZipCodeTempTable = new DataTable();
                        ZipCodeTempTable.Columns.Add("ID", typeof(string));
                        foreach (var region in regionList)
                        {
                            ZipCodeTempTable.Rows.Add(region.ZipCode);
                        }
                        SqlParameter tvparam = cmd.Parameters.AddWithValue("@ZipCodeList", ZipCodeTempTable);
                        tvparam.SqlDbType = SqlDbType.Structured;

                        List<polygons> zipcodePolygonLists = new List<polygons>();

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            GeographicModel rgn = null;

                            while (reader.Read())
                            {
                                var oneItem = new polygons()
                                {
                                    City = reader.FieldToString("City"),
                                    PolygonID = reader.FieldToInt("ZipcodePolygonID"),
                                    ZipCode = reader.FieldToString("ZipCode"),
                                    Latitude = reader.FieldToDouble("Latitude"),
                                    Longitude = reader.FieldToDouble("Longitude")
                                };
                                zipcodePolygonLists.Add(oneItem);
                            }

                            if (zipcodePolygonLists.Count() > 0)
                            {
                                rgn = null;

                                var groups = zipcodePolygonLists.GroupBy(x => x.PolygonID);

                                foreach (var group in groups)
                                {
                                    var lst = new TupleList<double, double>();
                                    var zip = string.Empty;
                                    foreach (var item in group)
                                    {
                                        zip = item.ZipCode;
                                        lst.Add(item.Latitude, item.Longitude);
                                    }
                                    rgn = regionList.FirstOrDefault(r => r.ZipCode == zip);
                                    if (rgn != null)
                                    {
                                        rgn.Polygons.Add(lst);
                                    }
                                }
                            }
                        }
                    }
                }

            }
            finally
            {
                sw.Stop();
                LoggerHelper.RecordTiming(System.Reflection.MethodBase.GetCurrentMethod().Name, sw, log);
                log.DebugFormat("{0} rows returned", regionList.Count);
                if (regionList.Count == 0)
                {
                    log.Error("RegionList is empty!");
                }
            }
        }
Пример #43
0
        //TODO: MakeInvCopy is going to be called over and over again by DesignScript, not us, so there is no opportunity to pass the count into this method.  
        //UniqueModuleEvaluator needs to be modified each time this is called so we know which module we are on.

        //TODO:  ApprenticeServer instance creation and lifetime management needs to be handled by InventorServices.Persistance

        //TODO: OccurrenceList needs to be set on each Module instance during UniqueModuleEvaluator's construction.

        //TODO: Refactor this method, it is so big.
        private void MakeInvCopy(ApprenticeServer appServ, 
                                 string templateAssemblyPath, 
                                 string templateDrawingPath, 
                                 string targetDirectory, 
                                 OccurrenceList occList, 
                                 int count, 
                                 UniqueModuleEvaluator uniqueModuleEvaluator)
        {
            // TODO Test for the existance of folders and assemblies.
            ApprenticeServer oAppServ = appServ;
            int panelID = count;
            OccurrenceList oOccs = occList;
            string topFileFullName;
            string targetPath = targetDirectory;
            TemplateAssemblyPath = templateAssemblyPath;
            TemplateDrawingPath = templateDrawingPath;
            string panelIDString = System.Convert.ToString(panelID);
            UniqueModules = uniqueModuleEvaluator;

            //Instead of using "panelID" to create unique folders for all instances, redirect to the GeometryMapIndex
            string geoMapString = System.Convert.ToString(GeometryMapIndex);
            string folderName;
            if (CreateAllCopies == false)
            {
                if (GeometryMapIndex < 10)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 00" + geoMapString;
                }

                else if (10 <= GeometryMapIndex && GeometryMapIndex < 100)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 0" + geoMapString;
                }
                else
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " " + geoMapString;
                }
            }

            else
            {
                if (panelID < 10)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 00" + panelIDString;
                }
                else if (10 <= panelID && panelID < 100)
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " 0" + panelIDString;
                }
                else
                {
                    folderName = System.IO.Path.GetFileNameWithoutExtension(TemplateAssemblyPath) + " " + panelIDString;
                }
            }
            //if(panelID < 10){
            //Need to get number of the parent occ, top level name as foldername
            string pathString = System.IO.Path.Combine(targetPath, folderName);

            topFileFullName = oOccs.TargetAssembly.FullDocumentName;
            string topFileNameOnly = System.IO.Path.GetFileName(topFileFullName);
            ModulePath = System.IO.Path.Combine(pathString, topFileNameOnly);


            TupleList<string, string> filePathPair = new TupleList<string, string>();

            for (int i = 0; i < occList.Items.Count; i++)
            {
                string targetOccPath = occList.Items[i].ReferencedFileDescriptor.FullFileName;
                string newCopyName = System.IO.Path.GetFileName(targetOccPath);
                string newFullCopyName = System.IO.Path.Combine(pathString, newCopyName);
                filePathPair.Add(targetOccPath, newFullCopyName);
            }

            //Check if an earlier panel already made the folder, if not, create it.
            if (!System.IO.Directory.Exists(pathString))
            {
                firstTime = true;
                System.IO.Directory.CreateDirectory(pathString);
                //AssemblyReplaceRef(oAppServ, oOccs.TargetAssembly, filePathPair, pathString);
                ApprenticeServerDocument oAssDoc;
                oAssDoc = oAppServ.Open(TemplateAssemblyPath);
                FileSaveAs fileSaver;
                fileSaver = oAppServ.FileSaveAs;
                fileSaver.AddFileToSave(oAssDoc, ModulePath);
                fileSaver.ExecuteSaveCopyAs();

                //Need to copy presentation files if there are any.  For now this is only going to work with the top assembly.
                string templateDirectory = System.IO.Path.GetDirectoryName(TemplateAssemblyPath);
                string[] presentationFiles = System.IO.Directory.GetFiles(templateDirectory, "*.ipn");
                //If we want the ability to have subassemblies with .ipn files or multiple ones, this will have to be changed
                //to iterate over all the .ipn files.
                if (presentationFiles.Length != 0)
                {
                    string newCopyPresName = System.IO.Path.GetFileName(presentationFiles[0]);
                    string newFullCopyPresName = System.IO.Path.Combine(pathString, newCopyPresName);

                    ApprenticeServerDocument presentationDocument = oAppServ.Open(presentationFiles[0]);
                    DocumentDescriptorsEnumerator presFileDescriptors = presentationDocument.ReferencedDocumentDescriptors;
                    foreach (DocumentDescriptor refPresDocDescriptor in presFileDescriptors)
                    {
                        if (refPresDocDescriptor.FullDocumentName == TemplateAssemblyPath)
                        {
                            refPresDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModulePath);
                            FileSaveAs fileSavePres;
                            fileSavePres = oAppServ.FileSaveAs;
                            fileSavePres.AddFileToSave(presentationDocument, newFullCopyPresName);
                        }
                    }
                }

                string newCopyDrawingName = System.IO.Path.GetFileName(TemplateDrawingPath);
                string newFullCopyDrawingName = System.IO.Path.Combine(pathString, newCopyDrawingName);

                if (TemplateDrawingPath != "")
                {
                    ApprenticeServerDocument drawingDoc = oAppServ.Open(TemplateDrawingPath);
                    DocumentDescriptorsEnumerator drawingFileDescriptors = drawingDoc.ReferencedDocumentDescriptors;
                    //This needs to be fixed.  It was written with the assumption that only the template assembly would be in 
                    //the details and be first in the collection of document descriptors.  Need to iterate through 
                    //drawingFileDescriptors and match names and replace correct references.
                    //Possibly can use the "filePathPair" object for name matching/reference replacing.
                    //drawingFileDescriptors[1].ReferencedFileDescriptor.ReplaceReference(topAssemblyNewLocation);
                    foreach (DocumentDescriptor refDocDescriptor in drawingFileDescriptors)
                    {
                        foreach (Tuple<string, string> pathPair in filePathPair)
                        {
                            string newFileNameLower = System.IO.Path.GetFileName(pathPair.Item2);
                            string drawingReferenceLower = System.IO.Path.GetFileName(refDocDescriptor.FullDocumentName);
                            string topAssemblyLower = System.IO.Path.GetFileName(ModulePath);
                            if (topAssemblyLower == drawingReferenceLower)
                            {
                                refDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModulePath);
                            }
                            if (newFileNameLower == drawingReferenceLower)
                            {
                                refDocDescriptor.ReferencedFileDescriptor.ReplaceReference(pathPair.Item2);
                            }
                        }
                    }

                    FileSaveAs fileSaveDrawing;
                    fileSaveDrawing = oAppServ.FileSaveAs;
                    fileSaveDrawing.AddFileToSave(drawingDoc, newFullCopyDrawingName);
                    fileSaveDrawing.ExecuteSaveCopyAs();
                    firstTime = true;

                    if (!UniqueModules.DetailDocumentPaths.Contains(newFullCopyDrawingName))
                    {
                        UniqueModules.DetailDocumentPaths.Add(newFullCopyDrawingName);
                    }
                }
            }
        }
		private void SetMenuItems()
		{
			//Set the name and callback function of the menu items
			slicerOptionsMenuItems = new TupleList<string, Func<bool>>
			{
				{ "Import".Localize(), ImportSettingsMenu_Click },
				{ "Export".Localize(), ExportSettingsMenu_Click },
				{ "Restore All".Localize(), RestoreAllSettingsMenu_Click },
			};

			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in slicerOptionsMenuItems)
			{
				sliceOptionsMenuDropList.AddItem(item.Item1);
			}
		}
Пример #45
0
        private void EventPublisher_ManipulatorChanged(object sender, ManipulatorEventArgs e)
        {
            // Visual indication of current manipulator
            var manipulators = new TupleList<ManipulatorManagerTypes, ToolStripButton>
                {
                    {ManipulatorManagerTypes.Default, ToolStripDefaultManipulator},
                    {ManipulatorManagerTypes.Polygon, ToolStripPolygonManipulator},
                    {ManipulatorManagerTypes.Attack, ToolStripAttackManipulator}
                };

            foreach (var manipulator in manipulators)
            {
                manipulator.Item2.Checked = manipulator.Item1 == e.ManipulatorType;
            }

            var manipulators2 = new TupleList<ManipulatorManagerTypes, ToolStripMenuItem>
                {
                    {ManipulatorManagerTypes.Default, MenuMapInteractionDefault},
                    {ManipulatorManagerTypes.Polygon,MenuMapInteractionPolygon},
                    {ManipulatorManagerTypes.Attack, MenuMapInteractionPlanAttacks}
                };

            foreach (var manipulator in manipulators2)
            {
                manipulator.Item2.Checked = manipulator.Item1 == e.ManipulatorType;
            }

            if (e.ManipulatorType == ManipulatorManagerTypes.Attack)
            {
                var pane = GetNavigationPane(NavigationPanes.Attack);
                LeftNavigation.SelectNavigationPage(pane.Key);
            }
        }
Пример #46
0
		public DynamicDropDownMenu Generate(string label = "", TupleList<string, Func<bool>> optionList = null, Direction direction = Direction.Down)
		{
			DynamicDropDownMenu menu = new DynamicDropDownMenu(label, CreateButtonViewStates(label), direction);
			menu.VAnchor = VAnchor.ParentCenter;
			menu.HAnchor = HAnchor.FitToChildren;
			menu.MenuAsWideAsItems = false;
			menu.AlignToRightEdge = true;
			menu.NormalColor = normalFillColor;
			menu.HoverColor = hoverFillColor;
			menu.BorderColor = normalBorderColor;
			menu.BackgroundColor = menu.NormalColor;

			if (optionList != null)
			{
				foreach (Tuple<string, Func<bool>> option in optionList)
				{
					menu.addItem(option.Item1, option.Item2);
				}
			}

			return menu;
		}
Пример #47
0
        public void add_handlers(string host_pattern, TupleList<string, CreateRequestHandler, Dictionary<string, object>> host_handlers)
        {
            /*Appends the given handlers to our handler list.

            Note that host patterns are processed sequentially in the
            order they were added, and only the first matching pattern is
            used.  This means that all handlers for a given host must be
            added in a single add_handlers call.
            */
            if (!host_pattern.EndsWith("$"))
                host_pattern += "$";
            var handlers_ = new List<URLSpec>();
            // The handlers with the wildcard host_pattern are a special
            // case - they're added in the constructor but should have lower
            // precedence than the more-precise handlers added later.
            // If a wildcard handler group exists, it should always be last
            // in the list, so insert new groups just before it.
            if (handlers.Any() && handlers.Last().Item1.ToString() == ".*$")
                handlers.Insert(handlers.Count - 1, Tuple.Create(new Regex(host_pattern, RegexOptions.Compiled), handlers_));
            else
                handlers.Add(Tuple.Create(new Regex(host_pattern, RegexOptions.Compiled), handlers_));

            foreach (var spec in host_handlers)
            {
                URLSpec spec_ = null;

                //todo? if type(spec) is type(()):
                {
                    //assert len(spec) in (2, 3)
                    var pattern = spec.Item1;
                    var handler = spec.Item2;

                    /*if isinstance(handler, str):
                        # import the Module and instantiate the class
                        # Must be a fully qualified name (module.ClassName)
                        handler = import_object(handler)*/

                    /*if len(spec) == 3:
                        kwargs = spec[2]
                    else:
                        kwargs = {}*/
                    var kwargs = spec.Item3;
                    spec_ = new URLSpec(pattern, handler, kwargs);
                }
                handlers_.Add(spec_);
                if (spec_.name != null)
                {
                    if (named_handlers.ContainsKey(spec_.name))
                        logging.warning(string.Format("Multiple handlers named {0}; replacing previous value", spec_.name));
                    named_handlers[spec_.name] = spec_;
                }
            }
        }
Пример #48
0
 public void clear()
 {
     //Resets all headers and content for this response."""
     // The performance cost of tornado.httputil.HTTPHeaders is significant
     // (slowing down a benchmark with a trivial handler by more than 10%),
     // and its case-normalization is not generally necessary for
     // headers we generate on the server side, so use a plain dict
     // and list instead.
     _headers = new HTTPHeaders {
         {"Server", "TornadoServer/" + tornado.version},
         {"Content-Type", "text/html; charset=UTF-8"}
     };
     _list_headers = new TupleList<string,string>();
     set_default_headers();
     if (!request.supports_http_1_1())
         if (request.headers.get("Connection") == "Keep-Alive")
             set_header("Connection", "Keep-Alive");
     _write_buffer = new List<byte[]>();
     _status_code = 200;
 }
Пример #49
0
        internal void MakeInvCopy(string templateAssemblyPath,
                         string targetDirectory,
                         OccurrenceList occurrenceList,
                         UniqueModuleEvaluator uniqueModuleEvaluator)
        {
            // TODO Test for the existance of folders and assemblies.
            TemplateAssemblyPath = templateAssemblyPath;        
            UniqueModules = uniqueModuleEvaluator;

            
            //Get the folder name that will be used to store the files associated with this Module.
            string folderName = GetModuleFolderPath();

            //Need to get number of the parent occ, top level name as foldername
            ModulePath = System.IO.Path.Combine(targetDirectory, folderName);

            string topFileFullName = occurrenceList.TargetAssembly.FullDocumentName;
            string topFileNameOnly = System.IO.Path.GetFileName(topFileFullName);
            ModuleAssemblyPath = System.IO.Path.Combine(ModulePath, topFileNameOnly);

            //If this file already exists in the current location, for now we are
            //going to just skip the file creation, and assume it was previously done
            //correctly.  Probably need to give the user the option to redo and 
            //overwrite files if they want to.
            if (!System.IO.File.Exists(ModuleAssemblyPath))
            {
                FilePathPair = new TupleList<string, string>();

                for (int i = 0; i < occurrenceList.Items.Count; i++)
                {
                    string targetOccPath = occurrenceList.Items[i].ReferencedFileDescriptor.FullFileName;
                    string newCopyName = System.IO.Path.GetFileName(targetOccPath);
                    string newFullCopyName = System.IO.Path.Combine(ModulePath, newCopyName);
                    FilePathPair.Add(targetOccPath, newFullCopyName);
                }

                //Check if an earlier module already made the folder, if not, create it.
                if (!System.IO.Directory.Exists(ModulePath))
                {
                    //This property is needed later when placing occurrences of the assembly this Module instance 
                    //refers to.  If FirstTime is false, we will want to have a slightly different strategry for constraint
                    //placement.  If FirstTime is true, all constraints are important and we need not relax them.  If 
                    //FirstTime is false, then we need tolerance in the constraints because of double precision.  When
                    //FirstTime is false, we really just want to position the occurrence correctly, not drive its 
                    //geometry.

                    if (FirstTime == null)
                    {
                        FirstTime = true;
                    }

                    System.IO.Directory.CreateDirectory(ModulePath);
                    ReplaceReferences(occurrenceList.TargetAssembly, FilePathPair, ModulePath);
                    AssemblyDocument oAssDoc = (AssemblyDocument)PersistenceManager.InventorApplication.Documents.Open(TemplateAssemblyPath, false);
                    oAssDoc.SaveAs(ModuleAssemblyPath, true);
                    oAssDoc.Close(true);


                    //Need to copy presentation files if there are any.  For now this is only going to work with the top assembly.
                    string templateDirectory = System.IO.Path.GetDirectoryName(TemplateAssemblyPath);
                    string[] presentationFiles = System.IO.Directory.GetFiles(templateDirectory, "*.ipn");
                    //If we want the ability to have subassemblies with .ipn files or multiple ones, this will have to be changed
                    //to iterate over all the .ipn files.
                    if (presentationFiles.Length != 0)
                    {
                        string newCopyPresName = System.IO.Path.GetFileName(presentationFiles[0]);
                        string newFullCopyPresName = System.IO.Path.Combine(ModulePath, newCopyPresName);
                        PresentationDocument presentationDocument = (PresentationDocument)PersistenceManager.InventorApplication.Documents.Open(presentationFiles[0], false);
                        DocumentDescriptorsEnumerator presFileDescriptors = presentationDocument.ReferencedDocumentDescriptors;
                        foreach (DocumentDescriptor refPresDocDescriptor in presFileDescriptors)
                        {
                            if (refPresDocDescriptor.FullDocumentName == TemplateAssemblyPath)
                            {
                                refPresDocDescriptor.ReferencedFileDescriptor.ReplaceReference(ModuleAssemblyPath);
                                presentationDocument.SaveAs(newFullCopyPresName, true);
                                presentationDocument.Close(true);
                            }
                        }
                    }
                }

                else
                {
                    FirstTime = false;
                }
            }
        }
Пример #50
0
 public WorkspaceSession( Workspace workspace )
 {
     StoredWorkspaces = new TupleList<string, object>(
         workspace.Workspaces.Select( w => Tuple.Create( w.Item1.FullName, w.Item2.Store() ) )
     );
 }
		private void SetMenuItems()
		{
			string importTxt = LocalizedString.Get("Import");
			string importTxtFull = string.Format("{0}", importTxt);
			string exportTxt = LocalizedString.Get("Export");
			string exportTxtFull = string.Format("{0}", exportTxt);
			//Set the name and callback function of the menu items
			slicerOptionsMenuItems = new TupleList<string, Func<bool>>
			{
				{importTxtFull, ImportQueueMenu_Click},
				{exportTxtFull, ExportQueueMenu_Click},
			};

			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in slicerOptionsMenuItems)
			{
				sliceOptionsMenuDropList.AddItem(item.Item1);
			}
		}
Пример #52
0
        public void ReplaceReferences(AssemblyDocument targetAssembly, TupleList<string, string> namePair, string folderPath)
        {
            OccurrenceList newOccs = new OccurrenceList(targetAssembly);
            string pathString = folderPath;
            List<string> patternComponentsList = new List<string>();
            for (int i = 0; i < newOccs.Items.Count; i++)
            {
                if (newOccs.Items[i].DefinitionDocumentType == DocumentTypeEnum.kPartDocumentObject)
                {
                    for (int f = 0; f < namePair.Count; f++)
                    {
                        if (namePair[f].Item1 == newOccs.Items[i].ReferencedFileDescriptor.FullFileName)
                        {
                            if (patternComponentsList.Contains(namePair[f].Item1))
                            {
                                newOccs.Items[i].ReferencedDocumentDescriptor.ReferencedFileDescriptor.ReplaceReference(namePair[f].Item2);
                            }

                            else
                            {
                                if (!System.IO.File.Exists(namePair[f].Item2))
                                {
                                    PartDocument partDoc = (PartDocument)PersistenceManager.InventorApplication.Documents.Open(namePair[f].Item1, false);
                                    partDoc.SaveAs(namePair[f].Item2, true);
                                    partDoc.Close(true);
                                    newOccs.Items[i].ReferencedDocumentDescriptor.ReferencedFileDescriptor.ReplaceReference(namePair[f].Item2);
                                }
                                patternComponentsList.Add(namePair[f].Item1);
                            }
                        }
                    }
                }

                else if (newOccs.Items[i].DefinitionDocumentType == DocumentTypeEnum.kAssemblyDocumentObject)
                {
                    for (int n = 0; n < namePair.Count; n++)
                    {
                        if (namePair[n].Item1 == newOccs.Items[i].ReferencedFileDescriptor.FullFileName)
                        {
                            AssemblyDocument subAssembly = (AssemblyDocument)PersistenceManager.InventorApplication.Documents.Open(newOccs.Items[i].ReferencedFileDescriptor.FullFileName,false);
                            ReplaceReferences(subAssembly, namePair, pathString);
                            string newFilePath = namePair[n].Item2;
                            subAssembly.SaveAs(namePair[n].Item2, true);
                            subAssembly.Close(true);
                            newOccs.Items[i].ReferencedDocumentDescriptor.ReferencedFileDescriptor.ReplaceReference(namePair[n].Item2);
                        }
                    }
                }
            }
        }
Пример #53
0
        private static void WriteHeader(StreamWriter html, string title, string baseDir, TupleList<string, string> menu)
        {
            if (html == null) throw new ArgumentNullException("html");
            if (string.IsNullOrWhiteSpace(title)) throw new ArgumentNullException("title");
            if (menu == null) throw new ArgumentNullException("menu");

            html.WriteLine(@"<html>
            <head>
            <meta charset=""UTF-8"">
            <title>{0}</title>
            <link href=""{1}style.css"" rel=""stylesheet"" />
            </head>
            <body>", title, baseDir);

            html.WriteLine(@"<ul id=""menu"">");
            foreach (var item in menu)
            {
                html.WriteLine(@"<li class=""menu-item""><a class=""menu-link"" href=""{2}{0}"">{1}</a></li>", item.Item1, item.Item2, baseDir);
            }
            html.WriteLine(@"</ul>");
        }
Пример #54
0
		private void SetMenuItems(DropDownMenu dropDownMenu)
		{
			menuItems = new TupleList<string, Func<bool>>();

			if (ActiveTheme.Instance.IsTouchScreen)
			{
				menuItems.Add(new Tuple<string, Func<bool>>("Remove All".Localize(), clearAllMenu_Select));
			}

			menuItems.Add(new Tuple<string, Func<bool>>("Send".Localize(), sendMenu_Selected));
			menuItems.Add(new Tuple<string, Func<bool>>("Add To Library".Localize(), addToLibraryMenu_Selected));

			BorderDouble padding = dropDownMenu.MenuItemsPadding;
			//Add the menu items to the menu itself
			foreach (Tuple<string, Func<bool>> item in menuItems)
			{
				if (item.Item2 == null)
				{
					dropDownMenu.MenuItemsPadding = new BorderDouble(5, 0, padding.Right, 3);
				}
				else
				{
					dropDownMenu.MenuItemsPadding = new BorderDouble(10, 5, padding.Right, 5);
				}

				dropDownMenu.AddItem(item.Item1);
			}

			dropDownMenu.Padding = padding;
		}
Пример #55
0
		private void AddSaveAndSaveAs(FlowLayoutWidget flowToAddTo)
		{
			TupleList<string, Func<bool>> buttonList = new TupleList<string, Func<bool>>();
			buttonList.Add("Save", () =>
			{
				MergeAndSavePartsToCurrentMeshFile();
				return true;
			});
			
			buttonList.Add("Save As", () =>
			{
				UiThread.RunOnIdle(OpenSaveAsWindow);
				return true;
			});

			SplitButtonFactory splitButtonFactory = new SplitButtonFactory();
			splitButtonFactory.FixedHeight = 40 * TextWidget.GlobalPointSizeScaleRatio;
			saveButtons = splitButtonFactory.Generate(buttonList, Direction.Up, imageName: "icon_save_32x32.png");
			saveButtons.Visible = false;

			saveButtons.Margin = new BorderDouble();
			saveButtons.VAnchor |= VAnchor.ParentCenter;

			flowToAddTo.AddChild(saveButtons);
		}
        void SetMenuItems()
        {
            menuItems = new TupleList<string, Func<bool>> 
            {                
                {LocalizedString.Get("Add Printer"), addPrinter_Click},
                {LocalizedString.Get("Add File"), importFile_Click},
				{LocalizedString.Get("Exit"), exit_Click},
            };

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple<string, Func<bool>> item in menuItems)
            {
                MenuDropList.MenuItemsPadding = new BorderDouble(8,4,8,4);
                MenuDropList.AddItem(item.Item1,pointSize:10);
            }            
            MenuDropList.Padding = padding;
        }
Пример #57
0
        public Application(TupleList<string, CreateRequestHandler, Dictionary<string, object>> handlers_ = null, string default_host_ = "", List<Func<HTTPRequest, OutputTransform>> transforms_ = null,
                 bool wsgi=false, Dictionary<string, object> settings_=null)
        {
            if (settings_ == null) 
                settings_ = new Dictionary<string, object>();

            if (transforms_ == null)
            {
                transforms = new List<Func<HTTPRequest, OutputTransform>>();
                if (settings_.get("gzip") != null)
                    transforms.Add(r => new GZipContentEncoding(r));
                transforms.Add(r => new ChunkedTransferEncoding(r));
            }
            else
                transforms = transforms_;
            handlers = new TupleList<Regex,List<URLSpec>>();
            named_handlers = new Dictionary<string, object>();
            default_host = default_host_;
            settings = settings_;
            //todo implement
            /*self.ui_modules = {'linkify': _linkify,
                               'xsrf_form_html': _xsrf_form_html,
                               'Template': TemplateModule,
                               }
            self.ui_methods = {}*/
            _wsgi = wsgi;
            /*self._load_ui_modules(settings.get("ui_modules", {}))
            self._load_ui_methods(settings.get("ui_methods", {}))*/
            if (settings.get("static_path") != null)
            {
                var path = settings["static_path"] as string;
                handlers_ = handlers_ ?? new TupleList<string, CreateRequestHandler, Dictionary<string, object>>();
                var static_url_prefix = settings.get("static_url_prefix", "/static/");
                var static_handler_class = settings.get<CreateRequestHandler>("static_handler_class", (app, rq, args) => new StaticFileHandler(app, rq, args));
                var static_handler_args = settings.get("static_handler_args", new Dictionary<string, object>());
                static_handler_args["path"] = path;

                foreach (var pattern in new string[] {Regex.Escape(static_url_prefix) + @"(.*)", 
                                                     @"/(favicon\.ico)", @"/(robots\.txt)"}) 
                {
                    handlers_.Insert(0, Tuple.Create(pattern, static_handler_class, static_handler_args));
                }
            }
            if (handlers_ != null)
                add_handlers(".*$", handlers_);

      
            // Automatically reload modified modules
            if (settings.get("debug") != null && !wsgi)
            {
                //todo implement
                //from tornado import autoreload
                //autoreload.start()
            }
        }
        void SetMenuItems()
        {
            menuItems = new TupleList<string, Func<bool>> 
            {                
                {LocalizedString.Get("Getting Started"), gettingStarted_Click},
                {LocalizedString.Get("View Help"), help_Click},
                {LocalizedString.Get("Report a Bug"), bug_Click},
				{LocalizedString.Get("Release Notes"), notes_Click},
                {LocalizedString.Get("About MatterControl"), about_Click},
            };

            BorderDouble padding = MenuDropList.MenuItemsPadding;
            //Add the menu items to the menu itself
            foreach (Tuple<string, Func<bool>> item in menuItems)
            {
                MenuDropList.MenuItemsPadding = new BorderDouble(8, 4, 8, 4);
                MenuDropList.AddItem(item.Item1, pointSize: 10);
            }
            MenuDropList.Padding = padding;
        }
Пример #59
0
        /// <summary>
        /// Creates a type representing the given <see cref="EnumParameterType"/>.
        /// </summary>
        private string GenerateType(EnumParameterType enumType, string propertyName, string moduleName)
        {
            string typeName = moduleName + propertyName;

            Dictionary<EnumParameterType, string> moduleTypes;

            if (m_enumTypeNames.TryGetValue(moduleName, out moduleTypes))
            {
                int i = 2;
                while (moduleTypes.Values.Contains(typeName))
                    typeName = moduleName + propertyName + i++;
            }

            var fixedMemberNameMapping = new TupleList<string, string>();
            var memberNames = new List<string>();

            foreach (var name in enumType.Values)
            {
                var fixedName = FixEnumMemberName(name);

                if (name != fixedName.TrimStart('@'))
                    fixedMemberNameMapping.Add(fixedName, name);

                memberNames.Add(fixedName);
            }

            var members = enumType.Values.Select(
                memberName =>
                SyntaxEx.FieldDeclaration(
                    new[] { SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword, SyntaxKind.ReadOnlyKeyword },
                    typeName, FixEnumMemberName(memberName),
                    SyntaxEx.ObjectCreation(typeName, SyntaxEx.Literal(memberName))));

            var constructorParameter = SyntaxEx.Parameter("string", "value");
            var contructor = SyntaxEx.ConstructorDeclaration(
                new[] { SyntaxKind.InternalKeyword }, typeName, new[] { constructorParameter },
                constructorInitializer: SyntaxEx.BaseConstructorInitializer((NamedNode)constructorParameter));

            var firstParameter = SyntaxEx.Parameter(typeName, "first");
            var secondParameter = SyntaxEx.Parameter(typeName, "second");

            Func<SyntaxKind, ExpressionSyntax, OperatorDeclarationSyntax> createOperator =
                (op, result) => SyntaxEx.OperatorDeclaration(
                    Syntax.ParseTypeName("bool"), op,
                    new[] { firstParameter, secondParameter },
                    new[] { SyntaxEx.Return(result) });

            var equalsExpression = SyntaxEx.Invocation(
                Syntax.IdentifierName("Equals"), (NamedNode)firstParameter, (NamedNode)secondParameter);
            var notEqualsExpression = SyntaxEx.Not(equalsExpression);

            var equalsOperator = createOperator(SyntaxKind.EqualsEqualsToken, equalsExpression);
            var notEqualsOPerator = createOperator(SyntaxKind.ExclamationEqualsToken, notEqualsExpression);

            var equalsParameter = SyntaxEx.Parameter("object", "obj");
            var equalsMethod = SyntaxEx.MethodDeclaration(
                new[] { SyntaxKind.PublicKeyword, SyntaxKind.OverrideKeyword }, "bool", "Equals",
                new[] { equalsParameter },
                SyntaxEx.Return(
                    SyntaxEx.Invocation(SyntaxEx.MemberAccess("base", "Equals"), (NamedNode)equalsParameter)));

            var getHashCodeMethod = SyntaxEx.MethodDeclaration(
                new[] { SyntaxKind.PublicKeyword, SyntaxKind.OverrideKeyword }, "int", "GetHashCode",
                new ParameterSyntax[0],
                SyntaxEx.Return(SyntaxEx.Invocation(SyntaxEx.MemberAccess("base", "GetHashCode"))));

            var classDeclaration =
                SyntaxEx.ClassDeclaration(typeName, Syntax.ParseTypeName("StringValue"), contructor)
                        .AddMembers(equalsOperator, notEqualsOPerator, equalsMethod, getHashCodeMethod)
                        .AddMembers(members.ToArray<MemberDeclarationSyntax>());

            var namespaceDeclaration = m_wiki.Files[Wiki.Names.Enums].SingleDescendant<NamespaceDeclarationSyntax>();

            m_wiki.Files[Wiki.Names.Enums] = m_wiki.Files[Wiki.Names.Enums].ReplaceNode(
                namespaceDeclaration, namespaceDeclaration.AddMembers(classDeclaration));

            m_enumTypeNames.Add(moduleName, enumType, typeName);

            return typeName;
        }
Пример #60
0
        private static void PickRandomInstalledGame()
        {
            using (dynamic steamPlayerServices = WebAPI.GetInterface("IPlayerService", steamApiKey))
            {

                try
                {
                    KeyValue kvGames = steamPlayerServices.GetOwnedGames(steamid: steamUser.SteamID.ConvertToUInt64(), include_appinfo: 1);
                    var apps = SteamDrives.getAllInstalledGames();
                    var matchedGames = new TupleList<String, int>();
                    foreach (KeyValue game in kvGames["games"].Children)
                    {
                        if (apps.Contains(game["appid"].AsInteger()))
                            matchedGames.Add(game["name"].AsString(), game["appid"].AsInteger());
                    }
                    Random r = new Random();
                    Tuple<String, int> randomGame = matchedGames[r.Next(matchedGames.Count)];
                    Console.Write("Would you like to play {0}? [Y/n] : ", randomGame.Item1);
                    switch (Console.ReadLine())
                    {
                        case "Y":
                        case "y":
                            Console.WriteLine("Launching {0} - AppID {1}", randomGame.Item1, randomGame.Item2);
                            var uri = String.Format("steam://run/{0}", randomGame.Item2.ToString());
                            System.Diagnostics.Process.Start(uri);
                            break;
                        default :
                            Console.WriteLine("Not launching game {0}", randomGame.Item1);
                            break;
                    }
                }
                catch (WebException ex)
                {
                    Console.WriteLine("Unable to make API request:{0}", ex.Message);
                }
            }
        }