Beispiel #1
0
	public static void Main(string[] args) {
		try {
			DataLexer lexer = new DataLexer(new ByteBuffer(Console.OpenStandardInput()));
			DataParser parser = new DataParser(lexer);
			parser.file();
		} catch(Exception e) {
			Console.Error.WriteLine("exception: "+e);
		}
	}
 internal static void Main()
 {
     var db = new BookstoreContext();
     var xmlDoc = XElement.Load(@"../../../DataFiles/complex-books.xml");
     var parser = new DataParser(db, xmlDoc);
     parser.Parse();
     xmlDoc = XElement.Load(@"../../../DataFiles/reviews-queries.xml");
     var querer = new QueryParser(db, xmlDoc);
     querer.Parse();
 }
        /// <summary>
        /// Parses the XML response from VisMasters.com.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="dataParser"></param>
        /// <returns></returns>
        public static Response parse(string response, DataParser dataParser)
        {
            string responseThatWontThrowExceptions = response.Replace("<br>", "\n");
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(responseThatWontThrowExceptions);

            Response ret = Response.fromResponseXml(xml);
            if (ret.Status != 0)
            {
                ret.RawData = xml.SelectSingleNode("/vismasters/response/data").InnerXml;
                ret.Data = dataParser(xml.SelectSingleNode("/vismasters/response/data"));
            }
            return ret;
        }
        private void btn_buildNgramfromDB_Click(object sender, EventArgs e)
        {
            String[] Languages = "'eu';,'ca';,'gl';,'es';,'en';,'pt';".Split(',');
            FileWriter FW = new FileWriter();
            for (int i = 0; i < Languages.Length; i++)
            {
                FetchFromDB fetchFromDatabase = new FetchFromDB();
                DataTable dataTable = fetchFromDatabase.getTrainingDataFor(Languages[i]);
                fetchFromDatabase.closeConnection();

                DataParser DP = new DataParser();
                DataTable cleanTable = new DataTable();
                cleanTable = DP.getCleanTable(dataTable);

                NgramBuilder NB = new NgramBuilder();

                DataTable uniGram = new DataTable();
                uniGram = NB.GetGram(cleanTable, 1);
                double uniGramN = NB.getTotalFrequency();

                DataTable smoothedUniGram = new DataTable();
                smoothedUniGram = NB.applySmoothing(uniGram, 0.1);
                double uniGramSmoothedN = NB.getTotalFrequency();

                DataTable biGram = new DataTable();
                biGram = NB.GetGram(cleanTable, 2);
                double biGramN = NB.getTotalFrequency();

                DataTable smoothedBiGram = new DataTable();
                smoothedBiGram = NB.applySmoothing(biGram, 0.1);
                double BiGramSmoothedN = NB.getTotalFrequency();

                //FileWriter FW = new FileWriter();

                FW.writeUniGram(uniGram, Languages[i], "False", uniGramN);
                FW.writeUniGram(smoothedUniGram, Languages[i], "True", uniGramSmoothedN);

                FW.writeBiGram(biGram, Languages[i], "False", biGramN);
                FW.writeBiGram(smoothedBiGram, Languages[i], "True", BiGramSmoothedN);

                MessageBox.Show("Done " + Languages[i]);

            }
            FW.closeWriter();
        }
Beispiel #5
0
        private int QueryDataHandler(CallerToken token, DataParser dataParser)
        {
            List <UFXQueryFuturesEntrustResponse> responseItems = new List <UFXQueryFuturesEntrustResponse>();
            var errorResponse = T2ErrorHandler.Handle(dataParser);

            token.ErrorResponse = errorResponse;

            if (T2ErrorHandler.Success(errorResponse.ErrorCode))
            {
                responseItems = UFXDataSetHelper.ParseData <UFXQueryFuturesEntrustResponse>(dataParser);
            }

            try
            {
                var entrustFlowItems = GetFlowItems(token, responseItems);

                if (token.OutArgs != null &&
                    token.OutArgs is List <EntrustFlowItem> &&
                    entrustFlowItems != null &&
                    entrustFlowItems.Count > 0
                    )
                {
                    ((List <EntrustFlowItem>)token.OutArgs).AddRange(entrustFlowItems);
                }

                if (token.Caller != null)
                {
                    token.Caller(token, entrustFlowItems, errorResponse);
                }
            }
            finally
            {
                if (token.WaitEvent != null)
                {
                    token.WaitEvent.Set();
                }
            }

            return(responseItems.Count());
        }
Beispiel #6
0
        public override void parse(byte[] data)
        {
            DataParser parser = new DataParser(data);

            if (parser.getStringFixed(4) != "BMP:")
            {
                throw new Exception("Expected BMP: header block");
            }
            Width  = parser.getWord();
            Height = parser.getWord();
            if (parser.getStringFixed(4) != "INF:")
            {
                throw new Exception("Expected INF: header block");
            }
            DataSize = parser.getDWord(); // size of "no of images" + (images*(size of with+height))
            Images   = parser.getWord();
            Widths   = new UInt16[Images];
            for (int j = 0; j < Images; j++)
            {
                Widths[j] = parser.getWord();
            }
            Heights = new UInt16[Images];
            for (int j = 0; j < Images; j++)
            {
                Heights[j] = parser.getWord();
            }
            if (parser.getStringFixed(4) != "BIN:")
            {
                throw new Exception("Expected BIN: header block");
            }
            BMPSize = parser.getDWord() - 5; // discard size of compressionmethod+uncompressedsize
            BMPCompressionMethod = parser.getByte();
            BMPUncompressedSize  = parser.getDWord();
            BMPData = parser.getBytes(BMPSize);

            Compression lzw = new Compression();

            data   = lzw.decompress(BMPData, BMPCompressionMethod);
            images = Tools.getBitmaps(data, Widths, Heights);
        }
