Search Results

Search found 5101 results on 205 pages for 'expression trees'.

Page 73/205 | < Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >

  • Central renderer for a given scene

    - by Loggie
    When creating a central rendering system for all game objects in a given scene I am trying to work out the best way to go about passing the scene to the render system to be rendered. If I have a scene managed by an arbitrary structure, i.e., an octree, bsp trees, quad-tree, kd tree, etc. What is the best way to pass this to the render system? The obvious problem is that if simply given the root node of the structure, the render system would require an intrinsic knowledge of the structure in order to traverse the structure. My solution to this is to clip all objects outside the frustum in the scene manager and then create a list of the objects which are left and pass this simple list to the render system, be it an array, a vector, a linked list, etc. (This would be a structure required by the render system as a means to know which objects should be rendered). The list would of course attempt to minimise OpenGL state changes by grouping objects that require the same rendering operations to be performed on them. I have been thinking a lot about this and started searching various terms on here and followed any additional information/links but I have not really found a definitive answer. The case may be that there is no definitive answer but I would appreciate some advice and tips. My question is, is this a reasonable solution to the problem? Are there any improvements that I could make? Are there any caveats I should know about? Side question: Am I right in assuming that octrees, bsp trees, etc are all forms of BVH?

    Read the article

  • How does the new google maps make buildings and cityscapes 3D?

    - by Aerovistae
    Anyone who's seen the new Google maps has no doubt taken note of the incredible amount of three-dimensional detail in select American cities such as Boston, New York, Chicago, and San Francisco. They've even modeled the trees, bridges and some of the boats in the harbor! Minor architectural details are present. It's crazy. Looking at it up close, I've found there's a rectangular area around each of those cities, and anything within them is 3Dified, but it cuts off hard and fast at the edge, even if it's in the middle of a building. The edge of the rectangle is where the 3D stops. This leads me to think it's being done algorithmically (which would make sense, given the scale of the project, how many trees and buildings and details there are), and yet I can't imagine how that's possible. How could an algorithm model all these things without extensive data on their shapes and contours? How could it model the individual wires of a bridge, or the statues in a park? It must be done by hand, and yet how could it be for so much detail! Does anyone have any insight on this?

    Read the article

  • SQL Server: Writing CASE expressions properly when NULLs are involved

    - by Mladen Prajdic
    We’ve all written a CASE expression (yes, it’s an expression and not a statement) or two every now and then. But did you know there are actually 2 formats you can write the CASE expression in? This actually bit me when I was trying to add some new functionality to an old stored procedure. In some rare cases the stored procedure just didn’t work correctly. After a quick look it turned out to be a CASE expression problem when dealing with NULLS. In the first format we make simple “equals to” comparisons to a value: SELECT CASE <value> WHEN <equals this value> THEN <return this> WHEN <equals this value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Second format is much more flexible since it allows for complex conditions. USE THIS ONE! SELECT CASE WHEN <value> <compared to> <value> THEN <return this> WHEN <value> <compared to> <value> THEN <return this> -- ... more WHEN's here ELSE <return this> END Now that we know both formats and you know which to use (the second one if that hasn’t been clear enough) here’s an example how the first format WILL make your evaluation logic WRONG. Run the following code for different values of @i. Just comment out any 2 out of 3 “SELECT @i =” statements. DECLARE @i INTSELECT  @i = -1 -- first resultSELECT  @i = 55 -- second resultSELECT  @i = NULL -- third resultSELECT @i AS OriginalValue, -- first CASE format. DON'T USE THIS! CASE @i WHEN -1 THEN '-1' WHEN NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS DontUseThisCaseFormatValue, -- second CASE format. USE THIS! CASE WHEN @i = -1 THEN '-1' WHEN @i IS NULL THEN 'We have a NULL!' ELSE 'We landed in ELSE' END AS UseThisCaseFormatValue When the value of @i is –1 everything works as expected, since both formats go into the –1 WHEN branch. When the value of @i is 55 everything again works as expected, since both formats go into the ELSE branch. When the value of @i is NULL the problems become evident. The first format doesn’t go into the WHEN NULL branch because it makes an equality comparison between two NULLs. Because a NULL is an unknown value: NULL = NULL is false. That is why the first format goes into the ELSE Branch but the second format correctly handles the proper IS NULL comparison.   Please use the second more explicit format. Your future self will be very grateful to you when he doesn’t have to discover these kinds of bugs.

    Read the article

  • Why does Gnumake from parent directory behave differently?

    - by WilliamKF
    I am stumped as to why when I do a gnumake from the parent directory it behaves incorrectly, whereas, if I cd to the subdirectory and do gnumake it works correctly. In the parent makefile, I have a rule like this: .PHONY: zlib-1.2.5 zlib-1.2.5: @ echo Issuing $(MAKE) in $@ ... pushd zlib-1.2.5; make; popd Which gives different result than doing the same from the toplevel pushd zlib-1.2.5; make; popd There is a something from the parent makefile that is making its way into the subdirectory makefile and causing it to behave incorrectly, but I don't know how to find it. The symptom I see is that the subdirectory config generated makefile rule for zlib misses the dependencies and I get this result going straight to the ar without generating the .o(s) first: cd ~/src; make zlib-1.2.5 CPPFLAGS_AUTO = < > Issuing make in zlib-1.2.5 ... pushd zlib-1.2.5; make; popd ~/src/zlib-1.2.5 ~/src make[1]: Entering directory `/disk2/user/src/zlib-1.2.5' ar rc libz.a adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o ar: adler32.o: No such file or directory make[1]: *** [libz.a] Error 1 gcc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map -O3 -fPIC -D_LARGEFILE64_SOURCE=1 -o libz.so.1.2.5 adler32.lo compress.lo crc32.lo deflate.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo uncompr.lo zutil.lo -lc -L. libz.a gcc: adler32.lo: No such file or directory gcc: compress.lo: No such file or directory gcc: crc32.lo: No such file or directory gcc: deflate.lo: No such file or directory [...] make[1]: *** [libz.so.1.2.5] Error 1 make[1]: Target `all' not remade because of errors. make[1]: Leaving directory `/disk2/user/src/zlib-1.2.5' ~/src Versus from the zlib directory where it works correctly: cd ~/src/zlib-1.2.5; make gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o example.o example.c gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o adler32.o adler32.c gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o compress.o compress.c gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o crc32.o crc32.c [...] gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o zutil.o zutil.c ar rc libz.a adler32.o compress.o crc32.o deflate.o gzclose.o gzlib.o gzread.o gzwrite.o infback.o inffast.o inflate.o inftrees.o trees.o uncompr.o zutil.o (ranlib libz.a || true) >/dev/null 2>&1 gcc -O3 -D_LARGEFILE64_SOURCE=1 -o example example.o -L. libz.a gcc -O3 -D_LARGEFILE64_SOURCE=1 -c -o minigzip.o minigzip.c gcc -O3 -D_LARGEFILE64_SOURCE=1 -o minigzip minigzip.o -L. libz.a mkdir objs 2>/dev/null || test -d objs gcc -O3 -fPIC -D_LARGEFILE64_SOURCE=1 -DPIC -c -o objs/adler32.o adler32.c mv objs/adler32.o adler32.lo mkdir objs 2>/dev/null || test -d objs gcc -O3 -fPIC -D_LARGEFILE64_SOURCE=1 -DPIC -c -o objs/compress.o compress.c mv objs/compress.o compress.lo [...] mkdir objs 2>/dev/null || test -d objs gcc -O3 -fPIC -D_LARGEFILE64_SOURCE=1 -DPIC -c -o objs/zutil.o zutil.c mv objs/zutil.o zutil.lo gcc -shared -Wl,-soname,libz.so.1,--version-script,zlib.map -O3 -fPIC -D_LARGEFILE64_SOURCE=1 -o libz.so.1.2.5 adler32.lo compress.lo crc32.lo deflate.lo gzclose.lo gzlib.lo gzread.lo gzwrite.lo infback.lo inffast.lo inflate.lo inftrees.lo trees.lo uncompr.lo zutil.lo -lc -L. libz.a rm -f libz.so libz.so.1 ln -s libz.so.1.2.5 libz.so ln -s libz.so.1.2.5 libz.so.1 rmdir objs gcc -O3 -D_LARGEFILE64_SOURCE=1 -o examplesh example.o -L. libz.so.1.2.5 gcc -O3 -D_LARGEFILE64_SOURCE=1 -o minigzipsh minigzip.o -L. libz.so.1.2.5 gcc -O3 -D_LARGEFILE64_SOURCE=1 -o example64 example64.o -L. libz.a gcc -O3 -D_LARGEFILE64_SOURCE=1 -o minigzip64 minigzip64.o -L. libz.a

    Read the article

  • Why does my performance slow to a crawl I move methods into a base class?

    - by Juliet
    I'm writing different implementations of immutable binary trees in C#, and I wanted my trees to inherit some common methods from a base class. However, I find. I have lots of binary tree data structures to implement, and I wanted move some common methods into in a base binary tree class. Unfortunately, classes which derive from the base class are abysmally slow. Non-derived classes perform adequately. Here are two nearly identical implementations of an AVL tree to demonstrate: AvlTree: http://pastebin.com/V4WWUAyT DerivedAvlTree: http://pastebin.com/PussQDmN The two trees have the exact same code, but I've moved the DerivedAvlTree.Insert method in base class. Here's a test app: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Juliet.Collections.Immutable; namespace ConsoleApplication1 { class Program { const int VALUE_COUNT = 5000; static void Main(string[] args) { var avlTreeTimes = TimeIt(TestAvlTree); var derivedAvlTreeTimes = TimeIt(TestDerivedAvlTree); Console.WriteLine("avlTreeTimes: {0}, derivedAvlTreeTimes: {1}", avlTreeTimes, derivedAvlTreeTimes); } static double TimeIt(Func<int, int> f) { var seeds = new int[] { 314159265, 271828183, 231406926, 141421356, 161803399, 266514414, 15485867, 122949829, 198491329, 42 }; var times = new List<double>(); foreach (int seed in seeds) { var sw = Stopwatch.StartNew(); f(seed); sw.Stop(); times.Add(sw.Elapsed.TotalMilliseconds); } // throwing away top and bottom results times.Sort(); times.RemoveAt(0); times.RemoveAt(times.Count - 1); return times.Average(); } static int TestAvlTree(int seed) { var rnd = new System.Random(seed); var avlTree = AvlTree<double>.Create((x, y) => x.CompareTo(y)); for (int i = 0; i < VALUE_COUNT; i++) { avlTree = avlTree.Insert(rnd.NextDouble()); } return avlTree.Count; } static int TestDerivedAvlTree(int seed) { var rnd = new System.Random(seed); var avlTree2 = DerivedAvlTree<double>.Create((x, y) => x.CompareTo(y)); for (int i = 0; i < VALUE_COUNT; i++) { avlTree2 = avlTree2.Insert(rnd.NextDouble()); } return avlTree2.Count; } } } AvlTree: inserts 5000 items in 121 ms DerivedAvlTree: inserts 5000 items in 2182 ms My profiler indicates that the program spends an inordinate amount of time in BaseBinaryTree.Insert. Anyone whose interested can see the EQATEC log file I've created with the code above (you'll need EQATEC profiler to make sense of file). I really want to use a common base class for all of my binary trees, but I can't do that if performance will suffer. What causes my DerivedAvlTree to perform so badly, and what can I do to fix it?

    Read the article

  • ASP NET MVC : "Cannot order by type 'System.Object'."

    - by rah.deex
    This is my code. I got this sample from the Internet and I tried to modify it. private void FillGridData() { //IQueryable<SVC> query = _customerService.GetQueryable(); _dataContext = new dbServiceModelDataContext(); var query = from m in _dataContext.SVCs select m; query = AddQuerySearchCriteria(query, _grid.SearchForm); int totalRows = query.Count(); _grid.Pager.Init(totalRows); if (totalRows == 0) { _grid.Data = new List<SVC>(); return; } query = AddQuerySorting(query, _grid.Sorter); query = AddQueryPaging(query, _grid.Pager); List<SVC> customers = query.ToList(); //***ERROR IN HERE***// _grid.Data = customers; } The error says "Cannot order by type 'System.Object'.", what is the matter? Do you have solution for me? This is The AddQuerySorting Method THE PROBLEM IS IN HERE is there anything wrong about the code? :( private IQueryable<SVC> AddQuerySorting(IQueryable<SVC> query, Sorter sorter) { if (String.IsNullOrEmpty(sorter.SortField)) return query; //Used approach from http://www.singingeels.com/Articles/Self_Sorting_GridView_with_LINQ_Expression_Trees.aspx //instead of a long switch statement var param = Expression.Parameter(typeof(SVC), "customer"); var sortExpression = Expression.Lambda<Func<SVC, object>> (Expression.Convert(Expression.Property(param, sorter.SortField), typeof(object)), param); if (sorter.SortDirection == SortDirection.Asc) query = query.OrderBy(sortExpression); else query = query.OrderByDescending(sortExpression); return query; } here is AddQueryPaging Method private IQueryable<SVC> AddQueryPaging(IQueryable<SVC> query, Pager pager) { if (pager.TotalPages == 0) return query; query = query.Skip((pager.CurrentPage - 1) * pager.PageSize) .Take(pager.PageSize); return query; }

    Read the article

  • How to create basic Adobe Illustrator files programatically?

    - by Jonas Follesø
    I need to create a really basic Adobe Illustrator file on the clipboard that I can paste in Adobe Illustrator or Expression Design. I'm looking for code samples on how to programaticaly generate Adobe Illustrator Files, preferably from C# or some other .NET language (but at the moment any language goes). I have found the Adobe Illustrator 3 File Format documentation online but it's allot to digest for this simple scenario. I don't want to depend on the actual Adobe Illustrator program (COM interop for instance) to generate my documents. Must be pure code. The code is for an Expression Studio addin, and I need to be able to create something on the clipboard I can paste into Expression Design. After looking at the formats Expression Design puts on the clipboard when copying a basic shape I've concluded that ADOBE AI3 i the best one to use (the others are either rendered images, or cfXaml that you cannot paste INTO Design). So based on this I can't use SWG which would probably been easier. Another idea might be to use a PDF component as the AI and PDF format is supposed to be compatible? I'm also finding some references to a format called "Adobe Illustrator Clipboard Format" (AICB), but can't find allot of documentation about it.

    Read the article

  • How to Process Lambda Expressions Passed as Argument Into Method - C# .NET 3.5

    - by Sunday Ironfoot
    My knowledge of Lambda expressions is a bit shaky, while I can write code that uses Lambda expressions (aka LINQ), I'm trying to write my own method that takes a few arguments that are of type Lambda Expression. Background: I'm trying to write a method that returns a Tree Collection of objects of type TreeItem from literally ANY other object type. I have the following so far: public class TreeItem { public string Id { get; set; } public string Text { get; set; } public TreeItem Parent { get; protected set; } public IList<TreeItem> Children { get { // Implementation that returns custom TreeItemCollection type } } public static IList<TreeItem> GetTreeFromObject<T>(IList<T> items, Expression<Func<T, string>> id, Expression<Func<T, string>> text, Expression<Func<T, IList<T>>> childProperty) where T : class { foreach (T item in items) { // Errrm!?? What do I do now? } return null; } } ...which can be called via... IList<TreeItem> treeItems = TreeItem.GetTreeFromObject<Category>( categories, c => c.Id, c => c.Name, c => c.ChildCategories); I could replace the Expressions with string values, and just use reflection, but I'm trying to avoid this as I want to make it strongly typed. My reasons for doing this is that I have a control that accepts a List of type TreeItem, whereas I have dozens of different types that are all in a tree like structure, and don't want to write seperate conversion methods for each type (trying to adhere to the DRY principle). Am I going about this the right way? Is there a better way of doing this perhaps?

    Read the article

  • script to search and replace deprecated functions

    - by user573881
    Hi, I am using the following script to search and replace the deprecated functions in a file with the newer ones. 5 for strFile in `ls deprecated_functions_search_and_replace.txt ` 6 do 7 sed "s/ereg_replace[^\(]*(\([^,]*\),/preg_replace\1('#'.\2.'#',/g" $strFile > temp_file 8 mv $strFile $strFile".bakup" 9 mv temp_file $strFile 10 11 sed "s/eregi[^\(]*(\([^,]*\),/preg_match\1('#'.\2.'#i',/g" $strFile > temp_file 12 mv $strFile $strFile".bakup" 13 mv temp_file $strFile 14 15 sed "s/ereg[^\(]*(\([^,]*\),/preg_match\1('#'.\2.'#',/g" $strFile > temp_file 16 mv $strFile $strFile".bakup" 17 mv temp_file $strFile 18 19 sed "s/split[^\(]*(\([^,]*\),/preg_split\1('#'.\2.'#',/g" $strFile > temp_file 20 mv $strFile $strFile".bakup" 21 mv temp_file $strFile 22 23 sed "s/mysql_escape_string/mysql_real_escape_string/g" $strFile > temp_file 24 mv $strFile $strFile".bakup" 25 mv temp_file $strFile 26 27 sed "s/set_magic_quotes_runtime(0)/\/\/set_magic_quotes_runtime(0)/g" $strFile > temp_file 28 mv $strFile $strFile".bakup" 29 mv temp_file $strFile 30 31 sed "s/ini_get('safe_mode')/false/g" $strFile > temp_file 32 mv $strFile $strFile".bakup" 33 mv temp_file $strFile 34 35 sed "s/session_register('\(.*\)')/$_SESSION['\1']=$\1/g" $strFile > temp_file 36 mv $strFile $strFile".bakup" 37 mv temp_file $strFile 38 39 sed "s/session_unregister('\(.*\)')/$_SESSION['\1']=''/g" $strFile > temp_file 40 mv $strFile $strFile".bakup" 41 mv temp_file $strFile 42 43 done However, when I run this script I am getting an error saying: sed: -e expression #1, char 60: invalid reference \2 on `s' command's RHS sed: -e expression #1, char 52: invalid reference \2 on `s' command's RHS sed: -e expression #1, char 50: invalid reference \2 on `s' command's RHS sed: -e expression #1, char 51: invalid reference \2 on `s' command's RHS I am unable to figure out whats going wrong. Someone please help me. Regards.

    Read the article

  • error of integer overflow

    - by user308565
    This the part of my OpenGL code, I am getting an error for : struct Ball { float x; float y; float rot; float dir; bool rmv; Ball* next; }; Ball* curBall; void addBall() { if (balls==NULL) { balls=new Ball; balls->next=NULL; curBall=balls; } else { curBall->next=new Ball; curBall=curBall->next; curBall->next=NULL; } curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1; curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1; curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1; curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1; curBall->rmv=false; } error : In function ‘void addBall()’: file.cpp:120: warning: integer overflow in expression file.cpp:121: warning: integer overflow in expression file.cpp:122: warning: integer overflow in expression file.cpp:123: warning: integer overflow in expression

    Read the article

  • How can I combine several Expressions into a fast method?

    - by chillitom
    Suppose I have the following expressions: Expression<Action<T, StringBuilder>> expr1 = (t, sb) => sb.Append(t.Name); Expression<Action<T, StringBuilder>> expr2 = (t, sb) => sb.Append(", "); Expression<Action<T, StringBuilder>> expr3 = (t, sb) => sb.Append(t.Description); I'd like to be able to compile these into a method/delegate equivalent to the following: void Method(T t, StringBuilder sb) { sb.Append(t.Name); sb.Append(", "); sb.Append(t.Description); } What is the best way to approach this? I'd like it to perform well, ideally with performance equivalent to the above method. UPDATE So, whilst it appears that there is no way to do this directly in C#3 is there a way to convert an expression to IL so that I can use it with System.Reflection.Emit?

    Read the article

  • Help with Boost Spirit ASTs

    - by Decmac04
    I am writing a small tool for analyzing simple B Machine substitutions as part of a college research work. The code successfully parse test inputs of the form mySubst := var1 + var2. However, I get a pop-up error message saying "This application has requested the Runtime to terminate it in an unusual way. " In the command prompt window, I get an "Assertion failed message". The main program is given below: // BMachineTree.cpp : Defines the entry point for the console application. // /*============================================================================= Copyright (c) 2010 Temitope Onunkun =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // UUsing Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// #define BOOST_SPIRIT_DUMP_PARSETREE_AS_XML #include <boost/spirit/core.hpp> #include <boost/spirit/tree/ast.hpp> #include <boost/spirit/tree/tree_to_xml.hpp> #include "BMachineTreeGrammar.hpp" #include <iostream> #include <stack> #include <functional> #include <string> #include <cassert> #include <vector> #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) #include <map> #endif // Using AST to parse B Machine substitutions //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; typedef char const* iterator_t; typedef tree_match<iterator_t> parse_tree_match_t; typedef parse_tree_match_t::tree_iterator iter_t; //////////////////////////////////////////////////////////////////////////// string evaluate(parse_tree_match_t hit); string eval_machine(iter_t const& i); vector<string> dx; string evaluate(tree_parse_info<> info) { return eval_machine(info.trees.begin()); } string eval_machine(iter_t const& i) { cout << "In eval_machine. i->value = " << string(i->value.begin(), i->value.end()) << " i->children.size() = " << i->children.size() << endl; if (i->value.id() == substitution::leafValueID) { assert(i->children.size() == 0); // extract string tokens string leafValue(i->value.begin(), i->value.end()); dx.push_back(leafValue.c_str()); return leafValue.c_str(); } // else if (i->value.id() == substitution::termID) { if ( (*i->value.begin() == '*') || (*i->value.begin() == '/') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } // else assert(0); } else if (i->value.id() == substitution::expressionID) { if ( (*i->value.begin() == '+') || (*i->value.begin() == '-') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + " " + eval_machine(i->children.begin()+1); } else assert(0); } // else if (i->value.id() == substitution::simple_substID) { if (*i->value.begin() == (':' >> '=') ) { assert(i->children.size() == 2); dx.push_back( eval_machine(i->children.begin()) ); dx.push_back( eval_machine(i->children.begin()+1) ); return eval_machine(i->children.begin()) + "|->" + eval_machine(i->children.begin()+1); } else assert(0); } else { assert(0); // error } return 0; } //////////////////////////////////////////////////////////////////////////// int main() { // look in BMachineTreeGrammar for the definition of BMachine substitution BMach_subst; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "\t\tB Machine Substitution...\n\n"; cout << "/////////////////////////////////////////////////////////\n\n"; cout << "Type an expression...or [q or Q] to quit\n\n"; string str; while (getline(cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; tree_parse_info<> info = ast_parse(str.c_str(), BMach_subst, space_p); if (info.full) { #if defined(BOOST_SPIRIT_DUMP_PARSETREE_AS_XML) // dump parse tree as XML std::map<parser_id, std::string> rule_names; rule_names[substitution::identifierID] = "identifier"; rule_names[substitution::leafValueID] = "leafValue"; rule_names[substitution::factorID] = "factor"; rule_names[substitution::termID] = "term"; rule_names[substitution::expressionID] = "expression"; rule_names[substitution::simple_substID] = "simple_subst"; tree_to_xml(cout, info.trees, str.c_str(), rule_names); #endif // print the result cout << "Variables in Vector dx: " << endl; for(vector<string>::iterator idx = dx.begin(); idx < dx.end(); ++idx) cout << *idx << endl; cout << "parsing succeeded\n"; cout << "result = " << evaluate(info) << "\n\n"; } else { cout << "parsing failed\n"; } } cout << "Bye... :-) \n\n"; return 0; } The grammar, defined in BMachineTreeGrammar.hpp file is given below: /*============================================================================= Copyright (c) 2010 Temitope Onunkun http://www.dcs.kcl.ac.uk/pg/onun Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_BMachineTreeGrammar_HPP_ #define BOOST_SPIRIT_BMachineTreeGrammar_HPP_ using namespace boost::spirit; /////////////////////////////////////////////////////////////////////////////// // // Using Boost Spririt Trees (AST) to parse B Machine Substitutions. // /////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// // // B Machine Grammar // //////////////////////////////////////////////////////////////////////////// struct substitution : public grammar<substitution> { static const int identifierID = 1; static const int leafValueID = 2; static const int factorID = 3; static const int termID = 4; static const int expressionID = 5; static const int simple_substID = 6; template <typename ScannerT> struct definition { definition(substitution const& ) { // Start grammar definition identifier = alpha_p >> (+alnum_p | ch_p('_') ) ; leafValue = leaf_node_d[ lexeme_d[ identifier | +digit_p ] ] ; factor = leafValue | inner_node_d[ ch_p( '(' ) >> expression >> ch_p(')' ) ] ; term = factor >> *( (root_node_d[ch_p('*') ] >> factor ) | (root_node_d[ch_p('/') ] >> factor ) ); expression = term >> *( (root_node_d[ch_p('+') ] >> term ) | (root_node_d[ch_p('-') ] >> term ) ); simple_subst= leaf_node_d[ lexeme_d[ identifier ] ] >> root_node_d[str_p(":=")] >> expression ; // End grammar definition // turn on the debugging info. BOOST_SPIRIT_DEBUG_RULE(identifier); BOOST_SPIRIT_DEBUG_RULE(leafValue); BOOST_SPIRIT_DEBUG_RULE(factor); BOOST_SPIRIT_DEBUG_RULE(term); BOOST_SPIRIT_DEBUG_RULE(expression); BOOST_SPIRIT_DEBUG_RULE(simple_subst); } rule<ScannerT, parser_context<>, parser_tag<simple_substID> > simple_subst; rule<ScannerT, parser_context<>, parser_tag<expressionID> > expression; rule<ScannerT, parser_context<>, parser_tag<termID> > term; rule<ScannerT, parser_context<>, parser_tag<factorID> > factor; rule<ScannerT, parser_context<>, parser_tag<leafValueID> > leafValue; rule<ScannerT, parser_context<>, parser_tag<identifierID> > identifier; rule<ScannerT, parser_context<>, parser_tag<simple_substID> > const& start() const { return simple_subst; } }; }; #endif The output I get on running the program is: ///////////////////////////////////////////////////////// B Machine Substitution... ///////////////////////////////////////////////////////// Type an expression...or [q or Q] to quit mySubst := var1 - var2 parsing succeeded In eval_machine. i->value = := i->children.size() = 2 Assertion failed: 0, file c:\redmound\bmachinetree\bmachinetree\bmachinetree.cpp , line 114 I will appreciate any help in resolving this problem.

    Read the article

  • Asp.net MVC 2, MvcContrib, and a base controller with redirect actions

    - by jeriley
    I've got a base controller that takes a couple generics, nothing overly fancy. public class SystemBaseController<TForm, TFormViewModel> : Controller where TForm : class, IForm where TFormViewModel : class, IViewModel ok, no big deal. I have a method "CompleteForm" that takes in the viewModel, looks kinda like this ... public ActionResult CompleteForm(TFormViewModel viewModel) { //does some stuff return this.RedirectToAction(c => c.FormInfo(viewModel)); } Problem is, the controller that inherits this, like so public class SalesFormController : SystemBaseController<SalesForm, SalesViewModel> { } I end up getting a error from MvcContrib - Controller name must end in 'Controller' at this point ... public RedirectToRouteResult(Expression<Action<T>> expression) : this(expression, expr => Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(expr)) {} The expression that's passed in is correct (SystemBaseController blahblah) but I'm not sure why its 1.) saying there's no controller at the end, and 2.) if I pull out everything into the controller (out of the base), works just fine. Do I need to write or setup some kind of action filter of my own or what am I missing?

    Read the article

  • Linq Query Performance , comparing Compiled query vs Non-Compiled.

    - by AG.
    Hello Guys, I was wondering if i extract the common where clause query into a common expression would it make my query much faster, if i have say something like 10 linq queries on a collection with exact same 1st part of the where clause. I have done a small example to explain a bit more . public class Person { public string First { get; set; } public string Last { get; set; } public int Age { get; set; } public String Born { get; set; } public string Living { get; set; } } public sealed class PersonDetails : List<Person> { } PersonDetails d = new PersonDetails(); d.Add(new Person() {Age = 29, Born = "Timbuk Tu", First = "Joe", Last = "Bloggs", Living = "London"}); d.Add(new Person() { Age = 29, Born = "Timbuk Tu", First = "Foo", Last = "Bar", Living = "NewYork" }); Expression<Func<Person, bool>> exp = (a) => a.Age == 29; Func<Person, bool> commonQuery = exp.Compile(); var lx = from y in d where commonQuery.Invoke(y) && y.Living == "London" select y; var bx = from y in d where y.Age == 29 && y.Living == "NewYork" select y; Console.WriteLine("All Details {0}, {1}, {2}, {3}, {4}", lx.Single().Age, lx.Single().First , lx.Single().Last, lx.Single().Living, lx.Single().Born ); Console.WriteLine("All Details {0}, {1}, {2}, {3}, {4}", bx.Single().Age, bx.Single().First, bx.Single().Last, bx.Single().Living, bx.Single().Born); So can some of the guru's here give me some advice if it would be a good practice to write query like var lx = "Linq Expression " or var bx = "Linq Expression" ? Any inputs would be highly appreciated. Thanks, AG

    Read the article

  • Linq PredicateBuilder with conditional AND, OR and NOT filters.

    - by richeym
    We have a project using LINQ to SQL, for which I need to rewrite a couple of search pages to allow the client to select whether they wish to perform an and or an or search. I though about redoing the LINQ queries using PredicateBuilder and have got this working pretty well I think. I effectively have a class containing my predicates, e.g.: internal static Expression<Func<Job, bool>> Description(string term) { return p => p.Description.Contains(term); } To perform the search i'm doing this (some code omitted for brevity): public Expression<Func<Job, bool>> ToLinqExpression() { var predicates = new List<Expression<Func<Job, bool>>>(); // build up predicates here if (SearchType == SearchType.And) { query = PredicateBuilder.True<Job>(); } else { query = PredicateBuilder.False<Job>(); } foreach (var predicate in predicates) { if (SearchType == SearchType.And) { query = query.And(predicate); } else { query = query.Or(predicate); } } return query; } While i'm reasonably happy with this, I have two concerns: The if/else blocks that evaluate a SearchType property feel like they could be a potential code smell. The client is now insisting on being able to perform 'and not' / 'or not' searches. To address point 2, I think I could do this by simply rewriting my expressions, e.g.: internal static Expression<Func<Job, bool>> Description(string term, bool invert) { if (invert) { return p => !p.Description.Contains(term); } else { return p => p.Description.Contains(term); } } However this feels like a bit of a kludge, which usually means there's a better solution out there. Can anyone recommend how this could be improved? I'm aware of dynamic LINQ, but I don't really want to lose LINQ's strong typing.

    Read the article

  • Problem building STLport NDK r5/ Android

    - by user558299
    Hi all, I'm trying to build STLport for Android. I got the following steps, but they are not working: 1 - Clone STLport repository using: git clone git://stlport.git.sourceforge.net/gitroot/stlport/stlport 2 - Configure environment using : ./configure --target=arm-eabi --with-extra-cxxflags="-fshort-enums" --with-extra-cflags="-fshort-enums" 3 - From src directory build it using make SYSROOT"{MY NDK path}/platforms/android-5/arch-arm/" release-static But I got the following errors: In file included from ../stlport/stl/_alloc.h:45, from ../stlport/memory:29, from dll_main.cpp:41: ../stlport/stl/_new.h:45:24: error: new: No such file or directory In file included from ../stlport/stl/_limits.h:36, from ../stlport/limits:29, from dll_main.cpp:48: ../stlport/stl/_cwchar.h:26:30: error: cstddef: No such file or directory In file included from ../stlport/stl/_utility.h:35, from ../stlport/utility:35, from dll_main.cpp:40: ../stlport/type_traits:889: error: 'declval' was not declared in this scope ../stlport/type_traits:889: error: expected primary-expression before '>' token ../stlport/type_traits:889: error: expected primary-expression before ')' token ../stlport/type_traits:889: error: 'declval' was not declared in this scope ../stlport/type_traits:889: error: expected primary-expression before '>' token ../stlport/type_traits:889: error: expected primary-expression before ')' token ../stlport/type_traits:889: error: ISO C++ forbids declaration of 'decltype' with no type ../stlport/type_traits:889: error: ISO C++ forbids in-class initialization of non-const static member 'decltype' ../stlport/type_traits:889: error: template declaration of 'int std::tr1::detail::decltype' ../stlport/type_traits:942: error: ISO C++ forbids declaration of 'decltype' with no type ../stlport/type_traits:942: error: ISO C++ forbids in-class initialization of non-const static member 'decltype' ../stlport/type_traits:942: error: template declaration of 'int std::tr1::detail::decltype' make: *** [obj/arm-eabi-gcc/so/dll_main.o] Error 1 Is there any include dir or configuration I´m missing? Thanks, Sergio

    Read the article

  • Regex problem in Java in code sample

    - by JaneNY
    I have job with regex in my expressions: example !(FA1_A.i & FA1_M.i) I have operators ! ( ) & | operands have names [a-zA-Z_]*.[a-zA-Z_] I wrote in Java to split on tokens, but it doesn't split on operators and operands If should be !, (, FA1_A.i, &, FA1_m.i, ) . Can anybody tell me what is wrong ? String stringOpеrator = "([!|&()])"; String stringOperand = "(([a-zA-Z_]*)\\.([a-zA-Z_]*))"; String reg=stringOpеrator+"|"+stringOperand; Pattern pattern = Pattern.compile(reg); Matcher m = pattern.matcher(expression); // System.out.println("func: " + function + " item: " + item); while (m.find()) { int a=m.start(); int b=m.end(); String test=expression.substring(m.start(), m.end()); String g=test; tokens.add(new Token(expression.substring(m.start() , m.end()))); //m = pattern.matcher(expression); }

    Read the article

  • Which languages support *recursive* function literals / anonymous functions?

    - by Hugh Allen
    It seems quite a few mainstream languages support function literals these days. They are also called anonymous functions, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, &printf doesn't count. EDIT to add: if you have a genuine function literal expression <exp>, you should be able to pass it to a function f(<exp>) or immediately apply it to an argument, ie. <exp>(5). I'm curious which languages let you write function literals which are recursive. Wikipedia's "anonymous recursion" article doesn't give any programming examples. Let's use the recursive factorial function as the example. Here are the ones I know: JavaScript / ECMAScript can do it with callee: function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}} it's easy in languages with letrec, eg Haskell (which calls it let): let fac x = if x<2 then 1 else fac (x-1) * x in fac and there are equivalents in Lisp and Scheme. Note that the binding of fac is local to the expression, so the whole expression is in fact an anonymous function. Are there any others?

    Read the article

  • Can a class inherit from LambdaExpression in .NET? Or is this not recommended?

    - by d.
    Consider the following code (C# 4.0): public class Foo : LambdaExpression { } This throws the following design-time error: Foo does not implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) There's absolutely no problem with public class Foo : Expression { } but, out of curiosity and for the sake of learning, I've searched in Google System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) and guess what: zero results returned (when was the last time you saw that?). Needless to say, I haven't found any documentation on this method anywhere else. As I said, one can easily inherit from Expression; on the other hand LambdaExpression, while not marked as sealed (Expression<TDelegate> inherits from it), seems to be designed to prevent inheriting from it. Is this actually the case? Does anyone out there know what this method is about? EDIT (1): More info based on the first answers - If you try to implement Accept, the editor (C# 2010 Express) automatically gives you the following stub: protected override Expression Accept(System.Linq.Expressions.ExpressionVisitor visitor) { return base.Accept(visitor); } But you still get the same error. If you try to use a parameter of type StackSpiller directly, the compiler throws a different error: System.Linq.Expressions.Compiler.StackSpiller is inaccessible due to its protection level. EDIT (2): Based on other answers, inheriting from LambdaExpression is not possible so the question as to whether or not it is recommended becomes irrelevant. I wonder if, in cases like this, the error message should be Foo cannot implement inherited abstract member System.Linq.Expressions.LambdaExpression.Accept(System.Linq.Expressions.Compiler.StackSpiller) because [reasons go here]; the current error message (as some answers prove) seems to tell me that all I need to do is implement Accept (which I can't do).

    Read the article

  • C pointers and addresses

    - by yCalleecharan
    Hi, I always thought that *&p = p = &*p in C. I tried this code: #include <stdio.h> #include <stdlib.h> char a[] = "programming"; char *ap = &a[4]; int main(void) { printf("%x %x %x\n", ap, &*(ap), *&(ap)); /* line 13 */ printf("%x %x %x\n\n", ap+1, &*(ap+1), *&(ap+1)); /* line 14 */ } The first printf line (line 13) gives me the addresses: 40b0a8 40b0a8 40b0a8 which are the same as expected. But when I added the second printf line, Borland complains: "first.c": E2027 Must take address of a memory location in function main at line 14 I was expecting to get: 40b0a9 40b0a9 40b0a9. It seems that the expression *&(ap+1) on line 14 is the culprit here. I thought all three pointer expressions on line 14 are equivalent. Why am I thinking wrong? A second related question: The line char *ap = a; points to the first element of array a. I used char *ap = &a[4]; to point to the 5th element of array a. Is the expression char *ap = a; same as the expression char *ap = &a[0]; Is the last expression only more verbose than the previous one? Thanks a lot...

    Read the article

  • Creating a property setter delegate

    - by Jim C
    I have created methods for converting a property lambda to a delegate: public static Delegate MakeGetter<T>(Expression<Func<T>> propertyLambda) { var result = Expression.Lambda(propertyLambda.Body).Compile(); return result; } public static Delegate MakeSetter<T>(Expression<Action<T>> propertyLambda) { var result = Expression.Lambda(propertyLambda.Body).Compile(); return result; } These work: Delegate getter = MakeGetter(() => SomeClass.SomeProperty); object o = getter.DynamicInvoke(); Delegate getter = MakeGetter(() => someObject.SomeProperty); object o = getter.DynamicInvoke(); but these won't compile: Delegate setter = MakeSetter(() => SomeClass.SomeProperty); setter.DynamicInvoke(new object[]{propValue}); Delegate setter = MakeSetter(() => someObject.SomeProperty); setter.DynamicInvoke(new object[]{propValue}); The MakeSetter lines fail with "The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly." Is what I'm trying to do possible? Thanks in advance.

    Read the article

  • Why this Either-monad code does not type check?

    - by pf_miles
    instance Monad (Either a) where return = Left fail = Right Left x >>= f = f x Right x >>= _ = Right x this code frag in 'baby.hs' caused the horrible compilation error: Prelude> :l baby [1 of 1] Compiling Main ( baby.hs, interpreted ) baby.hs:2:18: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `return' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the expression: Left In the definition of `return': return = Left In the instance declaration for `Monad (Either a)' baby.hs:3:16: Couldn't match expected type `[Char]' against inferred type `a1' `a1' is a rigid type variable bound by the type signature for `fail' at <no location info> Expected type: String Inferred type: a1 In the expression: Right In the definition of `fail': fail = Right baby.hs:4:26: Couldn't match expected type `a1' against inferred type `a' `a1' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `f', namely `x' In the expression: f x In the definition of `>>=': Left x >>= f = f x baby.hs:5:31: Couldn't match expected type `b' against inferred type `a' `b' is a rigid type variable bound by the type signature for `>>=' at <no location info> `a' is a rigid type variable bound by the instance declaration at baby.hs:1:23 In the first argument of `Right', namely `x' In the expression: Right x In the definition of `>>=': Right x >>= _ = Right x Failed, modules loaded: none. why this happen? and how could I make this code compile ? thanks for any help~

    Read the article

  • Using XPath on String in Android (JAVA)

    - by Rav
    I am looking for some examples of using xpath in Android? Or if anyone can share their experiences. I have been struggeling to make tail or head of this problem :-( I have a string that contains a standard xml file. I believe I need to convert that into an xml document. I have found this code which I think will do the trick: public static Document stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(xmlSource))); } Next steps Assuming the code above is OK, I need to apply xpath to get values from cat: "/animal/mammal/feline/cat" I look at the dev doc here: http://developer.android.com/reference/javax/xml/xpath/XPath.html and also look online, but I am not sure where to start! I have tried to use the following code: XPathFactory xPathFactory = XPathFactory.newInstance(); // To get an instance of the XPathFactory object itself. XPath xPath = xPathFactory.newXPath(); // Create an instance of XPath from the factory class. String expression = "SomeXPathExpression"; XPathExpression xPathExpression = xPath.compile(expression); // Compile the expression to get a XPathExpression object. Object result = xPathExpression.evaluate(xmlDocument); // Evaluate the expression against the XML Document to get the result. But I get "Cannot be resolved". Eclipse doesn't seem to be able to fix this import. I tried manually entering: javax.xml.xpath.XPath But this did not work. Does anyone know any good source code that I can utilise, for Android platform? 1.5

    Read the article

  • Multiple generic parameters on a html helper extension method

    - by WestDiscGolf
    What I'm trying to do is create an extension method for the HtmlHelper to create a specific output and associated details like TextBoxFor<. What I want to do is specify the property from the model class as per TextBoxFor<, then an associated controller action and other parameters. So far the signature of the method looks like: public static MvcHtmlString Create<TModel, TProperty, TController>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Expression<Action<TController>> action, object htmlAttributes) where TController : Controller where TModel : class The issue occurs when I go to call it. In my view if I call it as per the TextBoxFor without specifying the Model type I am able to specify the lambda expression to set the property which it's for, but when I go to specify the action I am unable to. However, when I specify the controller type Html.Create<HomeController>( ... ) I am unable to specify the model property that the control is to be created for. I want to be able to call it like <%= Html.Create(x => x.Title, controller => controller.action, null) %> I've been hitting my head for a few hours now on this issue over the past day, can anyone point me in the right direction?

    Read the article

  • Type errors when using same name

    - by lykimq
    I have 3 files: 1) cpf0.ml type string = char list type url = string type var = string type name = string type symbol = | Symbol_name of name 2) problem.ml: type symbol = | Ident of string 3) test.ml open Problem;; open Cpf0;; let symbol b = function | Symbol_name n -> Ident n When I combine test.ml: ocamlc -c test.ml. I received an error: This expression has type Cpf0.name = char list but an expression was expected of type string Could you please help me to correct it? Thank you very much EDIT: Thank you for your answer. I want to explain more about these 3 files: Because I am working with extraction in Coq to Ocaml type: cpf0.ml is generated from cpf.v : Require Import String. Definition string := string. Definition name := string. Inductive symbol := | Symbol_name : name -> symbol. The code extraction.v: Set Extraction Optimize. Extraction Language Ocaml. Require ExtrOcamlBasic ExtrOcamlString. Extraction Blacklist cpf list. where ExtrOcamlString I opened: open Cpf0;; in problem.ml, and I got a new problem because in problem.ml they have another definition for type string This expression has type Cpf0.string = char list but an expression was expected of type Util.StrSet.elt = string Here is a definition in util.ml defined type string: module Str = struct type t = string end;; module StrOrd = Ord.Make (Str);; module StrSet = Set.Make (StrOrd);; module StrMap = Map.Make (StrOrd);; let set_add_chk x s = if StrSet.mem x s then failwith (x ^ " already declared") else StrSet.add x s;; I was trying to change t = string to t = char list, but if I do that I have to change a lot of function it depend on (for example: set_add_chk above). Could you please give me a good idea? how I would do in this case.

    Read the article

< Previous Page | 69 70 71 72 73 74 75 76 77 78 79 80  | Next Page >