// TODO comment this static string GetSignatures(string json) { dynamic inputJson = JsonConvert.DeserializeObject(json); string document = inputJson.textDocument; int line = inputJson.caret.line; int character = inputJson.caret.character; Pos caret = new Pos(line, character); var parser = ParserData.GetParser(document, new Parse.Pos(caret.line, caret.character)); int methodIndex = 0; int parameterIndex = 0; MethodNode methodNode = null; SignatureHelp signatures = null; if (parser.Success) { if (parser.Bav.SelectedNode.ElementAtOrDefault(0) is MethodNode) { methodNode = (MethodNode)parser.Bav.SelectedNode[0]; parameterIndex = methodNode.Parameters.Length; } else if (parser.Bav.SelectedNode.ElementAtOrDefault(0) is IExpressionNode && parser.Bav.SelectedNode.ElementAtOrDefault(1) is MethodNode) { methodNode = (MethodNode)parser.Bav.SelectedNode[1]; parameterIndex = Array.IndexOf(methodNode.Parameters, parser.Bav.SelectedNode[0]); } SignatureInformation information = null; if (methodNode != null) { Type methodType = Element.GetMethod(methodNode.Name); if (methodType != null) { Element element = (Element)Activator.CreateInstance(methodType); information = new SignatureInformation( element.ToString(), "", element.ParameterData.Select(p => new ParameterInformation(p.Name, "") ).ToArray()); } } signatures = new SignatureHelp ( new SignatureInformation[] { information }, methodIndex, parameterIndex ); } return(JsonConvert.SerializeObject(signatures)); }
public LanguageData(Grammar grammar) { Grammar = grammar; GrammarData = new GrammarData(this); ParserData = new ParserData(this); ScannerData = new ScannerData(this); }
//retrieves a single, unique prescription using the prescription ID public Prescription GetPrescription(int pID) { //get filepath of prescription file located in internal storage string internalStoragePath = Application.Context.FilesDir.Path; string prescriptionPath = Path.Combine(internalStoragePath, prescriptionFileName); //return null if file doesn't exist if (!DoesPrescriptionExist(pID)) { return(null); } string[] prescriptionData = File.ReadAllLines(prescriptionPath); foreach (string prescriptionLine in prescriptionData) { //if prescription ID matches pID, return the data of the current prescription if (GetRXIDFromPrescriptionData(prescriptionLine) == pID) { ParserData newParserData = new ParserData(prescriptionLine); return(newParserData.CreatePrescription()); } } //if no matches found, return null return(null); }
public string ParseJson(string data) { try { string errorList = ""; string res; var result = JsonConvert.DeserializeObject <List <ChemistryInfo> >(data); int i = 1; foreach (var item in result) { res = new ParserData().SaveItem(item); if (res == "FAIL") { return("ERROR"); } if (res != "") { //if (res.ToUpper().Trim() == "HEATNOEXISTS") //{ // errorList += "Record No." + i.ToString() + ":" + res + "; "; //} errorList += "Record No." + i.ToString() + ":" + res + "; "; i++; } } return(errorList); } catch (Exception ex) { return("ERROR"); } }
public void Build() { _stateHash.Clear(); Stopwatch sw = new Stopwatch(); sw.Start(); var i1 = sw.ElapsedMilliseconds; Data = _language.ParserData; CheckPrecedenceSettings(_language.GrammarData, Data.ParseMethod); var i2 = sw.ElapsedMilliseconds; var i3 = sw.ElapsedMilliseconds; CreateLalrParserStates(); var i4 = sw.ElapsedMilliseconds; //TODO: move all the following to a single method //ComputeTransitionIncludesAndItemLookbacks(); //5 ms var i5 = sw.ElapsedMilliseconds; PropagateTransitionsIncludes(0); //220 ms var i6 = sw.ElapsedMilliseconds; //ComputeTransitionsSources(0); var i7 = sw.ElapsedMilliseconds; ComputeLookaheads(); var i8 = sw.ElapsedMilliseconds; var i9 = sw.ElapsedMilliseconds; ComputeAndResolveConflicts(); var i10 = sw.ElapsedMilliseconds; var i11 = sw.ElapsedMilliseconds; var i12 = sw.ElapsedMilliseconds; if (Data.ParseMethod == ParseMethod.Nlalr) { SwitchConflictingStatesToNonCanonicalLookaheads(); } var i13 = sw.ElapsedMilliseconds; ReportAndSetDefaultActionsForConflicts(); CreateReduceActions(); ComputeStateExpectedLists(); }
public string ParseJson(string data, char status) { try { string errorList = ""; ResultViewModel res; var result = JsonConvert.DeserializeObject <List <ChemistryInfo> >(data); foreach (var item in result) { res = new ParserData().SaveItem(item, status); if (res.Message == "FAIL") { return("ERROR"); } if (res.Message != "") { errorList += "<br />" + "Heat No." + res.HeatNo + ":" + res.Message + "; "; } } return(errorList); } catch (Exception ex) { return("ERROR"); } }
/// <summary> /// Initializes the specified grammar. /// </summary> /// <param name="grammar">The grammar.</param> public LanguageData(Grammar grammar) { Grammar = grammar; GrammarData = new GrammarData(this); ParserData = new ParserData(this); ConstructAll(); }
public static async Task <ParserData> ListDocumentParsers(string apiKey) { var parserData = new ParserData(); var url = string.Format("/parsers?api_key={0}", apiKey); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri("https://api.docparser.com/v1"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { HttpResponseMessage Response = await client.GetAsync(url); var result = await Response.Content.ReadAsStringAsync(); if (result.Length > 0) { JsonConvert.PopulateObject(result, parserData); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } return(parserData); }
public void ParseSection2() { // Start and End for tag HtmlSectionTemplate template = new HtmlSectionTemplate(); template.Tags = "T"; template.Template = "<table><tr><td>Title:<#TITLE>(</td><td><#START></td><td><#DESCRIPTION></td><Z(><td><#GENRE></td></Z)?></tr></table>"; HtmlSectionParser elements = new HtmlSectionParser(template); ParserData data = new ParserData(); IParserData idata = (IParserData)data; string source = "<table><tr><td>Test</td><td>123</td><td>blah blah</td></tr></table>"; elements.ParseSection(source, ref idata); Assert.IsTrue(data.GetElement("#TITLE") == "Test"); Assert.IsTrue(data.GetElement("#START") == "123"); Assert.IsTrue(data.GetElement("#DESCRIPTION") == "blah blah"); data = new ParserData(); idata = (IParserData)data; source = "<table><tr><td>Title:Test(1:2)</td><td>123</td><td>blah blah</td></tr></table>"; elements.ParseSection(source, ref idata); Assert.IsTrue(data.GetElement("#TITLE") == "Test"); Assert.IsTrue(data.GetElement("#START") == "123"); Assert.IsTrue(data.GetElement("#DESCRIPTION") == "blah blah"); }
public LanguageData(Grammar grammar) { Grammar = grammar; GrammarData = new GrammarData(this); ParserData = new ParserData(this); ScannerData = new ScannerData(this); ConstructAll(); }
/// <summary> /// Create a DTO of all needed e-mail default data. /// </summary> /// <returns>a dictionary of the following keys (grammar, actionTable, gotoTable, messageStyle, signatureStyle)</returns> public static ParserData GetParserData() { ParserData data = new ParserData(); data.MessageStyle = GetMessageStyle(); data.SignatureStyle = GetSignatureStyle(); return(data); }
public void Build() { _stateHash.Clear(); Data = _language.ParserData; CreateParserStates(); ComputeTransitions(); ComputeLookaheads(); ComputeAndResolveConflicts(); CreateRemainingReduceActions(); ComputeStatesExpectedTerminals(); }//method
public override bool CanParse(object data) { if (!base.CanParse(data)) { return(false); } Regex regEx = new Regex(ParserData.ToString()); return(regEx.IsMatch(data.ToString())); }
public void Build() { _stateHash.Clear(); Data = _language.ParserData; CreateParserStates(); ComputeTransitions(); ComputeLookaheads(); ComputeAndResolveConflicts(); CreateRemainingReduceActions(); ComputeStatesExpectedTerminals(); }//method
//returns a list of all the user's prescriptions public List <Prescription> GetAllPrescriptions() { List <Prescription> prescriptionList = new List <Prescription>(); foreach (string p in GetAllPrescriptionData()) { ParserData parse = new ParserData(p); prescriptionList.Add(parse.CreatePrescription()); } return(prescriptionList); }
public bool IsThereAvailableDoses(ParserData parse) { //get today's taken dosages List <TakenDosage> doses = GetTodaysDosesForPrescription(parse.prescriptionID); if (doses == null || (doses != null && doses.Count < parse.frequencyQty)) { return(true); } return(false); }
public void Build() { _stateHash.Clear(); Data = _language.ParserData; CreateParserStates(); var itemsNeedLookaheads = GetReduceItemsInInadequateState(); ComputeTransitions(itemsNeedLookaheads); ComputeLookaheads(itemsNeedLookaheads); ComputeAndResolveConflicts(); CreateRemainingReduceActions(); ComputeStatesExpectedTerminals(); }
public CelestialBody BuildCelestialBody(ParserData parserData) { switch (parserData.Type.ToLower()) { case "planet": return(BuildPlanet(parserData)); case "asteroid": return(BuildAstroid(parserData)); default: return(new Astroid()); } }
protected override ParsedData Parse(ParserData parserData) { string devEUI = parserData.GetDevEUI(); DateTime dateTime = parserData.GetTime(); decimal batV = parserData.GetPayloadValue("BatV").AsDecimal(); var keyValues = new List <ParsedData.KeyValue>() { new ParsedData.KeyValue("BatV", batV), new ParsedData.KeyValue("BatPrc", (batV - 3.40m) / 0.60m * 100), new ParsedData.KeyValue("RSSI", parserData.GetRSSI()), }; return(new ParsedData(devEUI, dateTime, keyValues)); }
static string ParseDocument(string document, int clientPort) { var data = ParserData.GetParser(document, null); if (data.Rules != null && data.Diagnostics.Count == 0) { string final = Program.RuleArrayToWorkshop(data.Rules, data.VarCollection); using (var wc = new WebClient()) { wc.UploadString($"http://localhost:{clientPort}/", final); } } return(JsonConvert.SerializeObject(data.Diagnostics.ToArray())); }
public IEnumerable <ParserError> Parse([FromBody] ParserData data) { var parser = new GameDefinitionParser(); var builder = new GameDefinitionBuilder(); var errors = parser.Parse(builder, data.Text); if (errors.Count == 0) { var definition = builder.Build(); // TODO: use definition somehow } return(errors); }
public Parser(LanguageData language, NonTerminal root) { Language = language; Data = Language.ParserData; _grammar = Language.Grammar; Context = new ParsingContext(this); Scanner = new Scanner(this); Root = root; if(Root == null) { Root = Language.Grammar.Root; InitialState = Language.ParserData.InitialState; } else { if(Root != Language.Grammar.Root && !Language.Grammar.SnippetRoots.Contains(Root)) throw new Exception(string.Format(Resources.ErrRootNotRegistered, root.Name)); InitialState = Language.ParserData.InitialStates[Root]; } }
private Astroid BuildAstroid(ParserData parserData) { Astroid returningAstroid = new Astroid() { Neighbours = new List <string>(), Radius = parserData.Radius, Colour = parserData.Colour, X = parserData.X, Y = parserData.Y, VX = parserData.VX, VY = parserData.VY, collision = returnCollisionComponent(parserData.OnCollision) }; return(returningAstroid); }
public void Build() { _stateHash.Clear(); _data = _language.ParserData; CreateParserStates(); var itemsNeedLookaheads = GetReduceItemsInInadequateState(); ComputeTransitions(itemsNeedLookaheads); ComputeLookaheads(itemsNeedLookaheads); ComputeStatesExpectedTerminals(); ComputeConflicts(); ApplyHints(); HandleUnresolvedConflicts(); CreateRemainingReduceActions(); //Create error action - if it is not created yet by some hint or custom code if (_data.ErrorAction == null) _data.ErrorAction = new ErrorRecoveryParserAction(); }//method
private Planet BuildPlanet(ParserData parserData) { Planet returningPlanet = new Planet() { Name = parserData.Name, Radius = parserData.Radius, Colour = parserData.Colour, X = parserData.X, Y = parserData.Y, VX = parserData.VX, VY = parserData.VY, Neighbours = parserData.Neighbours, collision = returnCollisionComponent(parserData.OnCollision) }; return(returningPlanet); }
/// <summary> /// builds a node out of parserData /// </summary> /// <param name="data">the data</param> /// <returns>this, so you can easily chain commands</returns> public NodeBuilder BuildNode(ParserData data) { _currentNode = data.Type switch { "AND" => new AndNode(data.Id), "OR" => new OrNode(data.Id), "INPUT_HIGH" => new InputNode(data.Id, true), "INPUT_LOW" => new InputNode(data.Id, false), "PROBE" => new OutputNode(data.Id), "NOT" => new NotNode(data.Id), "NAND" => BuildNAND(data.Id), "NOR" => BuildNOR(data.Id), "XNOR" => BuildXNOR(data.Id), _ => throw new NotImplementedException() }; return(this); }
/// <summary> /// Преобразование кода MSQL в SQL. /// </summary> /// <param name="MSQL"></param> /// <returns>Код SQL</returns> public static string Parse(string MSQL) { //Инициализация парсера if (!ParserData.IsInitial) { string sql = ParserData.GetSQLInitial(); var DS = new System.Data.DataSet(); string ErrorText; const bool ErrorShow = true; if (!sys.SelectDS(DirectionQuery.Remote, sql, out DS, out ErrorText, ErrorShow)) { return(""); } ParserData.ParserInitialFromDS(DS); } var parser = new Parser(); return(parser.Parse(MSQL, "Sys")); }
public void Build(ParseMethod method) { _stateHash.Clear(); Stopwatch sw = new Stopwatch(); sw.Start(); var i1 = sw.ElapsedMilliseconds; Data = _language.ParserData = new ParserData(_language.Grammar, method); CheckPrecedenceSettings(_language.GrammarData, method); var i2 = sw.ElapsedMilliseconds; var i3 = sw.ElapsedMilliseconds; CreateLalrParserStates(); var i4 = sw.ElapsedMilliseconds; //TODO: move all the following to a single method //ComputeTransitionIncludesAndItemLookbacks(); //5 ms var i5 = sw.ElapsedMilliseconds; PropagateTransitionsIncludes(0); //220 ms var i6 = sw.ElapsedMilliseconds; //ComputeTransitionsSources(0); var i7 = sw.ElapsedMilliseconds; ComputeLookaheads(); var i8 = sw.ElapsedMilliseconds; var i9 = sw.ElapsedMilliseconds; ComputeAndResolveConflicts(); var i10 = sw.ElapsedMilliseconds; var i11 = sw.ElapsedMilliseconds; var i12 = sw.ElapsedMilliseconds; if (Data.ParseMethod == ParseMethod.Nlalr) { SwitchConflictingStatesToNonCanonicalLookaheads(); } var i13 = sw.ElapsedMilliseconds; ReportAndSetDefaultActionsForRemainingConflicts(); CreateReduceActions(); ComputeStateExpectedLists(); }//method
protected override ParsedData Parse(ParserData parserData) { string devEUI = parserData.GetDevEUI(); DateTime dateTime = parserData.GetTime(); var keyValues = new List <ParsedData.KeyValue>() { new ParsedData.KeyValue("BatV", parserData.GetPayloadValue("BatV").AsDecimal()), new ParsedData.KeyValue("Air.Temperature", parserData.GetPayloadValue("TempC_SHT").AsDecimal()), new ParsedData.KeyValue("Air.Humidity", parserData.GetPayloadValue("Hum_SHT").AsDecimal()), new ParsedData.KeyValue("RSSI", parserData.GetRSSI()), }; if (parserData.TryGetPayloadValue("TempC_DS", out ParserValue parserValue) && !parserValue.IsNull()) { keyValues.Add(new ParsedData.KeyValue("Soil.Temperature", parserValue.AsDecimal())); } return(new ParsedData(devEUI, dateTime, keyValues)); }
public void Build() { _stateHash.Clear(); _data = _language.ParserData; CreateParserStates(); var itemsNeedLookaheads = GetReduceItemsInInadequateState(); ComputeTransitions(itemsNeedLookaheads); ComputeLookaheads(itemsNeedLookaheads); ComputeStatesExpectedTerminals(); ComputeConflicts(); ApplyHints(); HandleUnresolvedConflicts(); CreateRemainingReduceActions(); //Create error action - if it is not created yet by some hint or custom code if (_data.ErrorAction == null) { _data.ErrorAction = new ErrorRecoveryParserAction(); } }//method
public void ParseSection3() { // Multiple tags HtmlSectionTemplate template = new HtmlSectionTemplate(); template.Tags = "T"; template.Template = "<table><tr><td><#TITLE>-<#SUBTITLE></td><td><#START></td><td><#DESCRIPTION></td><Z(><td><#GENRE></td></Z)?></tr></table>"; HtmlSectionParser elements = new HtmlSectionParser(template); ParserData data = new ParserData(); IParserData idata = (IParserData)data; string source = "<table><tr><td>Test-Sub</td><td>123</td><td>blah blah</td></tr></table>"; elements.ParseSection(source, ref idata); Assert.IsTrue(data.GetElement("#TITLE") == "Test"); Assert.IsTrue(data.GetElement("#SUBTITLE") == "Sub"); Assert.IsTrue(data.GetElement("#START") == "123"); Assert.IsTrue(data.GetElement("#DESCRIPTION") == "blah blah"); }
//onCreate for our new view protected override void OnCreate(Bundle savedInstanceState) { //just opens up the window for adding prescription base.OnCreate(savedInstanceState); //grabs the text field for testing //get the intent of the chip, or no intent if it didnt work var intentType = Intent.Type ?? String.Empty; if (MainActivity.ViewPrescMimeType.Equals(intentType)) { // Get the string that was written to the NFC tag, and display it. var rawMessages = Intent.GetParcelableArrayExtra(NfcAdapter.ExtraNdefMessages); var msg = (NdefMessage)rawMessages[0]; var prescRecord = msg.GetRecords()[0]; var prescData = Encoding.ASCII.GetString(prescRecord.GetPayload()); rawPrescriptionData = prescData; parse = new ParserData(prescData); /* * TODO: CHECK IF PATIENT NAME IN NFC DATA MATCHES THE USERNAME (WE SHOULD PROBS ALSO SPLIT THIS INTO FIRST NAME, LAST NAME) * -IF NAME MATCHES * -IF PRESCRIPTION DOESN'T EXIST IN APP * -PROMPT USER IF THEY'D LIKE TO ADD PRESCRIPTION * -ELSE IF PRESCRIPTION DOES EXIST IN APP * -ADD DOSAGE * -ELSE IF NAME DOESN'T MATCH * -NOTIFY USER THIS IS NOT THEIR PRESCRIPTION * */ string greetingText = ""; if (parse.patientName.Equals(LocalDataManager.Instance.GetUsername())) { if (LocalDataManager.Instance.DoesPrescriptionExist(parse.prescriptionID)) { //check if dosage is available for today, if yes, show accept screen if (LocalDataManager.Instance.IsThereAvailableDoses(parse)) { SetTapView(); //prompt user if they are taking a dose now greetingText = "Hello " + LocalDataManager.Instance.GetUsername() + ", you're able to take a dose. Are you taking it now?"; } else { SetTapViewBad(); //If there are no more available doses for today greetingText = "You should not take any more doses today."; } //decrement dosage counter //create a TakenDosage //if not TextView textGreeting; TextView textDose; textGreeting = FindViewById <TextView>(Resource.Id.textView1); textDose = FindViewById <TextView>(Resource.Id.textView2); textGreeting.Text = greetingText; textDose.Text = parse.strengthQty + parse.strengthUnit + " " + parse.brandName + " (" + parse.genericName + ")"; } else { DisplayNewPrescription(); /* * //If patient name in chip data doesn't match user's name * greetingText = "This is not your prescription."; * img.SetImageResource(Resource.Drawable.imgReject); * layout.SetBackgroundResource(Resource.Color.clrRejectedRed); */ } } else { SetTapViewBad(); //If there are no more available doses for today greetingText = "This is not your prescription."; //if not TextView textGreeting; TextView textDose; textGreeting = FindViewById <TextView>(Resource.Id.textView1); textDose = FindViewById <TextView>(Resource.Id.textView2); textGreeting.Text = greetingText; textDose.Text = parse.strengthQty + parse.strengthUnit + " " + parse.brandName + " (" + parse.genericName + ")"; } } }
/// <summary> /// Registers a new user, using the properties of this class. /// </summary> /// <param name="nickName">Name of the nick.</param> /// <param name="dateOfBirth">The date of birth.</param> /// <param name="emailAddress">The email address.</param> /// <param name="emailAddressIsPublic">flag to signal if the emailaddress is visible for everyone or not</param> /// <param name="iconURL">The icon URL.</param> /// <param name="ipNumber">The ip number.</param> /// <param name="location">The location.</param> /// <param name="occupation">The occupation.</param> /// <param name="signature">The signature.</param> /// <param name="website">The website.</param> /// <param name="emailTemplatePath">The email template path.</param> /// <param name="emailData">The email data.</param> /// <param name="autoSubscribeThreads">Default value when user creates new threads.</param> /// <param name="defaultMessagesPerPage">Messages per page to display</param> /// <returns> /// UserID of new user or 0 if registration failed. /// </returns> public static int RegisterNewUser(string nickName, DateTime?dateOfBirth, string emailAddress, bool emailAddressIsPublic, string iconURL, string ipNumber, string location, string occupation, string signature, string website, string emailTemplatePath, Dictionary <string, string> emailData, ParserData parserData, bool autoSubscribeThreads, short defaultMessagesPerPage) { UserEntity newUser = new UserEntity(); // initialize objects newUser.AmountOfPostings = 0; newUser.DateOfBirth = dateOfBirth; newUser.EmailAddress = emailAddress; newUser.EmailAddressIsPublic = emailAddressIsPublic; newUser.IPNumber = ipNumber; newUser.IconURL = iconURL; newUser.IsBanned = false; newUser.JoinDate = DateTime.Now; newUser.Location = location; newUser.NickName = nickName; newUser.Occupation = occupation; newUser.Signature = signature; newUser.Website = website; string password = HnDGeneralUtils.GenerateRandomPassword(); newUser.Password = HnDGeneralUtils.CreateMD5HashedBase64String(password); //Preferences newUser.AutoSubscribeToThread = autoSubscribeThreads; newUser.DefaultNumberOfMessagesPerPage = defaultMessagesPerPage; if (!string.IsNullOrEmpty(signature)) { newUser.SignatureAsHTML = TextParser.TransformSignatureUBBStringToHTML(signature, parserData); } else { newUser.SignatureAsHTML = ""; } //Fetch the SystemDataEntity to use the "DefaultUserTitleNewUser" as the user title & the "DefaultRoleNewUser" // as the roleID of the newly created RoleUserEntity. SystemDataEntity systemData = SystemGuiHelper.GetSystemSettings(); newUser.UserTitleID = systemData.DefaultUserTitleNewUser; RoleUserEntity roleUser = new RoleUserEntity(); roleUser.RoleID = systemData.DefaultRoleNewUser; roleUser.User = newUser; // first encode fields which could lead to cross-site-scripting attacks EncodeUserTextFields(newUser); // now save the new user entity and the new RoleUser entity recursively in one go. This will create a transaction for us // under the hood so we don't have to do that ourselves. if (newUser.Save(true)) { // all ok, Email the password bool result = HnDGeneralUtils.EmailPassword(password, emailAddress, emailTemplatePath, emailData); } return(newUser.UserID); }
public CoreParser(Parser parser) { Parser = parser; Data = parser.Language.ParserData; _grammar = Data.Language.Grammar; }
///Парсинг запроса. private string Parse(string MSQL, bool Test) { string sql; if (!ParserData.IsInitial) { sql = ParserData.GetSQLInitial(); var DS = new System.Data.DataSet(); string ErrorText; const bool ErrorShow = true; if (!sys.SelectDS(DirectionQuery.Remote, sql, out DS, out ErrorText, ErrorShow)) { return(""); } ParserData.ParserInitialFromDS(DS); } //Для тестирования. Показываем исходные таблицы. if (!Test) { dgvEntity.DataSource = ParserData.DTArEntity; dgvAttrParent.DataSource = ParserData.DTArAttrParent; } parser = new Parser(); sql = parser.ParseTest(MSQL, cbPsevdominEntity.Text, "Sys"); //Результат SQL. if (!Test) { txTime.Text = parser.ParseTimeSQL.ToString(); //Для тестирования. Время выполнения процедур парсера. //Выходные данные. //Таблицы для парсинга, полученные при работе парсера. System.Data.DataTable DTMain; //Главная таблица, в которой весь запрос. System.Data.DataTable DTTable; //Список таблиц, которые используются в выходном запросе SQL. System.Data.DataTable DTEntity; //Список сущностей, которые используются в исходном запросе MSQL. System.Data.DataTable DTUserStr; //Список строк пользователя в исходном запросе MSQL. System.Data.DataTable DTAttrTable; System.Data.DataTable DTStateDate; parser.ReturnTestTable(out DTMain, out DTEntity, out DTTable, out DTUserStr, out DTAttrTable, out DTStateDate); //Выходные данные. dgvString.DataSource = DTMain; dgvListEntity.DataSource = DTEntity; dgvListTable.DataSource = DTTable; dgvUserString.DataSource = DTUserStr; dgvAttrTable.DataSource = DTAttrTable; dgvStateDate.DataSource = DTStateDate; dgvString.Columns[0].Width = 43; dgvString.Columns[1].Width = 111; dgvString.Columns[2].Width = 50; dgvString.Columns[3].Width = 55; dgvString.Columns[4].Width = 58; dgvString.Columns[5].Width = 50; dgvString.Columns[6].Width = 57; dgvString.Columns[7].Width = 101; dgvString.Columns[8].Width = 73; dgvString.Columns[9].Width = 100; dgvString.Columns[10].Width = 64; dgvString.Columns[11].Width = 50; dgvString.Columns[12].Width = 144; dgvString.Columns[13].Width = 118; dgvString.Columns[14].Width = 59; dgvString.Columns[15].Width = 52; dgvString.Columns[16].Width = 58; dgvString.Columns[17].Width = 57; dgvString.Columns[18].Width = 71; dgvString.Columns[19].Width = 72; dgvString.Columns[20].Width = 76; dgvString.Columns[21].Width = 65; } return(sql); }
public List <ParserData> Parse(string fileName, Stream file) { List <ParserData> parserData = new List <ParserData>(); using (TextFieldParser parser = new TextFieldParser(file)) { parser.TextFieldType = FieldType.Delimited; string[] commentTokens = new string[1]; commentTokens[0] = "#"; parser.CommentTokens = commentTokens; parser.SetDelimiters(";"); parser.SetDelimiters(":"); string[] curData = parser.ReadFields(); //get nodes while (!parser.EndOfData) { curData[0] = curData[0].Trim(';'); if (parserData.Exists(pd => pd.Id.Contains(curData[0]))) { break; } parserData.Add(new ParserData() { Id = curData[0], Type = curData[1].Trim(';'), Ouputs = new List <string>() }); curData = parser.ReadFields(); } bool lastLine = false; //get node connections while (!parser.EndOfData || lastLine) { var curParserData = parserData.Find(pd => pd.Id.Equals(curData[0])); curParserData.Ouputs.AddRange(curData.Skip(1).First().Split(',').ToList()); List <string> newInputs = new List <string>(); curParserData.Ouputs.ForEach(node => newInputs.Add(node.Trim(';'))); curParserData.Ouputs = newInputs; int index = parserData.FindIndex(pd => pd.Id.Equals(curParserData.Id)); parserData[index] = curParserData; curData = parser.ReadFields(); //parser ignores the last line unless we do this if (lastLine) { break; } if (parser.EndOfData) { lastLine = true; } } } ParserData header = new ParserData { HeaderData = Path.GetFileName(fileName) }; parserData.Insert(0, header); return(parserData); }
void OnEnable() { if (m_Parser == null) m_Parser = new ParserData(); }
/// <summary> /// Re-parses all messages from start date till now or when amountToIndex is reached. This routine will read messagetext for a message, /// parse it, and update the MessageTextAsXML field with the parse result. /// </summary> /// <param name="amountToParse">Amount to parse.</param> /// <param name="startDate">Start date.</param> /// <param name="reGenerateHTML">If true, the HTML is also re-generated and saved.</param> /// <returns>the amount of messages re-parsed</returns> public static int ReParseMessages(int amountToParse, DateTime startDate, bool reGenerateHTML, ParserData parserData) { // index is blocks of 100 messages. var qf = new QueryFactory(); var q = qf.Create() .Select(MessageFields.MessageID, MessageFields.MessageText) .Where(MessageFields.PostingDate >= new DateTime(startDate.Year, startDate.Month, startDate.Day, 0, 0, 0, 0)); if(amountToParse <= 0) { // If we don't have a specific amount of messages to parse, then parse all messages posted till Now. q.AndWhere(MessageFields.PostingDate <= DateTime.Now); } TypedListDAO dao = new TypedListDAO(); bool parsingFinished = false; int amountProcessed = 0; int pageSize = 100; int pageNo = 1; while(!parsingFinished) { q.Page(pageNo, pageSize); DataTable messagesToParse = dao.FetchAsDataTable(q); parsingFinished = (messagesToParse.Rows.Count <= 0); if(!parsingFinished) { foreach(DataRow row in messagesToParse.Rows) { MessageEntity directUpdater = new MessageEntity(); directUpdater.IsNew = false; string messageXML = string.Empty; string messageHTML = string.Empty; TextParser.ReParseMessage((string)row["MessageText"], reGenerateHTML, parserData, out messageXML, out messageHTML); // use the directupdater entity to create an update query without fetching the entity first. directUpdater.Fields[(int)MessageFieldIndex.MessageID].ForcedCurrentValueWrite((int)row["MessageID"]); directUpdater.MessageTextAsXml = messageXML; if(reGenerateHTML) { directUpdater.MessageTextAsHTML=messageHTML; } directUpdater.Fields.IsDirty=true; // no transactional update. directUpdater.Save(); } amountProcessed += messagesToParse.Rows.Count; pageNo++; if(amountToParse > 0) { parsingFinished = (amountToParse <= amountProcessed); } } } return amountProcessed; }
//retrieves the prescription ID given a string of raw prescription data (in CSV format) private int GetRXIDFromPrescriptionData(string prescriptionData) { ParserData newParserData = new ParserData(prescriptionData); return(newParserData.prescriptionID); }
public CoreParser(ParserData parserData, Scanner scanner) { Data = parserData; _grammar = parserData.Language.Grammar; _scanner = scanner; }