Beispiel #7
0
 public void Admin_LimitedPermissionAcess_WS_1208()
 {
     if (!DataParser.ReturnExecution("WS_1208"))
     {
         Assert.Ignore();
     }
     else
     {
         _file = "Resources\\" + client + "\\TestsData\\WS_1208.xml";
         string       user  = AwardData.GetAwardUserName(_file);
         MainHomePage proxy = InitialPage.Go().Logon().ClickLogin().NavigateToAdminHomePageSpan().
                              ClickOptionProxy("Proxy").EnterUserNameProxySprint2(user).ProxyToMainHomePageSprint().ClosePopUp();
         Assert.AreEqual("You are proxied in as:" + user, proxy.GetProxyLoginMsgSprint(),
                         "The message of proxy login is not correct");
         Assert.AreEqual("Exit Proxy", proxy.GetExitMsg(), "The exit proxy link is not present");
         ProxyHomePage admin = proxy.NavigateToAdminHomePageSpan();
         Assert.IsTrue(admin.IsBulkAwardOptPresent(), "Bulk Award Upload is not present");
         Assert.IsTrue(admin.IsProxyOptPresent(), "Proxy is not present");
         Assert.IsTrue(admin.IsBudgetToolOptPresent(), "Budget tool is not present");
         Assert.IsTrue(admin.IsPendingApprovalsOptPresent(), "Pending Approvals is not present");
     }
 }
Beispiel #8
0
        public void TestCase3()
        {
            var listInputs = new List <string>()
            {
                "1 imported bottle of perfume at £27.99",
                "1 bottle of perfume at £18.99",
                "1 packet of headache pills at £9.75",
                "1 imported box of chocolates at £11.25"
            };
            var listOfProducts = new List <Product>();
            var dataParser     = new DataParser(new CategoryManager());

            foreach (var input in listInputs)
            {
                listOfProducts.Add(dataParser.Parse(input));
            }

            var taxCalculator = new TaxCalculator();

            taxCalculator.Proceed(listOfProducts);
            Assert.IsTrue(taxCalculator.SalesTaxes == 6.70 && taxCalculator.Total == 74.68);
        }
        public void SingleEntitySelector()
        {
            var service     = LocalSpiderProvider.Value.CreateScopeServiceProvider();
            var dataContext =
                new DataFlowContext(
                    new Response
            {
                Request = new Request("http://abcd.com"),
                Content = Encoding.UTF8.GetBytes(Html),
                CharSet = "UTF-8"
            }, service);

            var parser = new DataParser <N>();


            parser.HandleAsync(dataContext).GetAwaiter().GetResult();

            var results = (ParseResult <N>)dataContext.GetParseData(typeof(N).FullName);

            Assert.Equal("i am title", results[0].title);
            Assert.Equal("i am dotnetspider", results[0].dotnetspider);
        }
Beispiel #10
0
        public new async Task <ActionResult> Profile(int userId)
        {
            string response = await clsBandRequests.GetBandInfo(userId);

            string response2 = await clsBandRequests.getBandAlbums(userId);

            //Hubo error
            if (!ErrorParser.parse(response).Equals(""))
            {
                ViewBag.Message = "F**k my life...";
            }

            BandProfileViewModel profile = new BandProfileViewModel();

            profile.Id       = Int32.Parse(Session["Id"].ToString());
            profile.Username = Session["Username"].ToString();
            profile.Name     = Session["Name"].ToString();
            profile.Info     = DataParser.parseBandInfo(response);

            profile.Albums = DataParser.parseAlbums(response2);
            return(View(profile));
        }
