コード例 #1
1
        public static CompilerResults CompileFile(string input, string output, params string[] references)
        {
            CreateOutput(output);

            List<string> referencedAssemblies = new List<string>(references.Length + 3);

            referencedAssemblies.AddRange(references);
            referencedAssemblies.Add("System.dll");
            referencedAssemblies.Add(typeof(IModule).Assembly.CodeBase.Replace(@"file:///", ""));
            referencedAssemblies.Add(typeof(ModuleAttribute).Assembly.CodeBase.Replace(@"file:///", ""));

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters(referencedAssemblies.ToArray(), output);

            using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(input))
            {
                if (stream == null)
                {
                    throw new ArgumentException("input");
                }

                StreamReader reader = new StreamReader(stream);
                string source = reader.ReadToEnd();
                CompilerResults results = codeProvider.CompileAssemblyFromSource(cp, source);
                ThrowIfCompilerError(results);
                return results;
            }
        }
コード例 #2
0
ファイル: cExcel.cs プロジェクト: CISC181/VolTeerNET
 public static List<string> GetAllExcelFiles()
 {
     List<string> ExcelFiles = new List<string>();
     ExcelFiles.AddRange(GetAllVolExcelFiles());
     ExcelFiles.AddRange(GetAllVendExcelFiles());
     return ExcelFiles;
 }
コード例 #3
0
ファイル: 09.cs プロジェクト: Xyresic/Interview-Practice
        public static IList<IList<int>> FindPathsWithSum(TreeNode root, List<int> path, int search)
        {
            if (root == null)
            {
                return new List<IList<int>>();
            }

            path.Add(root.Value);
            List<IList<int>> results = new List<IList<int>>();

            for (int i = path.Count - 1; i >= 0; i--)
            {
                IList<int> currPath = path.GetRange(i, path.Count - i);
                int sum = currPath.Aggregate((total, next) => { return total + next; });
                if (sum == search)
                {
                    results.Add(currPath);
                }
            }

            results.AddRange(FindPathsWithSum(root.Left, new List<int>(path), search));
            results.AddRange(FindPathsWithSum(root.Right, new List<int>(path), search));

            return results;
        }
コード例 #4
0
        public void ArticleClassificationIsVulnerabilities()
        {
            var urlList = new List<string>();
            //Fetching Parent node Urls
            urlList.AddRange(HPFortifyXMLMapping.Select(x => x.ArticleUrl));
            //Fetching Child urls
            var subcategoryUrl = (from query in HPFortifyXMLMapping
                                  from subcategory in query.SubCategories
                                  select subcategory.ArticleUrl).ToList();

            //Merging both Url list to make processing easier
            urlList.AddRange(subcategoryUrl);
            using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver())
            {
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                foreach (var url in urlList)
                {
                    driver.Url = url;
                    driver.Navigate();
                    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                    wait.Until(x => x.FindElement(By.Id("GuidanceTypeLabel")).Text.Length>0);
                    var text = driver.FindElement(By.Id("GuidanceTypeLabel")).Text;
                    Console.WriteLine(text);
                    Assert.IsTrue(text == "Vulnerability");
                }
            }
        }
コード例 #5
0
        public void TestRunningWeightedVarianceDecremental()
        {
            var arr = new List<double[]>();
            arr.AddRange(EnumerableExtensions.Create(1, _ => new double[] { 0 }));
            arr.AddRange(EnumerableExtensions.Create(1, _ => new double[] { 10 }));
            arr.AddRange(EnumerableExtensions.Create(1, _ => new double[] { 0 }));
            arr.AddRange(EnumerableExtensions.Create(1, _ => new double[] { 1 }));

            double[] w = EnumerableExtensions.Create(arr.Count, _ => (double)1).ToArray();

            var variancesDec = new List<double>();
            arr.RunningVarianceDecremental
                (
                        (idx, avgInc, varDec) =>
                        {
                            variancesDec.Add(varDec);
                        }
                        , w
                );

            Assert.IsTrue(Math.Abs(variancesDec[0] - 20.22) < 1E-2);
            Assert.IsTrue(Math.Abs(variancesDec[1] - 0.25) < 1E-2);
            Assert.IsTrue(Math.Abs(variancesDec[2] - 0) < 1E-2);
            Assert.IsTrue(Double.IsInfinity(variancesDec[3]));
        }
