public void ShouldConvert() { var profile = parser.TryParse(@" a=1 a.b=1 a.b.c=2+${a.b.d}/7 a.b.d=3 x.y=2 "); profile.WasSuccessful.ShouldBeTrue(); profile.Expectations.ShouldBeEmpty(); var tree = builder.Build(profile.Value, new Dictionary <QualifiedName, Scheme.SubstituteType>()).ToList(); tree.Count.ShouldBe(3); tree[0].NameString.ShouldBe("a"); tree[1].NameString.ShouldBe("a"); tree[1].ShouldBeOfType <ProfileTreeNode>().Children.Count.ShouldBe(2); tree[2].NameString.ShouldBe("x"); tree[1].ShouldBeOfType <ProfileTreeNode>().Children[1] .ShouldBeOfType <ProfileTreeNode>().Children[0] .ShouldBeOfType <ProfileTreeLeaf>().Value .ShouldBe("2+3/7"); }
/// <summary> /// Get a <seealso cref="Tree"/>. /// If a tree for the given expression is present in the cache, it is /// taken from there; otherwise, the expression string is parsed and /// the resulting tree is added to the cache. </summary> /// <param name="expression"> expression string </param> /// <returns> expression tree </returns> public virtual Tree Get(string expression) { if (_cache == null) { return _builder.Build(expression); } Tree tree = _cache.Get(expression); if (tree == null) { _cache.Put(expression, tree = _builder.Build(expression)); } return tree; }
private static void BuildTree() { while (true) { ITreeBuilder tb = new TreeBuilder(); Console.Clear(); Console.WriteLine("Tree\nChoose the operation:\n 1. All site\n 2. Part of site(using url)\n 3. Cancel"); var key = Console.ReadLine(); switch (key) { case "1": Console.Clear(); Console.WriteLine(@"Choose the site:"); var sites = GetListOfSites(); int id; int.TryParse(Console.ReadLine(), out id); var res = (from x in sites where x.Id == id select x).FirstOrDefault(); if (res != null) { tb.Build(res); Console.Clear(); Console.WriteLine(@"Complete!"); Console.ReadKey(); } break; case "2": Console.Clear(); Console.WriteLine(@"Input starting Url"); var url = Console.ReadLine(); tb.Build(url); Console.Clear(); Console.WriteLine(@"Complete!"); Console.ReadKey(); break; case "3": Console.Clear(); return; } } }
public void CliParser_TooManyResults_ThrowsUnexpectedTokenException() { // Arrange var nodeFactory = new CliNodeFactory("CLI node family"); var input = this.GetType().Assembly.GetResourceText("cli-grammar.lisp", true); var tokens = _tinyLispLexer.Lexize(input); var reader = new TinyLispPseudoReader(); var list = reader.Read(tokens); ITreeBuilder builder = new TreeBuilder(); var root = builder.Build(nodeFactory, list); IParser parser = new Parser { WantsOnlyOneResult = true, Root = root, }; var singleCommand = "sd --connection \"Server=.;Database=econera.diet.tracking;Trusted_Connection=True;\" --provider sqlserver -f c:/temp/mysqlite.json"; var commandText = $"{singleCommand} {singleCommand}"; var cliTokens = _cliLexer.Lexize(commandText); // Act parser.Root = root; var ex = Assert.Throws <UnexpectedTokenException>(() => parser.Parse(cliTokens)); var textToken = (TextToken)ex.Token; Assert.That(textToken.Text, Is.EqualTo("sd")); }
private static HashSet <string> CreateReservedWords() { var grammar = typeof(SqlTestsHelper).Assembly.GetResourceText("sql-grammar.lisp", true); var tokens = TheLexer.Lexize(grammar); var reader = new TinyLispPseudoReader(); var form = reader.Read(tokens); var nodeFactory = new SqlNodeFactory(); var builder = new TreeBuilder(); var root = builder.Build(nodeFactory, form); var nodes = root.FetchTree(); var words = new List <string>(); words.AddRange(nodes .Where(x => x is ExactTextNode) .Cast <ExactTextNode>() .Select(x => x.ExactText.ToLowerInvariant())); words.AddRange(nodes .Where(x => x is MultiTextNode) .Cast <MultiTextNode>() .SelectMany(x => x.Texts.Select(y => y.ToLowerInvariant()))); return(new HashSet <string>(words)); }
public override void DoWork(Action <string, double> ReportProgress, Action Done) { Parent.Message = "Receiving..."; var Converter = (Parent as ReceiveLocalComponent).Converter; var @base = Operations.Receive(localDataId).Result; if (Converter.CanConvertToNative(@base)) { var converted = Converter.ConvertToNative(@base); data = new GH_Structure <IGH_Goo>(); data.Append(Utilities.TryConvertItemToNative(converted, Converter)); } else if (@base.GetDynamicMembers().Count() == 1) { var treeBuilder = new TreeBuilder(Converter); var tree = treeBuilder.Build(@base[@base.GetDynamicMembers().ElementAt(0)]); data = tree; } else { data = new GH_Structure <IGH_Goo>(); data.Append(new GH_SpeckleBase(@base)); } Done(); }
public void Update(TokenPage page, CompilationEnvironment environment) { _flatStatements.Clear(); Pattern pattern = MainPattern.Instance; foreach (PageLine line in page) { pattern.TryMatch(line, environment.Messages, out Expression expression); if (expression != null) { _flatStatements.Add(expression); } } Root = TreeBuilder.Build(_flatStatements, environment); foreach (ITreeTransform transform in _transforms) { transform.Apply(Root, environment); } ParseTestCommands(page, environment.Messages); }
/// <summary> /// 创建 Trie 树 /// </summary> /// <param name="words">分词集合</param> private void buildTree(ref LeftArray <string> words) { if (words.Length != 0) { TreeBuilder treeBuilder = new TreeBuilder(); foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { if (CharTypeData.Data == DefaultCharTypeData.Data) { AutoCSer.Memory.CopyNotNull(DefaultCharTypeData.Byte, (CharTypeData = Unmanaged.GetSizeUnsafe64(1 << 16, false)).Byte, 1 << 16); } fixed(char *wordFixed = word) { treeBuilder.Build(Boot, word, wordFixed); CharTypeData.Byte[*wordFixed] |= TrieGraphHeadFlag; char *start = wordFixed, end = wordFixed + word.Length; do { if (*start != ' ') { CharTypeData.Byte[*start] |= (byte)WordType.TrieGraph; } }while (++start != end); CharTypeData.Byte[*(end - 1)] |= TrieGraphEndFlag; } } } } }
public string GetXMLMap(string webconfigloc, UserAuthInfo userinfo) { string _xmlmapJSON = ""; JavaScriptSerializer js = new JavaScriptSerializer(); TreeBuilder _builder = new TreeBuilder(); try { nodes = _builder.BuildXmlString(webconfigloc); _xmlmapJSON = js.Serialize(nodes); } catch { try { nodes = _builder.Build(webconfigloc); _xmlmapJSON = js.Serialize(nodes); } catch (Exception appexp) { throw (appexp); } } return(_xmlmapJSON); }
public void BuildTreeTest() { //Given var builder = new TreeBuilder(); var trainingSet = new List <IrisRecord> { new IrisRecord { SepalLength = 5.1m, SepalWidth = 3.5m, PetalLength = 1.4m, PetalWidth = 0.2m, Classification = "Iris-setosa" }, new IrisRecord { SepalLength = 4.9m, SepalWidth = 3.0m, PetalLength = 1.4m, PetalWidth = 0.3m, Classification = "Iris-setosa" }, new IrisRecord { SepalLength = 6.5m, SepalWidth = 3.0m, PetalLength = 5.2m, PetalWidth = 2.0m, Classification = "Iris-virginica" }, new IrisRecord { SepalLength = 6.2m, SepalWidth = 3.4m, PetalLength = 5.4m, PetalWidth = 2.3m, Classification = "Iris-virginica" }, new IrisRecord { SepalLength = 5.9m, SepalWidth = 3.0m, PetalLength = 5.1m, PetalWidth = 1.8m, Classification = "Iris-virginica" }, }; //When var tree = builder.Build(trainingSet); var classification = tree.Evaluate(new IrisRecord { SepalLength = 5.4m, SepalWidth = 3.4m, PetalLength = 1.7m, PetalWidth = 0.2m }); //Then classification.Should().BeEquivalentTo("Iris-setosa"); }
/// <summary> /// Builds the moving tree and then disables game object. /// </summary> public void BuildMoving() { if (movingTree != null) { movingTree.Build(); movingTree.gameObject.SetActive(false); } }
static void Main(string[] args) { var tree = TreeBuilder.Build(KeyJoin); bool result = tree.Root.Evaluate(); Console.WriteLine(result); Console.Read(); }
public void GivenATreeBuiltWithNameGroupingOnly() { var tb = new TreeBuilder<INode>(); tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) }); var nn1 = new NameNode { Text = "X.Y.U" }; var nn2 = new NameNode { Text = "X.Y.V" }; _result = tb.Build(new[] { nn1, nn2 }); }
public void GivenATreeBuiltWithMultipleSteps() { var tb = new TreeBuilder<INode>(); tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) }); tb.Group<PartNode>() .When(pn => pn.Part.Contains(".")) .As(pn => new PartNode { Part = PartNode.Strip(pn.Part) }); _result = tb.Build(_names.Select(name => new NameNode { Text = name })); }
public void TestThatIncompleteTreeResultsInProperError() { var tb = new TreeBuilder<INode>(); tb.Group<NameNode>().As(nn => new PartNode { Part = PartNode.Strip(nn.Text) }); var nn1 = new NameNode { Text = "X.Y" }; var nn2 = new NameNode { Text = "A.B" }; Assert.Throws<ArgumentException>(() => tb.Build(new[] {nn1, nn2})); }
public void InOrderPostOrderSuccessTest(int[] inorder, int[] postorder, string expectedPreOrderTree) { // arrange // act TreeNode root = TreeBuilder.Build(inorder, postorder); var actualPreOrderTree = (root != null) ? root.ToString(): ""; // assert Assert.AreEqual(expectedPreOrderTree, actualPreOrderTree); }
static void Main(string[] args) { Solution s = new Solution(); int?[] values = new int?[] { 5, 4, 8, 11, null, 13, 4, 7, 2, null, null, null, 1 }; TreeNode node = TreeBuilder.Build(values); int rs = s.MaxPathSum(node); Console.WriteLine($"Result:{rs} - Expect: {48}"); }
public void DirOnlyTreeTest() { var output = new StringWriter(); var builder = new TreeBuilder(output); builder.Build(TestDataPath, false); var result = output.ToString(); Assert.Equal(DirsOnlyResult, result); }
public void FullTreeTest() { var output = new StringWriter(); var builder = new TreeBuilder(output); builder.Build(TestDataPath, true); var result = output.ToString(); Assert.Equal(FullResult, result); }
public void Test_Build_Not_Root() { CodeTimer.CodeExecuteTime(() => { var tree = TreeBuilder.Build <Product>() .SetItems(Data, t => t.Name, i => i.Id, p => p.ParentId) .Data; var result = tree.ToJson(); Console.WriteLine(result); }); }
void PostRespond(HttpListenerRequest request, HttpListenerResponse response) { NameValueCollection parms = GetParams(request); try { builder.Update(request.RawUrl, parms); response.StatusCode = 200; } catch (XpcaPathError) { builder.Build(request.RawUrl, parms); response.StatusCode = 201; } }
private void GenerateTree(object sender, RoutedEventArgs e) { try { _decisionTree = _builder.Build(_trainingSet); RunTestDataButton.IsEnabled = true; BuildTreeView(_decisionTree); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public void Build_ExcelParser_RSS() { // arrange FillItemSet_ExcelParser(); ISplitter splitter = new SplitterRss(); TreeBuilder builder = new TreeBuilder("Z", 10, new NameGenerator(), splitter); // act TreeGenerative tree = builder.Build(_set); // assert Assert.IsNotNull(tree); Assert.IsTrue(tree.FeatureNames.Count > 0); }
public void Comment() { var comment = new Token(TokenType.Comment, "head"); var tokens = new[] { comment, }; HtmlNode node = TreeBuilder.Build(tokens).ChildNodes.First(); Assert.Equal(HtmlNodeType.Comment, node.NodeType); Assert.Equal("head", node.Value); }
public void Load() { if (!File.Exists(configPath)) { return; } StreamReader file = File.OpenText(configPath); using (JsonTextReader jsonReader = new JsonTextReader(file)) { while (jsonReader.Read()) { if (jsonReader.TokenType == JsonToken.PropertyName) { string fullName = (string)jsonReader.Value; if (jsonReader.Read() && jsonReader.TokenType == JsonToken.StartObject) { NameValueCollection parms = new NameValueCollection(); while (jsonReader.Read() && jsonReader.TokenType != JsonToken.EndObject) { if (jsonReader.TokenType == JsonToken.PropertyName) { string key = (string)jsonReader.Value; if (jsonReader.Read()) { string value = (String)jsonReader.Value; parms.Add(key, value); } } } TreeBuilder builder = new TreeBuilder(srv); try { builder.Update(fullName, parms); } catch (XpcaPathError) { builder.Build(fullName, parms); } } } } } file.Close(); }
public void Build_Gini() { // arrange FillItemSet_Features4_Items15(); ISplitter splitter = new SplitterGini(); TreeBuilder builder = new TreeBuilder("F1", 5, new NameGenerator(), splitter); // act TreeGenerative tree = builder.Build(_set); // assert Assert.IsNotNull(tree); Assert.IsTrue(tree.FeatureNames.Count > 0); Assert.AreEqual(4, tree.FeatureNames.Count); }
public void CommentAfterBrIsOutside() { var br = new Token(TokenType.OpenTag, "BR"); var rn = new Token(TokenType.Comment, "i'm the comment!"); var tokens = new[] { br, rn, }; List <HtmlNode> nodes = TreeBuilder.Build(tokens).ChildNodes.ToList(); Assert.Equal(2, nodes.Count); }
public int GenerateTrees(int count, string resolutionFeatureName, int maxItemCountInCategory, float itemSubsetCountRatio) { _trees.Clear(); var nameGenerator = new NameGenerator(); _treeBulder = new TreeBuilder(resolutionFeatureName, maxItemCountInCategory, nameGenerator, _splitter); for (int i = 0; i < count; i++) { ItemNumericalSet subset = _set.GetRandomSubset(itemSubsetCountRatio, true); TreeGenerative tg = _treeBulder.Build(subset); _trees.Add(tg.ToTree()); nameGenerator.Reset(); } return(TreeCount()); }
public void CliParser_ValidInput_Parses() { // Arrange var nodeFactory = new CliNodeFactory("CLI node family"); var input = this.GetType().Assembly.GetResourceText("cli-grammar.lisp", true); var tokens = _tinyLispLexer.Lexize(input); var reader = new TinyLispPseudoReader(); var list = reader.Read(tokens); ITreeBuilder builder = new TreeBuilder(); var root = builder.Build(nodeFactory, list); IParser parser = new Parser { Root = root, }; var commandText = "sd --connection \"Server=.;Database=econera.diet.tracking;Trusted_Connection=True;\" --provider sqlserver -f c:/temp/mysqlite.json"; var cliTokens = _cliLexer.Lexize(commandText); // Act parser.Root = root; var cliResults = parser.Parse(cliTokens); // Assert var cliCommand = (CliCommand)cliResults.Single(); var commandEntry = cliCommand.Entries.Single(x => string.Equals(x.Alias, "connection", StringComparison.InvariantCultureIgnoreCase)); Assert.That( commandEntry.Value, Is.EqualTo("Server=.;Database=econera.diet.tracking;Trusted_Connection=True;")); commandEntry = cliCommand.Entries.Single(x => string.Equals(x.Alias, "provider", StringComparison.InvariantCultureIgnoreCase)); Assert.That( commandEntry.Value, Is.EqualTo("sqlserver")); commandEntry = cliCommand.Entries.Single(x => string.Equals(x.Alias, "file", StringComparison.InvariantCultureIgnoreCase)); Assert.That( commandEntry.Value, Is.EqualTo("c:/temp/mysqlite.json")); }
public void SelfClosingTagBr() { var br = new Token(TokenType.OpenTag, "br"); var body = new Token(TokenType.OpenTag, "body"); var tokens = new[] { br, body, }; List <HtmlNode> nodes = TreeBuilder.Build(tokens).ChildNodes.ToList(); Assert.Equal(2, nodes.Count); }
public override void DoWork(Action <string, double> ReportProgress, Action Done) { try { Parent.Message = "Receiving..."; var Converter = (Parent as ReceiveLocalComponent).Converter; Base @base = null; try { @base = Operations.Receive(localDataId).Result; } catch (Exception e) { RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, "Failed to receive local data.")); Done(); return; } if (Converter.CanConvertToNative(@base)) { var converted = Converter.ConvertToNative(@base); data = new GH_Structure <IGH_Goo>(); data.Append(Utilities.TryConvertItemToNative(converted, Converter)); } else if (@base.GetDynamicMembers().Count() == 1) { var treeBuilder = new TreeBuilder(Converter); var tree = treeBuilder.Build(@base[@base.GetDynamicMembers().ElementAt(0)]); data = tree; } else { data = new GH_Structure <IGH_Goo>(); data.Append(new GH_SpeckleBase(@base)); } } catch (Exception e) { // If we reach this, something happened that we weren't expecting... Log.CaptureException(e); RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message)); Parent.Message = "Error"; } Done(); }
public void ThreeSelfClosingTagUpperCaseBr() { var br1 = new Token(TokenType.OpenTag, "BR"); var br2 = new Token(TokenType.OpenTag, "BR"); var br3 = new Token(TokenType.OpenTag, "BR"); var tokens = new[] { br1, br2, br3, }; List <HtmlNode> nodes = TreeBuilder.Build(tokens).ChildNodes.ToList(); Assert.Equal(3, nodes.Count); }
public void Build_EmptySeq_ThrowsTinyLispException() { // Arrange var lisp = "(defblock :name foo :is-top t (seq))"; var tokens = _lexer.Lexize(lisp); var reader = new TinyLispPseudoReader(); var pseudoList = reader.Read(tokens); ITreeBuilder builder = new TreeBuilder(); INodeFactory factory = new SqlNodeFactory(); // Act var ex = Assert.Throws <TinyLispException>(() => builder.Build(factory, pseudoList)); // Assert Assert.That(ex.Message, Is.EqualTo("Free arguments not found.")); }
public void TestPropTesterBasic() { var matched = new List<string>(); var not_matched = new List<string>(); var should_matched = new List<string> { "steve", "jeff" }; var should_not_matched = new List<string> { "jimbo", "george" }; var tester = new TreeBuilder<DataClass>(); tester.Push("name", "steve", comparison.Equals) .Push("name", "jeff", comparison.Equals) .Or(); var lambda = tester.Build(); foreach (var item in MakeSomeDataObjs()) { if (lambda(item)) matched.Add(item.name); else not_matched.Add(item.name); } Assert.IsTrue(Enumerable.SequenceEqual(matched.OrderBy(p => p), should_matched.OrderBy(p => p))); Assert.IsTrue(Enumerable.SequenceEqual(not_matched.OrderBy(p => p), should_not_matched.OrderBy(p => p))); }
public void TestTesterSerialization1() { var tester = new TreeBuilder<DataClass>(); tester.Push("name", "steve", comparison.Equals) .Push("name", "jeff", comparison.Equals) .Or(); var lambda = tester.Build(); var json = JsonConvert.SerializeObject(tester.tree); Assert.IsNotNull(json); var tree = JsonConvert.DeserializeObject<Node>(json); Assert.IsNotNull(tree); Console.WriteLine(json); }