Beispiel #11
0
        public RegularGrid Load(string filename)
        {
            RegularGrid  grid = new RegularGrid();
            StreamReader sr   = new StreamReader(filename);
            string       line = sr.ReadLine();

            grid.NCell = int.Parse(line.Trim());
            line       = sr.ReadLine();
            var buf = DataParser.Split <double>(line);

            grid.CellSize  = buf[0];
            grid.CentroidX = new double[grid.NCell];
            grid.CentroidY = new double[grid.NCell];
            for (int i = 0; i < grid.NCell; i++)
            {
                line = sr.ReadLine();
                buf  = DataParser.Split <double>(line);
                grid.CentroidX[i] = buf[0];
                grid.CentroidY[i] = buf[1];
            }
            return(grid);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            List <DataModel> datas = new DataParser("asd.csv").LoadFromTextFile();

            //asd123
            using var sw = new StreamWriter("result.csv");
            sw.WriteLine("No,Ido,Bemenet,Re,Im,Magnitude,dB,Phase");
            foreach (var d in datas)
            {
                List <Complex> cmplx = new List <Complex>();
                foreach (var item in d.RawData)
                {
                    cmplx.Add(new Complex(item));
                }

                var result = new FourierTransformation().FastFourierTransformation(cmplx.Take(256).ToArray());
                for (int i = 0; i < result.Length; i++)
                {
                    sw.WriteLine($"{i},{d.RecordTime},{d.RawData[i]},{result[i].Real},{result[i].Imaginary},{result[i].Magnitude},{result[i].Decibell},{result[i].Phase}");
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// Analyze replay locally before uploading
        /// </summary>
        /// <param name="file">Replay file</param>
        public void Analyze(ReplayFile file)
        {
            try {
                var result = DataParser.ParseReplay(file.Filename, false, false, false, true);
                switch (result.Item1)
                {
                case DataParser.ReplayParseResult.ComputerPlayerFound:
                case DataParser.ReplayParseResult.TryMeMode:
                    file.UploadStatus = UploadStatus.AiDetected;
                    return;

                case DataParser.ReplayParseResult.PTRRegion:
                    file.UploadStatus = UploadStatus.PtrRegion;
                    return;

                case DataParser.ReplayParseResult.PreAlphaWipe:
                    file.UploadStatus = UploadStatus.TooOld;
                    return;
                }

                if (result.Item1 != DataParser.ReplayParseResult.Success)
                {
                    return;
                }

                var replay = result.Item2;

                if (replay.ReplayBuild < MinimumBuild)
                {
                    file.UploadStatus = UploadStatus.TooOld;
                    return;
                }

                file.Fingerprint = GetFingerprint(replay);
            }
            catch (Exception e) {
                _log.Warn(e, $"Error analyzing file {file}");
            }
        }
Beispiel #14
0
 public void Admin_TestSupportPermissionAccess_WS_1204()
 {
     if (!DataParser.ReturnExecution("WS_1204"))
     {
         Assert.Ignore();
     }
     else
     {
         ProxyHomePage admin = InitialPage.Go().Logon().ClickLogin().NavigateToAdminHomePageSpan();
         Assert.IsTrue(admin.IsBulkAwardOptPresent(), "Bulk Award Upload is not present");
         Assert.IsTrue(admin.IsProxyOptPresent(), "Proxy is not present");
         Assert.IsTrue(admin.IsBudgetToolOptPresent(), "Budget tool is not present");
         Assert.IsTrue(admin.IsPendingApprovalsOptPresent(), "Pending Approvals is not present");
         Assert.IsTrue(admin.IsEditRewardCartUserMessageOptPresent(),
                       "Edit Reward Cart User Message is not present");
         Assert.IsTrue(admin.IsProxyManagerOptPresent(), "Proxy Manager is not present");
         Assert.IsTrue(admin.IsDeletedUnusedAwardOptPresent(), "Deleted Unused Award is not present");
         Assert.IsTrue(admin.IsEditPendingAwardsOptPresent(), "Edit Pending Awards is not present");
         Assert.IsTrue(admin.IsDebugRuleOptPresent(), "Debug Rule is not present");
         Assert.IsTrue(admin.IsDebugReportOptPresent(), "Debug Report is not present");
     }
 }
Beispiel #15
0
        public async Task SingleEntitySelector()
        {
            var request     = new Request("http://abcd.com");
            var dataContext =
                new DataContext(null, new SpiderOptions(), request,
                                new Response {
                Content = new ResponseContent {
                    Data = Encoding.UTF8.GetBytes(Html)
                }
            });

            var parser = new DataParser <N>();

            parser.SetHtmlSelectableBuilder();

            await parser.HandleAsync(dataContext);

            var results = (List <N>)dataContext.GetData(typeof(N));

            Assert.Equal("i am title", results[0].title);
            Assert.Equal("i am dotnetspider", results[0].dotnetspider);
        }
Beispiel #16
0
 public void Recognition_AwardDeliveryTypes_WS_218()
 {
     if (!DataParser.ReturnExecution("WS_218"))
     {
         Assert.Ignore();
     }
     else
     {
         _file = "Resources\\" + client + "\\TestsData\\WS_218.xml";
         AwardData.GetAwardImpact(_file);
         string user = AwardData.GetAwardUserName(_file),
                award = AwardData.GetAwardName(_file),
                value = AwardData.GetAwardValue(_file),
                amount = AwardData.GetAwardAmountValue(_file), printype = AwardData.GetAwardDeliverType(_file),
                msg    = AwardData.GetAwardMessage(_file),
                reason = AwardData.GetAwardMessage(_file);
         NominationHomePage recognitionPage = InitialPage.Go().Logon().ClickLogin().NavigateToNomination();
         recognitionPage
         .SearchEmployeeFound(user)
         .SelectAward(award)
         .SelectValueOfAward(amount)
         .SelectValues(value)
         .FillMsg(msg)
         .FillReason(reason).ClickNext();
         Assert.AreEqual("I want to Email this award.", recognitionPage.GetDeliverLabel("email"),
                         "Label is not correct");
         Assert.AreEqual("I want to print this award.", recognitionPage.GetDeliverLabel("print"),
                         "Label is not correct");
         recognitionPage.DeliverType(printype);
         Assert.AreEqual(2, recognitionPage.GetCountEditLnk(), "Edit links are not two");
         Assert.AreEqual("Ready to send?", recognitionPage.GetReadyToSendMsg(),
                         "The message is not ready to send");
         recognitionPage.ClickSendRecognition();
         Assert.AreEqual("Success!", recognitionPage.GetSuccesMsg(), "Message its not success");
         Assert.AreEqual("FINISH", recognitionPage.GetBtnFinishLabel(), "Button finish its not correct write");
         Assert.AreEqual("RECOGNIZE", recognitionPage.GetBtnRecognizOtherLabel(),
                         "Button finish its not correct write");
     }
 }
        public void CanParseDataTest()
        {
            var parser    = new DataParser(new TestableDataProvider(), new ReflectionMapper());
            var questions = parser.ProcessData(typeof(Question)).Cast <Question>().ToList();

            questions.Should().NotBeNullOrEmpty();
            questions.Should().HaveCount(5, "First row contains headers");

            // First item
            var item = questions.First();

            item.Title.Should().Be("Test 1");
            item.GoodDescription.Should().Be("Good 1");
            item.BadDescription.Should().Be("Bad 1");

            // Second item
            item = questions.Skip(1).First();
            item.Title.Should().Be("Test 2");
            item.GoodDescription.Should().Be("Good 2");
            item.BadDescription.Should().BeNull();

            // Third item
            item = questions.Skip(2).First();
            item.Title.Should().Be("Test 3");
            item.GoodDescription.Should().BeNull();
            item.BadDescription.Should().Be("Bad 3");

            // Fourth item
            item = questions.Skip(3).First();
            item.Title.Should().BeNull();
            item.GoodDescription.Should().Be("Good 4");
            item.BadDescription.Should().Be("Bad 4");

            // Fifth item
            item = questions.Skip(4).First();
            item.Title.Should().BeNull();
            item.GoodDescription.Should().BeNull();
            item.BadDescription.Should().Be("Bad 5");
        }
Beispiel #18
0
 public void Cart_PayCalculation_WS_1315()
 {
     if (!DataParser.ReturnExecution("WS_1315"))
     {
         Assert.Ignore();
     }
     else
     {
         GoToMallHomePage mallPage = InitialPage.Go().EnterId(client).Logon().ClickLogin().NavigateToMall();
         mallPage.CheckOptionPurchaseType("Email (Instant)");
         CompanyGiftCard giftCard = mallPage.SearchCompany("Groupon").SelectCompany();
         CompanyGifCart  gifcart = giftCard.ClickPlusAmount().ClickAddToCart().ClickGoToCart();
         int             total = gifcart.GetTotal(), quant = gifcart.GetQuantity(), amount = gifcart.GetAmount();
         Assert.AreEqual(total, quant * amount, "Is not equal");
         gifcart.ClickPlusQuant();
         gifcart.Refresh();
         total  = gifcart.GetTotal();
         quant  = gifcart.GetQuantity();
         amount = gifcart.GetAmount();
         Assert.AreEqual(total, quant * amount, "Is not equal");
     }
 }
Beispiel #19
0
 public void CheckOut_WrongZip_WS_1307()
 {
     if (!DataParser.ReturnExecution("WS_1307"))
     {
         Assert.Ignore();
     }
     else
     {
         _file = "Resources\\" + client + "\\TestsData\\WS_1307.xml";
         string company            = RedeemData.GetRedeemCompany(_file),
                firstname          = RedeemData.GetRedeemFirstName(_file),
                secondname         = RedeemData.GetRedeemSecondName(_file),
                address            = RedeemData.GetRedeemAddress(_file),
                city               = RedeemData.GetRedeemCity(_file),
                zip                = RedeemData.GetRedeemZip(_file),
                phone              = RedeemData.GetRedeemPhone(_file),
                state              = RedeemData.GetRedeemState(_file);
         GoToMallHomePage mallPage = InitialPage.Go().EnterId(client).Logon().ClickLogin().NavigateToMall();
         mallPage.CheckOptionPurchaseType("Email (Instant)");
         CompanyGiftCard giftCard = mallPage.SearchCompany("Buffalo").SelectCompany();
         CheckOutPage    checkout = giftCard.ClickPlusAmount().ClickAddToCart().ClickGoToCart().ClickCheckOut();
         checkout.FillName(firstname)
         .FillLastName(secondname)
         .FillAddress(address)
         .FillCity(city)
         .SelectState(state)
         .FillZipCode(zip)
         .FillPhoneNumber(phone);
         Assert.IsFalse(checkout.CannotEditEmail(), "Email txt field is editable");
         checkout.ClickNext();
         Assert.AreEqual("We got you covered Work Stride", checkout.GetNoCreditCardUseMsg(),
                         "The message is wrong or its possible to use the credit card");
         Assert.AreEqual("Your rewards have covered your balance.\r\nEnjoy your gift.",
                         checkout.GetNoCreditCardUseMsgSubtitle(),
                         "The message is wrong or its possible to use the credit card");
         checkout.ClickNextPayment().ClickCheckOut();
         // BUG not showing error msg
     }
 }
Beispiel #20
0
 public void VisaCard_ReloadWithBalance_WS_1279()
 {
     if (!DataParser.ReturnExecution("WS_1279"))
     {
         Assert.Ignore();
     }
     else
     {
         MainHomePage home = InitialPage.Go().Logon().ClickLogin();
         Thread.Sleep(1500);
         Assert.LessOrEqual("25.00", home.GetRewardsBalance(),
                            "The rewards balance is less than $25");
         VisaCenterHomePage visaPage = home.NavigateToVisaCenter();
         Assert.IsFalse(visaPage.IsSubmitAClaimPresent(), "Option is not present");
         Assert.IsTrue(visaPage.IsReloadYourCardPresent(), "Reload your card option is present");
         Assert.IsTrue(visaPage.IsCheckVisaCardBalance(), "Check Visa Card Balance option is present");
         var balance = visaPage.GetBalance();
         Assert.IsTrue(visaPage.IsAmountFieldAvl(), "Amount field is not available");
         visaPage.EnterAmount("100").ClickReloadCard();
         Assert.AreEqual(balance - 100, visaPage.GetBalance(), "Balance was not right decresing the amount");
     }
 }
Beispiel #21
0
        /// <summary>Get unfinished bundles which require this item.</summary>
        /// <param name="item">The item for which to find bundles.</param>
        private IEnumerable <BundleModel> GetUnfinishedBundles(Object item)
        {
            // no bundles for Joja members
            if (Game1.player.hasOrWillReceiveMail(Constant.MailLetters.JojaMember))
            {
                yield break;
            }

            // get community center
            CommunityCenter communityCenter = Game1.locations.OfType <CommunityCenter>().First();

            if (communityCenter.areAllAreasComplete())
            {
                yield break;
            }

            // get bundles
            foreach (BundleModel bundle in DataParser.GetBundles())
            {
                // ignore completed bundle
                if (communityCenter.isBundleComplete(bundle.ID))
                {
                    continue;
                }

                // get ingredient
                BundleIngredientModel ingredient = bundle.Ingredients.FirstOrDefault(p => p.ItemID == item.parentSheetIndex && p.Quality <= (ItemQuality)item.quality);
                if (ingredient == null)
                {
                    continue;
                }

                // yield if missing
                if (!communityCenter.bundles[bundle.ID][ingredient.Index])
                {
                    yield return(bundle);
                }
            }
        }
Beispiel #22
0
        public static Replay ParseRejoin(string fileName)
        {
            try {
                var replay = new Replay();

                var archive = new MpqArchive(fileName);
                archive.AddListfileFilenames();

                // Replay Details
                ReplayDetails.Parse(replay, DataParser.GetMpqFile(archive, "save.details"), true);

                // Player level is stored there
                ReplayAttributeEvents.Parse(replay, DataParser.GetMpqFile(archive, "replay.attributes.events"));

                return(replay);
            }
            catch (Exception ex) {
                //TODO: WE REALLY DON't want to do this
                Debug.WriteLine(ex);
                return(null);
            }
        }
        public static IEnumerable <CustomerModel> Execute(string[] args)
        {
            ConsoleInput input = new ConsoleInput();

            ParseFilePath(args[0], ref input);
            IEnumerable <string> lines = null;

            if (input.FilePath != null)
            {
                lines = File.ReadLines(input.FilePath);
                ParseDelimiter(args[1], ref input);
                ParseCommand(args[2], ref input);
                ParseCommandOption(args[3], ref input);
            }

            CustomerCollection collection = new CustomerCollection();
            var customers = DataParser.Execute(lines, input.Delimiter);

            collection.AddRange(customers);

            return(collection.Sort(input.CommandOption));
        }
        public void CanParseDynamicDataTest()
        {
            var newModel = JsonConvert.DeserializeObject <JObject>(_jsonObject);
            var builder  = new RuntimeTypeBuilder(nameof(_jsonObject));

            foreach (var property in newModel.Properties())
            {
                builder.Properties.Add(property.Name, GetType(property.Type));
            }

            var modelType = builder.Compile();

            var parser    = new DataParser(new TestableDataProvider(), new ReflectionMapper());
            var questions = parser.ProcessData(modelType).ToList();

            questions.Should().NotBeNullOrEmpty();
            questions.Should().HaveCount(5, "First row contains headers");

            var resultString = JsonConvert.SerializeObject(questions);

            resultString.Should().Be(_jsonResult);
        }
Beispiel #25
0
        private MexCore()
        {
            //Bilge.Log("MexCore::MexCore - Core being initialised");

            EventEntryStoreFactory esf   = new EventEntryStoreFactory();
            DataManager            dm    = new DataManager(esf);
            OriginIdentityStore    store = new OriginIdentityStore();
            RawEntryParserChain    rapc  = RawEntryParserChain.CreateChain(RawEntryParserChain.ALL_LINK, store);
            DataParser             dp    = new DataParser(store, rapc, dm);
            ImportManager          im    = new ImportManager(dp);

            //Bilge.Log("MexCore::MexCore - Diagnostics being initialised");
            Diagnostics = new MexDiagnosticManager();

            //Bilge.Log("MexCore::MexCore - about to start Options");
            Options = new MexOptions();

            //Bilge.Log("MexCore::MexCore - about to start WorkManager");
            WorkManager = PrimaryWorkManager.GetPrimaryWorkManager();

            //Bilge.Log("MexCore::MexCore - about to start DataStructures");
            DataManager = new DataStructureManager();

            //Bilge.Log("MexCore::MexCore - about to start IncommingMessageManager");
            MessageManager = IncomingMessageManager.Current;
            //MessageManager.AddFlimFlamCompatibility(im);

            //Bilge.Log("MexCore::MexCore - about to start ViewManager");
            ViewManager = new ViewSupportManager();

            //Bilge.Log("MexCore::MexCore - about to start CacheManager");
            CacheManager = new CacheSupportManager();

            //Bilge.Log("MexCore::MexCore - Starting CoreWorkerThread");
            m_coreExecutionThread      = new Thread(new ThreadStart(CoreThreadLoop));
            m_coreExecutionThread.Name = "MexCoreThread";

            //Bilge.Log("MexCore::MexCore - Construction complete");
        }
Beispiel #26
0
        private void ShowGameResult()
        {
            if (m_gameType == GameType.Normal)
            {
                var players = m_game.Players.OrderByDescending(player => player.Colonies.Count);

                m_trainSets.AddRange(m_game.Gameplay.TrainSets);
                DataParser.Serialize(m_trainSets);

                Invoke((MethodInvoker) delegate
                {
                    ResetGameToolStripEnabled(true);
                    GameplayControlGroupBoxEnabled(false);
                });

                MessageBox.Show("Game has finished! Here are the result:\n" +
                                players.Select(player => $"{player}: {player.Colonies.Count}").
                                Aggregate((p1, p2) => p1 + "\n" + p2), "Information",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                ClearEnvironmentPanel();
                m_worldMap.Close();
                m_worldMap.Dispose(); // this is needed as we override OnFormClosing()

                var players = m_game.Players;
                players.ForEach(player => player.Colonies.Clear());

                ShowWorldMap();
                GameToolStripEnabled(true);
                PlayersAndStartGameToolStripsEnabled(true);
                ResetGameToolStripEnabled(false);
                LoadEnvironment();

                GaCycle(++m_gaCurrentGen);
            }
        }
Beispiel #27
0
 public void Recognition_UploadAttachments_WS_1166_Sample2()
 {
     if (!DataParser.ReturnExecution("WS_1166"))
     {
         Assert.Ignore();
     }
     else
     {
         _file = "Resources\\" + client + "\\TestsData\\WS_1166.xml";
         AwardData.GetAwardImpact(_file);
         string user            = AwardData.GetAwardUserName(_file),
                award           = AwardData.GetAwardName(_file),
                value           = AwardData.GetAwardValue(_file),
                secondvalue     = AwardData.GetAwardSecondValue(_file),
                file_name       = GeneralData.GetFileName(_file),
                path_file_wrong = GeneralData.GetPathWrongFile(_file).Trim(),
                reason          = AwardData.GetAwardMessage(_file),
                path_file       = GeneralData.GetPathFile(_file).Trim(),
                proxy_name      = ProxyData.GetProxyUserName(_file);
         //Scenario 2
         NominationHomePage recognitionPage = InitialPage.Go().Logon().ClickLogin().NavigateToAdminHomePage().LoginProxyAsuser()
                                              .EnterUserName(proxy_name).ProxyToMainHomePage().ClosePopUp().NavigateToNomination();
         recognitionPage
         .SearchEmployeeFound(user)
         .SelectAward(award)
         .SelectValues(value)
         .SelectValues(secondvalue)
         .FillReason(reason);
         recognitionPage.ClickUploadFile();
         foreach (char a in path_file_wrong)
         {
             SendKeys.SendWait(a.ToString());
             Thread.Sleep(30);
         }
         SendKeys.SendWait("{ENTER}");
         Assert.AreEqual("You can't upload files of this type.", recognitionPage.GetErrorMsguploadFile(), "The file was upload correctly or the msg is not right");
     }
 }
Beispiel #28
0
    void Start()
    {
        map = Map.GetMap(PlayerProperties.CurrentMap);

        if (map.backgroundPath != null && map.backgroundPath.Length > 0)
        {
            if (!map.backgroundPath.ToLower().EndsWith(".png") && !map.backgroundPath.ToLower().EndsWith(".jpg") && !map.backgroundPath.ToLower().EndsWith(".jpeg"))
            {
                GameObject prefab = Instantiate(Resources.Load <GameObject>(map.backgroundPath));
            }
            else
            {
                UI_Background.sprite = DataParser.GetSpriteFromFile(map.backgroundPath);
                UI_Background.color  = Color.white;
            }
            UI_MapName.text = map.mapName;
        }

        string spritePath = NPC.GetNpc(map.npc).spritePath;

        if (spritePath != null && spritePath.Length > 0)
        {
            if (!spritePath.ToLower().EndsWith(".png"))
            {
                GameObject prefab = Instantiate(Resources.Load <GameObject>(spritePath));
            }
            else
            {
                Sprite sprite = DataParser.GetSpriteFromFile(NPC.GetNpc(map.npc).spritePath);
                UI_NPC.sprite = sprite;
                UI_NPC.color  = Color.white;
                UI_NPC.SetNativeSize();
                //float sizeMultiplier = sprite.bounds.size.y / 450.0f; //Resizes the NPC to a ySize of 850.
                //UI_NPC.rectTransform.sizeDelta = sprite.bounds.size / sizeMultiplier;
                //UI_NPC.transform.localPosition = new Vector2(0, -UIUtils.GetOutsideCanvasY(UI_NPC.rectTransform, UI_Canvas) + UI_NPC.rectTransform.rect.height);
            }
        }
    }
        private async void UploadLocation(object sender, RoutedEventArgs e)
        {
            Geolocator geolocator = new Geolocator();

            // 期望的精度级别(PositionAccuracy.Default 或 PositionAccuracy.High)
            geolocator.DesiredAccuracy = PositionAccuracy.High;
            // 期望的数据精度(米)
            geolocator.DesiredAccuracyInMeters = 50;

            try
            {
                Geoposition geoposition = await geolocator.GetGeopositionAsync();

                Dictionary <string, string> locationPair = new Dictionary <string, string>();
                locationPair.Add("ID", StaticObj.user.ID);
                locationPair.Add("LONGITUDE", geoposition.Coordinate.Point.Position.Longitude.ToString("0.000"));
                locationPair.Add("LATITUDE", geoposition.Coordinate.Point.Position.Latitude.ToString("0.000"));
                locationPair.Add("ALTITUDE", geoposition.Coordinate.Point.Position.Altitude.ToString("0.000"));
                locationPair.Add("TIME", DateTime.Now.ToString());
                locationPair.Add("POSITIONSOURCE", geoposition.Coordinate.PositionSource.ToString());

                StaticObj.SendPackets(DataParser.Str2Packets(Convert.ToInt32(CommandCode.SendLocation), JsonParser.SerializeObject(locationPair)));
                Packet[] incomming = await StaticObj.ReceivePackets();

                if (DataParser.GetPacketCommandCode(incomming[0]) == Convert.ToInt32(CommandCode.ReturnLocation))
                {
                    if (Convert.ToInt32(DataParser.Packets2Str(incomming)) != 0)
                    {
                        await(new MessageDialog(String.Format("发送成功!\n时间:{0}\n经度:{1}\n纬度:{2}海拔:{3}\n位置信息来源:{4}", locationPair["TIME"], locationPair["LONGITUDE"], locationPair["LATITUDE"], locationPair["ALTITUDE"], locationPair["POSITIONSOURCE"]))).ShowAsync();
                    }
                }
                else
                {
                    await(new MessageDialog("上传失败!")).ShowAsync();
                }
            }
            catch { }
        }
Beispiel #30
0
        public void GiveMessageWithInvalidParameter()
        {
            //Arrange
            DataParser parser = new DataParser();

            string inputString1 = "%$#4";
            int    reference    = -1;
            string refMessage1  = "Введенный параметр не является числовым значением";

            string inputString2 = "1";

            string refMessage2 = "Размер параметра не может быть меньше 2 и больше размера массива. ";

            string inputString3 = "20";

            string refMessage3 = "Размер параметра не может быть меньше 2 и больше размера массива. ";

            //Action
            int    parsedParameter1 = parser.ParseParameter(inputString1, 10);
            string message1         = parser.ValidationMessage;

            int    parsedParameter2 = parser.ParseParameter(inputString2, 10);
            string message2         = parser.ValidationMessage;

            int    parsedParameter3 = parser.ParseParameter(inputString3, 10);
            string message3         = parser.ValidationMessage;


            //Assert
            Assert.AreEqual(reference, parsedParameter1);
            Assert.IsTrue(message1.Contains(refMessage1));

            Assert.AreEqual(reference, parsedParameter2);
            Assert.IsTrue(message2.Contains(refMessage2));

            Assert.AreEqual(reference, parsedParameter3);
            Assert.IsTrue(message3.Contains(refMessage3));
        }
Beispiel #31
0
        /// <summary>
        /// Analyze replay locally before uploading
        /// </summary>
        /// <param name="file">Replay file</param>
        public bool Analyze(ReplayFile file)
        {
            try
            {
                if (!string.IsNullOrEmpty(file.Fingerprint))
                {
                    return(true);
                }

                var result      = DataParser.ParseReplay(file.Filename, false, false, false);
                var replay      = result.Item2;
                var parseResult = result.Item1;
                var status      = GetPreStatus(file, replay, parseResult);

                if (status != null)
                {
                    file.HotsweekUploadStatus = file.HotsApiUploadStatus = status.Value;
                }
                else if (parseResult != DataParser.ReplayParseResult.Success)
                {
                    file.HotsweekUploadStatus = file.HotsApiUploadStatus = UploadStatus.Incomplete;
                }

                if (parseResult != DataParser.ReplayParseResult.Success)
                {
                    return(false);
                }

                file.Fingerprint = GetFingerprint(replay);
                file.GameMode    = replay.GameMode;

                return(true);
            }
            catch (Exception e) {
                _log.Warn(e, $"Error analyzing file {file}");
                return(false);
            }
        }
Beispiel #32
0
    private void Update()
    {
        if (Client.client == null)
        {
            return;
        }
        if (!Client.client.Connected)
        {
            return;
        }
        if (!receiveMessage)
        {
            return;
        }

        Telepathy.Message msg;
        while (receiveMessage && Client.client.GetNextMessage(out msg))
        {
            switch (msg.eventType)
            {
            case Telepathy.EventType.Connected:
                break;

            case Telepathy.EventType.Data:
                FileObject file = DataParser.DeserializeObject <FileObject>(msg.data);
                if (file != null)
                {
                    receiveMessage = false;
                    StartCoroutine(Load(file));
                }
                break;

            case Telepathy.EventType.Disconnected:
                Error.ShowError(startScene, "Server Disconnected");
                break;
            }
        }
    }
        public LiveTestForm()
        {
            this.penDrawingBuffer = new FixedSizedQueue <PointFrame>(200);
            InitializeComponent();

            // Initialize Camera
            _camera = new AForgeCamera();
            //_camera = new FilesystemCamera(new DirectoryInfo(@"C:\temp\aforge\inph"));
            _camera.FrameReady += _camera_FrameReady;

            /*
             * _camera.FrameReady += delegate(object o, FrameReadyEventArgs e) {
             *  String path = @"C:\temp\live\cap-" + DateTime.Now.DayOfYear;
             *  if (!Directory.Exists(path))
             *  {
             *      Directory.CreateDirectory(path);
             *  }
             *  e.Frame.Bitmap.Save(Path.Combine(path, "cap-" + CurrentMillis.Millis + ".png"));
             * };
             */

            // Initialize Calibration and Pen Parsing Mechanism
            //_parser = new DataParser(
            //    new SimpleAForgeCalibrator(_camera, VisualizerControl.GetVisualizer()),
            //    new AForgePenTracker(new RedLaserStrategy(), _camera));
            _parser = new DataParser(_camera, VisualizerControl.GetVisualizer());
            //_parser = new QuadrilateralDataParser(_camera, VisualizerControl.GetVisualizer());
            _parser.PenPositionChanged += parser_PenPositionChanged;

            // Form for visual feedback of tracking process
            //screenForm = new ScreenForm();
            _inputEmulator = new AdvancedInputEmulator(VisualizerControl.GetVisualizer().Width, VisualizerControl.GetVisualizer().Height);

            if (!File.Exists(@"C:\temp\foundpoints.csv"))
            {
                File.Create(@"C:\temp\foundpoints.csv");
            }
        }
Beispiel #34
0
        public async Task ParseEntity()
        {
            var request = new Request("https://list.jd.com/list.html?cat=9987,653,655",
                                      new Dictionary <string, string> {
                { "cat", "手机" }, { "cat3", "110" }
            });
            var dataContext = new DataContext(null, new SpiderOptions(), request,
                                              new Response {
                Content = new ResponseContent {
                    Data = File.ReadAllBytes("Jd.html")
                }
            });

            var parser = new DataParser <Product>();

            parser.SetHtmlSelectableBuilder();
            await parser.HandleAsync(dataContext);

            var results = (List <Product>)dataContext.GetData(typeof(Product));

            Assert.Equal(60, results.Count);
            Assert.Contains("手机商品筛选", results[0].Title);
            Assert.Contains("手机商品筛选", results[1].Title);
            Assert.Contains("手机商品筛选", results[2].Title);
            Assert.Equal("手机", results[0].CategoryName);
            Assert.Equal(110, results[0].CategoryId);
            Assert.Equal("https://item.jd.com/3031737.html", results[0].Url);
            Assert.Equal("3031737", results[0].Sku);
            Assert.Equal("荣耀官方旗舰店", results[0].ShopName);
            Assert.Equal("荣耀 NOTE 8 4GB+32GB 全网通版 冰河银", results[0].Name);
            Assert.Equal("1000000904", results[0].VenderId);
            Assert.Equal("1000000904", results[0].JdzyShopId);
            Assert.Equal(DateTimeOffset.Now.ToString("yyyy-MM-dd"), results[0].RunId.ToString("yyyy-MM-dd"));

            var requests = dataContext.FollowRequests;

            Assert.Equal(7, requests.Count);
        }
Beispiel #35
0
        /// <summary>
        ///     Gets the weather data.
        /// </summary>
        private static void GetWeatherData()
        {
            Debug.Assert(Sources != null && Sources.Any(), "Weather data sources cannot be null or empty.");

            foreach (WeatherDataSources source in Sources)
            {
                try
                {
                    // Validate the format of the URL
                    Uri sourceUri;
                    if (Uri.TryCreate(source.Url, UriKind.Absolute, out sourceUri) && sourceUri.Scheme == Uri.UriSchemeHttp)
                    {
                        using (System.Net.WebClient client = new System.Net.WebClient())
                        {
                            string html = client.DownloadString(sourceUri);

                            if (!string.IsNullOrWhiteSpace(html))
                            {
                                // Get the first line of HTML
                                HtmlDocument = new HtmlAgilityPack.HtmlDocument();
                                HtmlDocument.LoadHtml(html);

                                DataParser parser = new DataParser();

                                // TODO: Evaluate whether to use an enumerator here instead of strings
                                switch (source.Airport.ToLowerInvariant())
                                {
                                    case "cynr":
                                        parser.SetParseStrategy(new CynrParse());
                                        break;
                                    case "cet2":
                                        parser.SetParseStrategy(new Cet2Parse());
                                        break;
                                    case "cfg6":
                                        parser.SetParseStrategy(new Cfg6Parse());
                                        break;
                                    case "crl4":
                                        parser.SetParseStrategy(new Crl4Parse());
                                        break;
                                    default:
                                        throw new InvalidOperationException("Invalid airport code specified in the configuration file.");
                                }

                                string data = parser.Parse();

                                // Parse and store the data
                                if (!string.IsNullOrWhiteSpace(data))
                                {
                                    // Does the string look as we expect?
                                    const string pattern = @"^(METAR|SPECI)\s\w{4}\s\d{6}Z(.*)$";

                                    System.Text.RegularExpressions.Regex expression = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Compiled);
                                    bool isValidData = expression.IsMatch(data);

                                    if (!isValidData)
                                    {
                                        throw new Exception(string.Format("Parsed data returned by {0} is an invalid data format: {1}", sourceUri, data));
                                    }

                                    ParseWeatherData(data);
                                }
                            }
                            else
                            {
                                // The HTML was blank, so there's nothing else we can do
                                throw new Exception(string.Format("The HTML document returned by a configured URL ({0}) is empty.", sourceUri));
                            }
                        }
                    }
                    else
                    {
                        // We had trouble creating the URL using configuration file entries
                        throw new UriFormatException(string.Format("The system was unable to parse a URL ({0}) in the configuration file.", sourceUri));
                    }
                }
                catch (Exception x)
                {
                    WriteToEventApplicationLog(x);
                    SendMail(x.Message);
                }
            }
        }
Beispiel #36
0
        private void button2_Click(object sender, EventArgs e)
        {
            //Read Button
            byte[] data = new byte[19];
            SyncStatus syncStatus;
            int packetCount = 0, maxPacket = 0, noofattmpt = 300, i; //, z;

            _dataParser = new DataParser();
            _dataParser.resetDataParser();

            //chronosGetId();
            //_chronos.GetID(out _chronosId);//from getID
            _chronos.ReadSyncBuffer(out data);//from getID
            chronosGetStatus();

            maxPacket = (_dataParser.bytesReady / 16 + 1);

            status.Clear();
            //status.AppendText("size: " + string.Format("{0:X2} ", _dataParser.bytesReady) + "bytes");
            status.AppendText("size: " + _dataParser.bytesReady + " bytes");
            if (_dataParser.bytesReady >= 1)
            {
                for (packetCount = 0; packetCount < maxPacket; packetCount++)
                {
                    data[0] = Constants.SYNC_AP_CMD_GET_MEMORY_BLOCKS_MODE_1;
                    for (i = 1; i <= 18; i++)
                        data[i] = 0;
                    data[1] = (byte)(packetCount >> 8);
                    data[2] = (byte)(packetCount & 0xFF);
                    data[3] = (byte)(packetCount >> 8);
                    data[4] = (byte)(packetCount & 0xFF);

                    _chronos.SendSyncCommand(data);

                    for (i = 1; i < noofattmpt; i++)
                    {
                        _chronos.GetSyncBufferStatus(out syncStatus);
                        if (syncStatus == SyncStatus.SYNC_USB_DATA_READY)
                        {
                            _chronos.ReadSyncBuffer(out data);
                            _dataParser.ParseData(data);
                            break;
                        }
                    }
                    if (i == noofattmpt) packetCount--; //try again  (more robust but might become infinite loop here)

                }
                status.Clear();
                status.AppendText("Ready for download.");
            }
            else
            {
                this.sync.Enabled = true;
                this.read.Enabled = false;
                this.erase.Enabled = false;
                this.download.Enabled = false;
                status.Clear();
                status.AppendText("No data ready for download. RF Access Point closed.");
                _chronos.StopSimpiliTI();

            }

            //Read button notes: Data parsing is used for temporary computer storage of gathered data.
            //Given that data were erased from the watch, data are available for download after READ and before EXIT.
        }
 private void btn_singleLineInput_Click(object sender, EventArgs e)
 {
     DataParser DP = new DataParser();
     String input = editBox_sinleInput.Text.ToString();
     String cleanString = DP.getCleanString(input);
 }
        private void btn_probabilityNgramfromFile_Click(object sender, EventArgs e)
        {
            FileWriter FW = new FileWriter();
            for (int i = 0; i < Languages.Length; i++)
            {

                gramDictionary.Add(Languages[i], new LanguageObject());
                FetchFromFolderFiles fetchFromFolder = new FetchFromFolderFiles("Trainingnlp");
                DataTable dataTable = fetchFromFolder.getTrainingDataFor(Languages[i]);

                DataParser DP = new DataParser();
                DataTable cleanTable = new DataTable();
                cleanTable = DP.getCleanTable(dataTable);

                NgramBuilder NB = new NgramBuilder();

                DataTable uniGram = new DataTable();
                uniGram = NB.GetGram(cleanTable, 1);
                double uniGramN = NB.getTotalFrequency();

                DataTable unSmoothedProbabilityUnigramDataTable = new DataTable();
                unSmoothedProbabilityUnigramDataTable = NB.ConvertTableToProbabilityTable(uniGram, uniGramN);
                Hashtable unSmoothedProbabilityUnigram = NB.ConvertProbTabletoHashTable(unSmoothedProbabilityUnigramDataTable);
                gramDictionary[Languages[i]].setProbabilityUnigram(unSmoothedProbabilityUnigram,uniGramN);

                DataTable smoothedUniGram = new DataTable();
                smoothedUniGram = NB.applySmoothing(uniGram, 0.1);
                double uniGramSmoothedN = NB.getTotalFrequency();

                DataTable SmoothedProbabilityUnigramDataTable = new DataTable();
                SmoothedProbabilityUnigramDataTable = NB.ConvertTableToProbabilityTable(smoothedUniGram, uniGramSmoothedN);
                Hashtable SmoothedProbabilityUnigram = NB.ConvertProbTabletoHashTable(SmoothedProbabilityUnigramDataTable);
                gramDictionary[Languages[i]].setSmoothedProbabilityUnigram(SmoothedProbabilityUnigram, uniGramSmoothedN);

                DataTable biGram = new DataTable();
                biGram = NB.GetGram(cleanTable, 2);
                double biGramN = NB.getTotalFrequency();

                DataTable UnSmoothedProbabilityBigramDataTable = new DataTable();
                UnSmoothedProbabilityBigramDataTable = NB.ConvertTableToProbabilityTable(biGram, biGramN);

                Hashtable UnSmoothedProbabilityBigram = NB.ConvertProbTabletoHashTable(UnSmoothedProbabilityBigramDataTable);
                gramDictionary[Languages[i]].setProbabilityBigram(UnSmoothedProbabilityBigram, biGramN);

                DataTable smoothedBiGram = new DataTable();
                smoothedBiGram = NB.applySmoothing(biGram, 0.1);
                double BiGramSmoothedN = NB.getTotalFrequency();

                DataTable SmoothedProbabilityBigramDataTable = new DataTable();
                SmoothedProbabilityBigramDataTable = NB.ConvertTableToProbabilityTable(smoothedBiGram, BiGramSmoothedN);

                Hashtable SmoothedProbabilityBigram = NB.ConvertProbTabletoHashTable(SmoothedProbabilityBigramDataTable);
                gramDictionary[Languages[i]].setSmoothedProbabilityBigram(SmoothedProbabilityBigram, BiGramSmoothedN);

                FW.writeUniGram(unSmoothedProbabilityUnigramDataTable, Languages[i], "False", uniGramN);
                FW.writeUniGram(SmoothedProbabilityUnigramDataTable, Languages[i], "True", uniGramSmoothedN);

                FW.writeNGram(UnSmoothedProbabilityBigram,Languages[i],"False",biGramN,"BiGram");
                FW.writeNGram(SmoothedProbabilityBigram, Languages[i], "True", BiGramSmoothedN, "BiGram");
               // If you want matrix representation include this and remove the upper 2 lines
               // FW.writeBiGram(UnSmoothedProbabilityBigramDataTable, Languages[i], "False", biGramN);
               // FW.writeBiGram(SmoothedProbabilityBigramDataTable, Languages[i], "True", BiGramSmoothedN);

            }
            FW.closeWriter();

            MessageBox.Show("Done ");
        }