コード例 #6
0
ファイル: ProgramTests.cs プロジェクト: nofuture-git/31g
        public void TestBkToCipherTextOnSocket()
        {
            _bkToCipherText = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            var endpt = new IPEndPoint(IPAddress.Loopback, BK_CT_PORT);
            _bkToCipherText.Connect(endpt);

            var bytesSent = _bkToCipherText.Send(Encoding.UTF8.GetBytes(TEST_INPUT));
            var buffer = new List<byte>();
            var data = new byte[256];

            _bkToCipherText.Receive(data, 0, data.Length, SocketFlags.None);
            buffer.AddRange(data.Where(b => b != (byte)'\0'));
            while (_bkToCipherText.Available > 0)
            {
                data = new byte[_bkToCipherText.Available];
                _bkToCipherText.Receive(data, 0, data.Length, SocketFlags.None);
                buffer.AddRange(data.Where(b => b != (byte)'\0'));
            }

            _bkToCipherText.Close();

            var cipherdata = Encoding.UTF8.GetString(buffer.ToArray());

            NoFuture.Shared.CipherText cipherText;
            var parseResult = NoFuture.Shared.CipherText.TryParse(cipherdata, out cipherText);
            Assert.IsTrue(parseResult);
            Console.WriteLine(cipherText.ToString());
        }
コード例 #7
0
 private List<Assembly> GetAllAssemblies(string path)
 {
     var files = new List<FileInfo>();
     var directoryToSearch = new DirectoryInfo(path);
     files.AddRange(directoryToSearch.GetFiles("*.dll", SearchOption.AllDirectories));
     files.AddRange(directoryToSearch.GetFiles("*.exe", SearchOption.AllDirectories));
     return files.ConvertAll(file => Assembly.LoadFile(file.FullName));
 }
コード例 #8
0
 public static IEnumerable<string> GetFileNames()
 {
     var list = new List<string>();
     list.AddRange(Directory.GetFiles(".", "g.*.graphml"));
     if (Directory.Exists("graphml"))
         list.AddRange(Directory.GetFiles("graphml", "g.*.graphml"));
     return list;
 }
コード例 #9
0
ファイル: TestPsTypeInfo.cs プロジェクト: nofuture-git/31g
        public void TestCtor()
        {
            var testInputAllBoolStrings = new List<string>
            {
                bool.TrueString,
                bool.TrueString,
                bool.FalseString,
                bool.TrueString,
                bool.FalseString,
                bool.FalseString
            };

            var testInputAllBoolMssqlBit = new List<string> {"1", "0", "0", "1", "0", "1"};
            var testInputAllDecimal = new List<string> {"0.0", "1.0", "3.4", "6.90", "8.098"};
            var testInputAllInt = new List<string> {"2", "138", "56", "85", "-5"};
            var testInputAllDate = new List<string>
            {
                DateTime.Today.ToLongDateString(),
                DateTime.Today.ToShortDateString(),
                "2015-03-04 09:23:55.554121"
            };

            var testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllBoolStrings.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.BOOL, testResult.PsDbType);

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllBoolMssqlBit.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.BOOL, testResult.PsDbType);

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllDecimal.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.DEC, testResult.PsDbType);

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllInt.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.INT, testResult.PsDbType);

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllDate.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.DATE, testResult.PsDbType);

            var testInputMixed = new List<string>();
            testInputMixed.AddRange(testInputAllBoolMssqlBit);
            testInputMixed.Add("do you wanna earn more money");
            testInputMixed.Add("sure we all do.");

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputMixed.ToArray());
            Assert.IsTrue(testResult.PsDbType.StartsWith(NoFuture.Sql.Mssql.Md.PsTypeInfo.DEFAULT_PS_DB_TYPE));

            var testInputAllBoolMixed = new List<string>();
            testInputAllBoolMixed.AddRange(testInputAllBoolStrings);
            testInputAllBoolMixed.AddRange(testInputAllBoolMssqlBit);

            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllBoolMixed.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.BOOL, testResult.PsDbType);

            var testInputAllIntWithDecPt = new List<string> {"2.0", "138.0", "56.0", "85.0", "-5.0"};
            testResult = new NoFuture.Sql.Mssql.Md.PsTypeInfo("test", testInputAllIntWithDecPt.ToArray());
            Assert.AreEqual(NoFuture.Sql.Mssql.Md.PsTypeInfo.DEC, testResult.PsDbType);
        }
コード例 #10
0
 public void When_machine_is_fed_with_coins_Then_should_sort_into_two_types()
 {
     CoinSortMachine machine = new CoinSortMachine();
     List<ICoin> coins = new List<ICoin>();
     CoinFactory factory = new CoinFactory();
     coins.AddRange(factory.GetPennies(10));
     coins.AddRange(factory.GetNickels(10));
     machine.FeedCoins(coins);
     Assert.AreEqual(10, machine.Pennies.Count);
     Assert.AreEqual(10, machine.Nickels.Count);
 }
コード例 #11
0
 public void ShouldParseWhenLastStringHasNoTerminator()
 {
     var bytes = new List<byte>();
     bytes.AddRange(Encoding.ASCII.GetBytes("abc"));
     bytes.Add(0);
     bytes.AddRange(Encoding.ASCII.GetBytes("def"));
     var reader = new DelimitedReader(new StreamReader(new MemoryStream(bytes.ToArray())));
     Assert.AreEqual("abc", reader.Read());
     Assert.AreEqual("def", reader.Read());
     Assert.AreEqual(null, reader.Read());
 }
コード例 #12
0
 public void ParseEndUserSuppliedXriIdentifer()
 {
     List<char> symbols = new List<char>(XriIdentifier.GlobalContextSymbols);
     symbols.Add('(');
     List<string> prefixes = new List<string>();
     prefixes.AddRange(symbols.Select(s => s.ToString()));
     prefixes.AddRange(symbols.Select(s => "xri://" + s.ToString()));
     foreach (string prefix in prefixes) {
         var id = Identifier.Parse(prefix + "andrew");
         Assert.IsInstanceOfType(id, typeof(XriIdentifier));
     }
 }
コード例 #13
0
        public void TestParserManyLines()
        {
            var data = new List<string>();
            data.AddRange(TestData.board_init.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
            data.AddRange(TestData.events.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
            data.AddRange(TestData.interrupt_sam_nvic.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));
            data.AddRange(TestData.osc8_calib.Split(new string[] { Environment.NewLine }, StringSplitOptions.None));

            var result = SuFileParser.Parse(data).ToList();

            Assert.AreEqual(21, result.Count());
        }
コード例 #14
0
        public void FieldDefinitions_ShouldHave_Correct_Indexed_Property()
        {
            var fieldDefinitionTypes = new List<Type>();

            fieldDefinitionTypes.AddRange(ReflectionUtils.GetTypesFromAssembly<FieldDefinition>(typeof(FieldDefinition).Assembly));
            fieldDefinitionTypes.AddRange(ReflectionUtils.GetTypesFromAssembly<FieldDefinition>(typeof(TaxonomyFieldDefinition).Assembly));

            foreach (var fieldDefintion in fieldDefinitionTypes)
            {
                Trace.WriteLine(string.Format("Checking Indexed prop for Indexed def:[{0}]", fieldDefintion.GetType().Name));

                var indexedSiteModel = SPMeta2Model.NewSiteModel(m => { });
                var indexedSiteField = ModelGeneratorService.GetRandomDefinition(fieldDefintion) as FieldDefinition;

                indexedSiteModel.AddField(indexedSiteField);
                indexedSiteField.Indexed = true;

                // dep lookiup
                if (indexedSiteField is DependentLookupFieldDefinition)
                {
                    var primaryLookupField = new LookupFieldDefinitionGenerator().GenerateRandomDefinition() as FieldDefinition;

                    (indexedSiteField as DependentLookupFieldDefinition).PrimaryLookupFieldId = primaryLookupField.Id;
                    indexedSiteModel.AddField(primaryLookupField);
                }

                TestModel(indexedSiteModel);

                Trace.WriteLine(string.Format("Checking Indexed prop for non-Indexed def:[{0}]", fieldDefintion.GetType().Name));

                var nonIdexedSiteModel = SPMeta2Model.NewSiteModel(m => { });
                var nonIndexedSiteField = ModelGeneratorService.GetRandomDefinition(fieldDefintion) as FieldDefinition;

                nonIdexedSiteModel.AddField(nonIndexedSiteField);
                nonIndexedSiteField.Indexed = false;

                // dep lookiup
                if (indexedSiteField is DependentLookupFieldDefinition)
                {
                    var primaryLookupField = new LookupFieldDefinitionGenerator().GenerateRandomDefinition() as FieldDefinition;

                    (nonIndexedSiteField as DependentLookupFieldDefinition).PrimaryLookupFieldId = primaryLookupField.Id;
                    nonIdexedSiteModel.AddField(primaryLookupField);
                }

                TestModel(nonIdexedSiteModel);
            }
        }
コード例 #15
0
        public void ExpectUpdateAttributes_ShouldHave_Services()
        {
            var updateAttrTypes = ReflectionUtils.GetTypesFromAssembly<ExpectUpdate>(typeof(ExpectUpdate).Assembly);

            var updateAttrServices = new List<ExpectUpdateValueServiceBase>();
            updateAttrServices.AddRange(ReflectionUtils.GetTypesFromAssembly<ExpectUpdateValueServiceBase>(typeof(ExpectUpdateValueServiceBase).Assembly)
                                                         .Select(t => Activator.CreateInstance(t) as ExpectUpdateValueServiceBase));

            TraceUtils.WithScope(trace =>
            {
                foreach (var attr in updateAttrTypes)
                {
                    var targetServices = updateAttrServices.FirstOrDefault(s => s.TargetType == attr);

                    if (targetServices != null)
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] has service: [{1}]", attr,
                            targetServices.GetType()));
                    }
                    else
                    {
                        trace.WriteLine(string.Format("ExpectUpdate: [{0}] misses  service impl", attr));
                        Assert.Fail();
                    }
                }
            });
        }
コード例 #16
0
ファイル: StringExtensionsTest.cs プロジェクト: coapp/Test
 public static void MyClassInitialize(TestContext testContext)
 {
     testStrings = new List<string>();
     testStrings.AddRange(File.ReadLines("..\\..\\..\\..\\Test\\CoApp\\Toolkit\\Extensions\\TestStrings.txt"));
     Files = new List<string>();
     Files.AddRange(File.ReadLines("..\\..\\..\\..\\Test\\CoApp\\Toolkit\\Extensions\\FileList.txt"));
 }
        /// <summary>
        /// Tests the scenario when the initial request contains a cookie (corresponding to user), in which case, the response should contain a similar cookie with the information
        /// replicated into the listener data.
        /// </summary>
        protected void ValidateUserIdWithRequestCookie(string requestPath, int testListenerTimeoutInMs, int testRequestTimeOutInMs, Cookie[] additionalCookies = null)
        {
            DateTimeOffset time = DateTimeOffset.UtcNow;
            List<Cookie> cookies = new List<Cookie>();
            int additionalCookiesLength = 0;
            if (null != additionalCookies)
            {
                cookies.AddRange(additionalCookies);
                additionalCookiesLength = additionalCookies.Length;
            }
            string userCookieStr = "userId|" + time.ToString("O");
            var cookie = new Cookie(CookieNames.UserCookie, userCookieStr);
            cookies.Add(cookie);

            var requestResponseContainer = new RequestResponseContainer(cookies.ToArray(), requestPath, this.Config.ApplicationUri, testListenerTimeoutInMs, testRequestTimeOutInMs);
            requestResponseContainer.SendRequest();

            var userCookie = requestResponseContainer.CookieCollection.ReceiveUserCookie();
            var item = Listener.ReceiveItemsOfType<TelemetryItem<RequestData>>(
                1,
                testListenerTimeoutInMs)[0];

            Assert.AreEqual("OK", requestResponseContainer.ResponseTask.Result.ReasonPhrase);
            Assert.AreEqual(2 + additionalCookiesLength, requestResponseContainer.CookieCollection.Count);
            Assert.AreEqual("userId", item.UserContext.Id);
            Assert.AreEqual(time, item.UserContext.AcquisitionDate.Value);
            Assert.AreEqual(userCookieStr, userCookie);
            Assert.AreEqual(userCookie, item.UserContext.Id + "|" + item.UserContext.AcquisitionDate.Value.ToString("O"));   
        }
コード例 #18
0
        public void DistinctGuidIdsForMultiThreads()
        {
            Thread[] threads = new Thread[HowManyThreads];
            Guid[][] ids = new Guid[HowManyThreads][];
            List<Guid> allIds = new List<Guid>(HowManyIds * HowManyThreads);

            IIdGenerator<Guid> idGenerator = new IdGuidGenerator();

            for (int i = 0; i < HowManyThreads; i++)
            {
                var threadId = i;
                threads[i] = new Thread(() =>
                {
                    ids[threadId] = idGenerator.Take(HowManyIds).ToArray();
                });
                threads[i].Start();
            }

            for (int i = 0; i < HowManyThreads; i++)
            {
                threads[i].Join();

                Assert.IsTrue(AssertUtil.AreUnique(ids[i]), "All ids needs to be unique");
                Assert.IsTrue(AssertUtil.AreSorted(ids[i]), "Ids array needs to be ordered");

                allIds.AddRange(ids[i]);
            }

            Assert.AreEqual(
                HowManyIds * HowManyThreads, allIds.Distinct().Count(),
                "All ids needs to be unique");
        }
コード例 #19
0
        public void GetSortedDateTimes_ReturnsCorrectList()
        {
            DateTime dateNow = DateTime.Now;

            var orderedDateRanges = new List<DateRange>();
            orderedDateRanges.Add( new DateRange( dateNow, dateNow.AddMinutes( 100 )));             // +-----------------------------------------------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(10), dateNow.AddMinutes(10)));   //   +
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(10), dateNow.AddMinutes(10)));   //   +
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(10), dateNow.AddMinutes(20)));   //   +---+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(10), dateNow.AddMinutes(30)));   //   +-------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(20), dateNow.AddMinutes(60)));   //       +----------------------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(30), dateNow.AddMinutes(60)));   //           +------------------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(40), dateNow.AddMinutes(50)));   //              +------------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(42), dateNow.AddMinutes(47)));   //                 +-----+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(45), dateNow.AddMinutes(45)));   //                    +
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(70), dateNow.AddMinutes(75)));   //                                  +---+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(90), dateNow.AddMinutes(110)));  //                                          +--------------+
            orderedDateRanges.Add(new DateRange(dateNow.AddMinutes(120), dateNow.AddMinutes(140))); //                                                            +-----------+

            var result = orderedDateRanges.GetSortedDateTimes();

            var correctDateTimes = new List<DateTime>();
            orderedDateRanges.ForEach(x => correctDateTimes.AddRange(new List<DateTime> { x.StartTime, x.EndTime }));
            correctDateTimes.Sort();

            Assert.Equal( correctDateTimes, result);
        }
コード例 #20
0
        /// <summary>
        /// Builds up a message packet from the payload passed across. The payload is modified by this method.
        /// </summary>
        /// <param name="payload"></param>
        /// <param name="isFirstMessage"></param>
        /// <returns></returns>
        private List<byte> BuildValidMessagePacket(List<byte> payload, bool isFirstMessage = true)
        {
            var checksumCalculator = new Crc16Ccitt(Crc16Ccitt.InitialiseToZero);
            var checksum = AddDCEStuffing(new List<byte>(checksumCalculator.ComputeChecksumBytes(payload.ToArray(), false)));

            var result = new List<byte>();
            if(isFirstMessage) result.Add(0x00); // prefix with a leading byte so that the listener will not reject it
            result.Add(0x10);
            result.Add(0x02);
            result.AddRange(AddDCEStuffing(payload));
            result.Add(0x10);
            result.Add(0x03);
            result.AddRange(checksum);

            return result;
        }
コード例 #21
0
        public void AllNumbersMultipleOfTest()
        {
            // Arrange
            int numberEnteredByUser = 10;
            GenerateSequence gs = new GenerateSequence();
            List<string> ExpectedOutput = new List<string>();
            List<string> ActualOutput = new List<string>();

            for (int num = 1; num <= numberEnteredByUser; num++)
            {
                // If multiple of 3
                if (num % 3 == 0 && num % 5 != 0)
                {
                    ExpectedOutput.Add("C");
                }
                else if (num % 3 != 0 && num % 5 == 0) // If multiple of 5
                {
                    ExpectedOutput.Add("E");
                }
                else if (num % 3 == 0 && num % 5 == 0) // If multiple of both 3 and 5
                {
                    ExpectedOutput.Add("Z");
                }
                else // If not multiple of niether 3 or 5
                {
                    ExpectedOutput.Add(num.ToString());
                }
            }

            // Act
            ActualOutput.AddRange(gs.AllNumbersMultipleOf(numberEnteredByUser));

            // Assert
            NUnit.Framework.Assert.AreEqual(ExpectedOutput, ActualOutput, "Sequences do not match!");
        }
コード例 #22
0
        public void TestContains() {
            var list = new List<int>();
            list.AddRange(Enumerable.Range(10, 100));

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(((IEnumerable) list).Contains(49));
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsFalse(((IEnumerable) list).Contains(201));
        }
        public void PriceTypeStationBuy5Pc_PassValidTypeIdList_MatchKnownValue()
        {
            IDictionary<int, double> priceList;
            int stationId = 60003760;
            double expectedPrice = 12901.26;
            double actualPrice = 0;
            string apiUrl = "Fakes/MarketDataLocationPricesApiV1Tests_PriceTypeStationBuy5Pc_PassValidTypeIdList_MatchKnownValue.xml";

            // Instantiate and populate a large list of type ids.
            List<int> typeIdList = new List<int>();
            typeIdList.Add(16229);
            typeIdList.Add(16229);
            typeIdList.Add(16229); // Duplicate Ids.
            typeIdList.AddRange(Enumerable.Range(16230, 100));

            // Populate the dictionary with the XML values.
            priceList = this.marketDataLocationPricesApiV1.PriceTypeStationBuy5Pc(typeIdList, stationId, apiUrl);

            // Output the full list.
            foreach (KeyValuePair<int, double> pair in priceList)
            {
                System.Diagnostics.Debug.WriteLine("{0}, {1}", pair.Key, pair.Value);
            }

            priceList.TryGetValue(16297, out actualPrice);

            Assert.AreEqual(expectedPrice, actualPrice);
        }
コード例 #24
0
        public void AddExtension()
        {
            bool directoryExists = Directory.Exists("Maperitive");

            Assert.IsTrue(directoryExists);

            if (directoryExists)
            {
                CreateDirectoriesRelative("Maperitive/", "Extension/");
                string[] directories = Directory.GetDirectories("Maperitive", "*", SearchOption.AllDirectories);

                List<string> directoryList = new List<string> { "Maperitive" };
                directoryList.AddRange(directories);

                foreach (string directory in directoryList)
                {
                    string[] files = Directory.GetFiles(directory);

                    foreach (string file in files)
                    {
                        string extension = Path.GetExtension(file);

                        if (extension != ".mapper")
                        {
                            FileStream originalFile = File.OpenRead(file);
                            FileStream compressedFile = File.Create(file.Replace("Maperitive\\", "Extension\\") + ".mapper");

                            originalFile.CopyTo(compressedFile);
                            compressedFile.Close();
                            originalFile.Close();
                        }
                    }
                }
            }
        }
コード例 #25
0
ファイル: UnitTest1.cs プロジェクト: 9073194/Farseer.Net
        /// <summary>
        /// 动态创建一个 ID == value的表达式树
        /// </summary>
        /// <param name="exp">右值</param>
        /// <param name="memberName">左边ID成员名称</param>
        public static Expression CreateBinaryExpression(Expression exp, object val)
        {
            switch (exp.NodeType)
            {
                case ExpressionType.Lambda: return CreateBinaryExpression(((LambdaExpression)exp).Body, val);
                case ExpressionType.Convert: return CreateBinaryExpression(((UnaryExpression)exp).Operand, val);
            }

            var lstExp = new List<Expression>();
            if (exp.NodeType == ExpressionType.New) { lstExp.AddRange(((NewExpression)exp).Arguments); }
            else { lstExp.Add(exp); }


            Expression result = null;
            foreach (var expression in lstExp)
            {
                var memExp = (MemberExpression)expression;
                var oParam = Expression.Constant(val, val.GetType());
                var binaryExp = Expression.AddAssign(expression, Expression.Convert(oParam, memExp.Type));
                if (result == null)
                {
                    result = binaryExp;
                }
                else
                {
                    result = Expression.And(result, binaryExp);
                }
            }
            return result;
        }
        protected IList<SyntaxNode> GetExpectedDescendants(IEnumerable<SyntaxNode> nodes, ImmutableArray<SyntaxKind> expected)
        {
            var descendants = new List<SyntaxNode>();
            foreach (var node in nodes)
            {
                if (expected.Any(e => e == node.Kind()))
                {
                    descendants.Add(node);
                    continue;
                }

                foreach (var child in node.ChildNodes())
                {
                    if (expected.Any(e => e == child.Kind()))
                    {
                        descendants.Add(child);
                        continue;
                    }

                    if (child.ChildNodes().Count() > 0)
                        descendants.AddRange(GetExpectedDescendants(child.ChildNodes(), expected));
                }
            }
            return descendants;
        }
コード例 #27
0
ファイル: XMLGenerator.cs プロジェクト: oneminot/everest
        internal static bool GenerateInstance(Type instanceType, Stream outputStream, out IResultDetail[] details)
        {

            string resourceName = String.Format(instanceType.FullName).Replace(".", "");

            var formatter = new MARC.Everest.Formatters.XML.ITS1.XmlIts1Formatter();
            formatter.Settings = MARC.Everest.Formatters.XML.ITS1.SettingsType.DefaultUniprocessor;
            formatter.ValidateConformance = false;
            // Testing pregen
            formatter.GraphAides.Add(new MARC.Everest.Formatters.XML.Datatypes.R1.DatatypeFormatter());
            formatter.BuildCache(Assembly.Load("MARC.Everest.RMIM.CA.R020402").GetTypes());

            IGraphable result = TypeCreator.GetCreator(instanceType).CreateInstance() as IGraphable;

            Trace.WriteLine("Starting Serialization");
            DateTime start = DateTime.Now;
            var gresult = formatter.Graph(outputStream, result);
            Trace.WriteLine(String.Format("            ->{0}", DateTime.Now.Subtract(start).TotalMilliseconds));
            Trace.WriteLine(String.Format("            ->{0} bytes", outputStream.Length));
            List<IResultDetail> dlist = new List<IResultDetail>();
            dlist.AddRange(gresult.Details);
            details = dlist.ToArray();

            return gresult.Code == MARC.Everest.Connectors.ResultCode.Accepted;
        }
コード例 #28
0
        public void SetUp()
        {
            _factory = new MockFactory();

            List<CommonEvent> mockResult;

            var mock1 = _factory.CreateMock<BaseEventCollector>();
            mockResult = new List<CommonEvent>();
            mockResult.AddRange(new[]
                      {
                          new CommonEvent(0, "100", "Mock1Event1", new DateTime(2013,10,15), null, "", "", "", "", "", ""),
                          new CommonEvent(0, "100", "Mock1Event2", new DateTime(2013,10,1), null, "", "", "", "", "", ""),
                      });
            mock1.Expects.One.MethodWith(x => x.GetEvents(201307, "松山")).WillReturn(mockResult);

            var mock2 = _factory.CreateMock<BaseEventCollector>();
            mockResult = new List<CommonEvent>();
            mockResult.AddRange(new[]
                      {
                          new CommonEvent(0, "100", "Mock2Event1", new DateTime(2013,10,8), null, "", "", "", "", "", ""),
                          new CommonEvent(0, "100", "Mock2Event2", new DateTime(2013,10,30), null, "", "", "", "", "", ""),
                          new CommonEvent(0, "100", "Mock2Event3", new DateTime(2013,10,25), null, "", "", "", "", "", ""),
                      });
            mock2.Expects.One.MethodWith(x => x.GetEvents(201307, "松山")).WillReturn(mockResult);

            sut = new AllEventCollector(new[] { mock1.MockObject, mock2.MockObject });
        }
コード例 #29
0
        public void TestTake() {
            var list = new List<int>();
            list.AddRange(Enumerable.Range(0, 100));

            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(Enumerable.Range(0, 9).Cast<object>().SequenceEqual(((IEnumerable) list).Take(9).Cast<object>().ToArray()));
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsTrue(Enumerable.Range(0, 9).Cast<object>().SequenceEqual(((IEnumerable) list).Take(9).Cast<object>().ToList().Cast<object>()));
        }
コード例 #30
0
        public void AddWorks()
        {
            var bytecode = new List<byte>();
            bytecode.Add(Bytecode.PUSH_INT);
            bytecode.AddRange(BitConverter.GetBytes(23L));
            bytecode.Add(Bytecode.PUSH_INT);
            bytecode.AddRange(BitConverter.GetBytes(170L));
            bytecode.Add(Bytecode.ADD);

            var interpreter = new Interpreter(bytecode.ToArray(), new List<string> { "" }, null, 0);
            interpreter.Run();

            Assert.AreEqual(1, interpreter.Stack.Count);
            Assert.AreEqual(193, interpreter.Stack.Pop());
            Assert.AreEqual(19, interpreter.PC);
        }