Search Results

Search found 4243 results on 170 pages for 'bool'.

Page 16/170 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • How can I handle events within my custom control?

    - by highone
    I am not looking to create new events. I need to create a canvas control that optionally fades in or out depending on whether or not the mouse is over it. The code below probably explains what I want to do better than I can. private Storyboard fadeInStoryboard; private Storyboard fadeOutStoryboard; public FadingOptionPanel() { InitializeComponent(); } public static readonly DependencyProperty FadeEnabledProperty = DependencyProperty.Register("IsFadeEnabled", typeof(bool), typeof(FadingOptionPanel), new FrameworkPropertyMetadata(true, OnFadeEnabledPropertyChanged, OnCoerceFadeEnabledProperty)); public bool IsFadeEnabled { get { return (bool)GetValue(FadeEnabledProperty); } set { SetValue(FadeEnabledProperty, value); } } private static void OnFadeEnabledPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { } private static object OnCoerceFadeEnabledProperty(DependencyObject sender, object data) { if (data.GetType() != typeof(bool)) { data = true; } return data; } private void FadingOptionPanel_MouseEnter(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeInStoryboard.Begin(this); } } private void FadingOptionPanel_MouseLeave(object sender, MouseEventArgs e) { if (IsFadeEnabled) { fadeOutStoryboard.Begin(this); } } private void FadingOptionsPanel_Loaded(object sender, RoutedEventArgs e) { //Initialize Fade In Animation DoubleAnimation fadeInDoubleAnimation = new DoubleAnimation(); fadeInDoubleAnimation.From = 0; fadeInDoubleAnimation.To = 1; fadeInDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.5)); fadeInStoryboard = new Storyboard(); fadeInStoryboard.Children.Add(fadeInDoubleAnimation); Storyboard.SetTargetName(fadeInDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeInDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); //Initialize Fade Out Animation DoubleAnimation fadeOutDoubleAnimation = new DoubleAnimation(); fadeOutDoubleAnimation.From = 1; fadeOutDoubleAnimation.To = 0; fadeOutDoubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(.2)); fadeOutStoryboard = new Storyboard(); fadeOutStoryboard.Children.Add(fadeOutDoubleAnimation); Storyboard.SetTargetName(fadeOutDoubleAnimation, this.Name); Storyboard.SetTargetProperty(fadeOutDoubleAnimation, new PropertyPath(Canvas.OpacityProperty)); } I originally was using this code inside a usercontrol instead of a custom control before I found out that usercontrols don't support content.

    Read the article

  • Show WPF tooltip on disabled item only

    - by DT
    Just wondering if it is possible to show a WPF on a disabled item ONLY (and not when the item is enabled). I would like to give the user a tooltip explaining why an item is currently disabled. I have an IValueConverter to invert the boolean IsEnabled property binding. But it doesn't seem to work in this situation. The tooltip is show both when the item is enabled and disabled. So is is possible to bind a tooltip.IsEnabled property exclusively to an item's own !IsEnabled? Pretty straightforward question I guess, but code example here anyway: public class BoolToOppositeBoolConverter : IValueConverter { #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType != typeof(bool)) throw new InvalidOperationException("The target must be a boolean"); return !(bool)value; } #endregion } And the binding: <TabItem Header="Tab 2" Name="tabItem2" ToolTip="Not enabled in this situation." ToolTipService.ShowOnDisabled="True" ToolTipService.IsEnabled="{Binding Path=IsEnabled, ElementName=tabItem2, Converter={StaticResource oppositeConverter}}"> <Label Content="Item content goes here" /> </TabItem> Thanks folks.

    Read the article

  • c# Most efficient way to combine two objects

    - by Dested
    I have two objects that can be represented as an int, float, bool, or string. I need to perform an addition on these two objects with the results being the same thing c# would produce as a result. For instance 1+"Foo" would equal the string "1Foo", 2+2.5 would equal the float 5.5, and 3+3 would equal the int 6 . Currently I am using the code below but it seems like incredible overkill. Can anyone simplify or point me to some way to do this efficiently? private object Combine(object o, object o1) { float left = 0; float right = 0; bool isInt = false; string l = null; string r = null; if (o is int) { left = (int)o; isInt = true; } else if (o is float) { left = (float)o; } else if (o is bool) { l = o.ToString(); } else { l = (string)o; } if (o1 is int) { right = (int)o1; } else if (o is float) { right = (float)o1; isInt = false; } else if (o1 is bool) { r = o1.ToString(); isInt = false; } else { r = (string)o1; isInt = false; } object rr; if (l == null) { if (r == null) { rr = left + right; } else { rr = left + r; } } else { if (r == null) { rr = l + right; } else { rr = l + r; } } if (isInt) { return Convert.ToInt32(rr); } return rr; }

    Read the article

  • Tokyo Cabinet Tuning Parameters

    - by user235478
    Hello, I have been trying to find a better Tokyo Cabinet (or Tokyo Tyrant) configuration for my application, but I don't know exactly how. I know what some parameters mean but I want to have a fine tuning control, so I need to know the impact of each one. The Tokyo documentation is really good but not at this point. Does any one can help me? Thanks. TCHDB -> *bool tchdbtune(TCHDB *hdb, int64_t bnum, int8_t apow, int8_t fpow, uint8_t opts);* How do I use: bnum, apow and fpow? TCBDB -> *bool tcbdbtune(TCBDB *bdb, int32_t lmemb, int32_t nmemb, int64_t bnum, int8_t apow, int8_t fpow, uint8_t opts);* How do I use: lmemb, nmemb, bnum, apow and fpow? TCFDB -> *bool tcfdbtune(TCFDB *fdb, int32_t width, int64_t limsiz);* How do I use: width and limsiz? Note: I am only putting this to get all types of database in the topic, this one is really simple. TCTDB -> *bool tctdbtune(TCTDB *tdb, int64_t bnum, int8_t apow, int8_t fpow, uint8_t opts);* How do I use: bnum, apow and fpow?

    Read the article

  • linq-to-sql combine child expressions

    - by VictorS
    I need to create and combine several expressions for child entity into one to use it on "Any" operator of a parent. Code now looks like this: Expresion<Child, bool> startDateExpression = t => t.start_date >= startDate; Expression<Child, bool> endDateExpression = t => t.end_date <= endDate; .... ParameterExpression param = startDateExpression.Parameters[0]; Expression<Func<T, bool>> Combined = Expression.Lambda<Func<Child, bool>>( Expression.AndAlso(startDateExpression.Body, startDateExpression.Body), param); //but now I am trying to use combined expression on parent //this line fails just to give an idea on what I am trying to do: //filter type is IQueryable<Parent>; var filter = filter.Where(p =>p.Children.Any(Combined)); How can I do that? Is there better(more elegant way way of doing it?

    Read the article

  • Most efficient way to combine two objects in C#

    - by Dested
    I have two objects that can be represented as an int, float, bool, or string. I need to perform an addition on these two objects with the results being the same thing c# would produce as a result. For instance 1+"Foo" would equal the string "1Foo", 2+2.5 would equal the float 5.5, and 3+3 would equal the int 6 . Currently I am using the code below but it seems like incredible overkill. Can anyone simplify or point me to some way to do this efficiently? private object Combine(object o, object o1) { float left = 0; float right = 0; bool isInt = false; string l = null; string r = null; if (o is int) { left = (int)o; isInt = true; } else if (o is float) { left = (float)o; } else if (o is bool) { l = o.ToString(); } else { l = (string)o; } if (o1 is int) { right = (int)o1; } else if (o is float) { right = (float)o1; isInt = false; } else if (o1 is bool) { r = o1.ToString(); isInt = false; } else { r = (string)o1; isInt = false; } object rr; if (l == null) { if (r == null) { rr = left + right; } else { rr = left + r; } } else { if (r == null) { rr = l + right; } else { rr = l + r; } } if (isInt) { return Convert.ToInt32(rr); } return rr; }

    Read the article

  • How do I get a window caption?

    - by P.Brian.Mackey
    I would like to get a Window Caption as given by spy++ (highlighted in red) I have code to do this (or so I thought)...but it seems to work pretty awful....in some cases 1% of the time... public delegate bool EnumDelegate(IntPtr hWnd, int lParam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool IsWindowVisible(IntPtr hWnd); [DllImport("user32.dll", EntryPoint = "GetWindowText", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] static extern int GetWindowText(IntPtr hWnd, StringBuilder lpWindowText, int nMaxCount); [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam); static List<NativeWindow> collection = new List<NativeWindow>(); public static NativeWindow GetAppNativeMainWindow() { GetNativeWindowHelper.EnumDelegate filter = delegate(IntPtr hWnd, int lParam) { StringBuilder strbTitle = new StringBuilder(255); int nLength = GetNativeWindowHelper.GetWindowText(hWnd, strbTitle, strbTitle.Capacity + 1); string strTitle = strbTitle.ToString(); if (!string.IsNullOrEmpty(strTitle)) { if (strTitle.ToLower().StartsWith("window title | my application")) { NativeWindow window = new NativeWindow(); window.AssignHandle(hWnd); collection.Add(window); return false;//stop enumerating } } return true;//continue enumerating }; GetNativeWindowHelper.EnumDesktopWindows(IntPtr.Zero, filter, IntPtr.Zero); if (collection.Count != 1) { //log error ReleaseWindow(); return null; } else return collection[0]; } public static void ReleaseWindow() { foreach (var item in collection) { item.ReleaseHandle(); } }

    Read the article

  • slot function not getting called

    - by chappar
    I am learning QT and trying out some examples. I am trying to make a dialog that disappears a label when a button is pressed and makes it appear when the same button is pressed again. Below is the code. #include <QApplication> #include <QPushButton> #include <QLabel> #include <QDialog> #include <QObject> #include <QHBoxLayout> int main(int argc, char ** argv) { QApplication app(argc, argv); QDialog *dialog = new QDialog; QPushButton *testButton = new QPushButton(QObject::tr("test")); QLabel * testLabel = new QLabel (QObject::tr("test")); QHBoxLayout * layout = new QHBoxLayout; layout->addWidget(testButton); layout->addWidget(testLabel); QObject::connect(testButton, SIGNAL(toggled(bool)), testLabel, SLOT(setVisible(bool))); dialog->setLayout(layout); dialog->show(); return app.exec(); } It is not working. Whenever i press the test button nothing happens. But if i change the signal slot connections as QObject::connect(testButton, SIGNAL(clicked(bool)), testLabel, SLOT(setVisible(bool))); it makes the label disappear. So, why it is not working with signal "toggled". What i am guessing is, it is not able to find that signal. Can you guys throw some light?

    Read the article

  • Is there a more efficient way to run enum values through a switch-case statement in C# than this?

    - by C Patton
    I was wondering if there was a more efficient (efficient as in simpler/cleaner code) way of making a case statement like the one below... I have a dictionary. Its key type is an Enum and its value type is a bool. If the boolean is true, I want to change the color of a label on a form. The variable names were changed for the example. Dictionary<String, CustomType> testDict = new Dictionary<String, CustomType>(); //populate testDict here... Dictionary<MyEnum, bool> enumInfo = testDict[someString].GetEnumInfo(); //GetEnumInfo is a function that iterates through a Dictionary<String, CustomType> //and returns a Dictionary<MyEnum, bool> foreach (KeyValuePair<MyEnum, bool> kvp in enumInfo) { switch (kvp.Key) { case MyEnum.Enum1: if (someDictionary[kvp.Key] == true) { Label1.ForeColor = Color.LimeGreen; } else { Label1.ForeColor = Color.Red; } break; case MyEnum.Enum2: if (someDictionary[kvp.Key] == true) { Label2.ForeColor = Color.LimeGreen; } else { Label2.ForeColor = Color.Red; } break; } } So far, MyEnum has 8 different values.. which means I have 8 different case statements.. I know there must be an easier way to do this, I just can't conceptualize it in my head. If anyone could help, I'd greatly appreciate it. I love C# and I learn new things every day.. I absorb it like a sponge :) -CP

    Read the article

  • Custom types as key for a map - C++

    - by Appu
    I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key. struct Foo { Foo(std::string s) : foo_value(s){} bool operator<(const Foo& foo1) { return foo_value < foo1.foo_value; } bool operator>(const Foo& foo1) { return foo_value > foo1.foo_value; } std::string foo_value; }; When used with std::map, I am getting the following error. error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const Foo' (or there is no acceptable conversion) c:\program files\microsoft visual studio 8\vc\include\functional 143 If I change the struct like the below, everything worked. struct Foo { Foo(std::string s) : foo_value(s) {} friend bool operator<(const Foo& foo,const Foo& foo1) { return foo.foo_value < foo1.foo_value; } friend bool operator>(const Foo& foo,const Foo& foo1) { return foo.foo_value > foo1.foo_value; } std::string foo_value; }; Nothing changed except making the operator overloads as friend. I am wondering why my first code is not working? Any thoughts?

    Read the article

  • How to detect whether there is a specific member variable in class?

    - by Kirill V. Lyadvinsky
    For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code: template<int> struct TT {typedef int type;}; template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; } template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; } struct P1 {int x; }; struct P2 {float X; }; // it also could be struct P3 {unknown_type X; }; int main() { P1 p1 = {1}; P2 p2 = {1}; Check_x(p1); // must return true Check_x(p2); // must return false return 0; } But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template: template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; } template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; } But it does not compile in GNU C++. Is there universal solution? UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.

    Read the article

  • function objects versus function pointers

    - by kumar_m_kiran
    Hi All, I have two questions related to function objects and function pointers, Question : 1 When I read the different uses sort algorithm of STL, I see that the third parameter can be a function objects, below is an example class State { public: //... int population() const; float aveTempF() const; //... }; struct PopLess : public std::binary_function<State,State,bool> { bool operator ()( const State &a, const State &b ) const { return popLess( a, b ); } }; sort( union, union+50, PopLess() ); Question : Now, How does the statement, sort(union, union+50,PopLess()) work? PopLess() must be resolved into something like PopLess tempObject.operator() which would be same as executing the operator () function on a temporary object. I see this as, passing the return value of overloaded operation i.e bool (as in my example) to sort algorithm. So then, How does sort function resolve the third parameter in this case? Question : 2 Question Do we derive any particular advantage of using function objects versus function pointer? If we use below function pointer will it derive any disavantage? inline bool popLess( const State &a, const State &b ) { return a.population() < b.population(); } std::sort( union, union+50, popLess ); // sort by population PS : Both the above references(including example) are from book "C++ Common Knowledge: Essential Intermediate Programming" by "Stephen C. Dewhurst". I was unable to decode the topic content, thus have posted for help. Thanks in advance for your help.

    Read the article

  • Passing filtering functions to Where() in LINQ-to-SQL

    - by Daniel
    I'm trying to write a set of filtering functions that can be chained together to progressively filter a data set. What's tricky about this is that I want to be able to define the filters in a different context from that in which they'll be used. I've gotten as far as being able to pass a very basic function to the Where() clause in a LINQ statement: filters file: Func<item, bool> returnTrue = (i) => true; repository file: public IQueryable<item> getItems() { return DataContext.Items.Where(returnTrue); } This works. However, as soon as I try to use more complicated logic, the trouble begins: filters file: Func<item, bool> isAssignedToUser = (i) => i.assignedUserId == userId; repository file: public IQueryable<item> getItemsAssignedToUser(int userId) { return DataContext.Items.Where(isAssignedToUser); } This won't even build because userId isn't in the same scope as isAssignedToUser(). I've also tried declaring a function that takes the userId as a parameter: Func<item, int, bool> isAssignedToUser = (i, userId) => i.assignedUserId == userId; The problem with this is that it doesn't fit the function signature that Where() is expecting: Func<item, bool> There must be a way to do this, but I'm at a loss for how. I don't feel like I'm explaining this very well, but hopefully you get the gist. Thanks, Daniel

    Read the article

  • How to use the LINQ where expression?

    - by NullReference
    I'm implementing the service \ repository pattern in a new project. I've got a base interface that looks like this. Everything works great until I need to use the GetMany method. I'm just not sure how to pass a LINQ expression into the GetMany method. For example how would I simply sort a list of objects of type name? nameRepository.GetMany( ? ) public interface IRepository<T> where T : class { void Add(T entity); void Update(T entity); void Delete(T entity); void Delete(Expression<Func<T, bool>> where); T GetById(long Id); T GetById(string Id); T Get(Expression<Func<T, bool>> where); IEnumerable<T> GetAll(); IEnumerable<T> GetMany(Expression<Func<T, bool>> where); } public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where) { return dbset.Where(where).ToList(); }

    Read the article

  • What makes this "declarator invalid"? C++

    - by nieldw
    I have Vertex template in vertex.h. From my graph.h: 20 template<class edgeDecor, class vertexDecor, bool dir> 21 class Vertex; which I use in my Graph template. I've used the Vertex template successfully throughout my Graph, return pointers to Vertices, etc. Now for the first time I am trying to declare and instantiate a Vertex object, and gcc is telling me that my 'declarator' is 'invalid'. How can this be? 81 template<class edgeDecor, class vertexDecor, bool dir> 82 Graph<edgeDecor,int,dir> Graph<edgeDecor,vertexDecor,dir>::Dijkstra(vertex s, bool print = false) const 83 { 84 /* Construct new Graph with apropriate decorators */ 85 Graph<edgeDecor,int,dir> span = new Graph<edgeDecor,int,dir>(); 86 span.E.reserve(this->E.size()); 87 88 typename Vertex<edgeDecor,int,dir> v = new Vertex(INT_MAX); 89 span.V = new vector<Vertex<edgeDecor,int,dir> >(this->V.size,v); 90 }; And gcc is saying: graph.h: In member function ‘Graph<edgeDecor, int, dir> Graph<edgeDecor, vertexDecor, dir>::Dijkstra(Vertex<edgeDecor, vertexDecor, dir>, bool) const’: graph.h:88: error: invalid declarator before ‘v’ graph.h:89: error: ‘v’ was not declared in this scope I know this is probably another noob question, but I'll appreciate any help.

    Read the article

  • Are function-local typedefs visible inside C++0x lambdas?

    - by GMan - Save the Unicorns
    I've run into a strange problem. The following simplified code reproduces the problem in MSVC 2010 Beta 2: template <typename T> struct dummy { static T foo(void) { return T(); } }; int main(void) { typedef dummy<bool> dummy_type; auto x = [](void){ bool b = dummy_type::foo(); }; // auto x = [](void){ bool b = dummy<bool>::foo(); }; // works } The typedef I created locally in the function doesn't seem to be visible in the lambda. If I replace the typedef with the actual type, it works as expected. Here are some other test cases: // crashes the compiler, credit to Tarydon int main(void) { struct dummy {}; auto x = [](void){ dummy d; }; } // works as expected int main(void) { typedef int integer; auto x = [](void){ integer i = 0; }; } I don't have g++ 4.5 available to test it, right now. Is this some strange rule in C++0x, or just a bug in the compiler? From the results above, I'm leaning towards bug. Though the crash is definitely a bug. For now, I have filed two bug reports. All code snippets above should compile. The error has to do with using the scope resolution on locally defined scopes. (Spotted by dvide.) And the crash bug has to do with... who knows. :) Update According to the bug reports, they have both been fixed for the next release of Visual Studio 2010.

    Read the article

  • MySQL - Structure for Permissions to Objects

    - by Kerry
    What would be an ideal structure for users permissions of objects. I've seen many related posts for general permissions, or what sections a user can access, which consists of a users, userGroups and userGroupRelations or something of that nature. In my system there are many different objects that can get created, and each one has to be able to be turned on or off. For instance, take a password manager that has groups and sub groups. Group 1 Group 2 Group 3 Group 4 Group 5 Group 6 Group 7 Group 8 Group 9 Group 10 Each group can contain a set of passwords. A user can be given read, write, edit and delete permissions to any group. More groups can get created at any point in time. If someone has permission to a group, I should be able to make him have permissions to all sub groups OR restrict it to just that group. My current thought is to have a users table, and then a permissions table with columns like: permission_id (int) PRIMARY_KEY user_id (int) INDEX object_id (int) INDEX type (varchar) INDEX read (bool) write (bool) edit (bool) delete (bool) This has worked in the past, but the new system I'm building needs to be able to scale rapidly, and I am unsure if this is the best structure. It also makes the idea of having someone with all subgroup permissions of a group more difficult. So, as a question, should I use the above structure? Or can someone point me in the direction of a better one?

    Read the article

  • linq delegate function checking from objects

    - by Philip
    I am trying to find the list of objects which can be replaced. Class Letter{ int ID; string Name; string AdvCode; int isDeleted; } Class Replacers{ int ID; string MainAdvCode; string ReplacesAdvCode; } example data: Replacers 0 455 400 1 955 400 2 955 455 such that if a Letter has and Advcode of 455 and another has a code of 400 the 400 gets marked for deletion. And then if another Letter has a 955 then the 455 gets marked for deletion and the 400 (which is already marked) is marked for deletion. The problem is with my current code the 400 and 455 is marking itself for deletion?!?!? Public class Main{ List<Letter> Letters; List<Replacers> replaces; //select the ones to replace the replacements aka the little guys //check if the replacements replacer exists if yes mark deleted var filterMethodReplacements = new Func<Letter, bool>(IsAdvInReplacements);//Working var filterMethodReplacers = new Func<Letter, bool>(IsAdvInReplacers);//NOT WORKING???? var resReplacements=letters.Where(filterMethodReplacements);//working foreach (Letter letter in resReplacements) { //select the Replacers aka the ones that contain the little guys var resReplacers = letters.Where(filterMethodReplacers); if (resReplacers != null) letter.isDeleted = 1; } } } private bool IsAdvInReplacements(Letter letter) { return (from a in Replacables where a.ReplaceAdvCode == letter.AdvCode select a).Any(); } private bool IsAdvInReplacers(Letter letter) { //?????????????????????????????? return (from a in Replacables where a.MainAdvCode == letter.AdvCode select a).Any(); } }

    Read the article

  • Type casting in C++ by detecting the current 'this' object type

    - by Elroy
    My question is related to RTTI in C++ where I'm trying to check if an object belongs to the type hierarchy of another object. The BelongsTo() method checks this. I tried using typeid, but it throws an error and I'm not sure about any other way how I can find the target type to convert to at runtime. #include <iostream> #include <typeinfo> class X { public: // Checks if the input type belongs to the type heirarchy of input object type bool BelongsTo(X* p_a) { // I'm trying to check if the current (this) type belongs to the same type // hierarchy as the input type return dynamic_cast<typeid(*p_a)*>(this) != NULL; // error C2059: syntax error 'typeid' } }; class A : public X { }; class B : public A { }; class C : public A { }; int main() { X* a = new A(); X* b = new B(); X* c = new C(); bool test1 = b->BelongsTo(a); // should return true bool test2 = b->BelongsTo(c); // should return false bool test3 = c->BelongsTo(a); // should return true } Making the method virtual and letting derived classes do it seems like a bad idea as I have a lot of classes in the same type hierarchy. Or does anybody know of any other/better way to the do the same thing? Please suggest.

    Read the article

  • Can C++ do something like an ML case expression?

    - by Nathan Andrew Mullenax
    So, I've run into this sort of thing a few times in C++ where I'd really like to write something like case (a,b,c,d) of (true, true, _, _ ) => expr | (false, true, _, false) => expr | ... But in C++, I invariably end up with something like this: bool c11 = color1.count(e.first)>0; bool c21 = color2.count(e.first)>0; bool c12 = color1.count(e.second)>0; bool c22 = color2.count(e.second)>0; // no vertex in this edge is colored // requeue if( !(c11||c21||c12||c22) ) { edges.push(e); } // endpoints already same color // failure condition else if( (c11&&c12)||(c21&&c22) ) { results.push_back("NOT BICOLORABLE."); return true; } // nothing to do: nodes are already // colored and different from one another else if( (c11&&c22)||(c21&&c12) ) { } // first is c1, second is not set else if( c11 && !(c12||c22) ) { color2.insert( e.second ); } // first is c2, second is not set else if( c21 && !(c12||c22) ) { color1.insert( e.second ); } // first is not set, second is c1 else if( !(c11||c21) && c12 ) { color2.insert( e.first ); } // first is not set, second is c2 else if( !(c11||c21) && c22 ) { color1.insert( e.first ); } else { std::cout << "Something went wrong.\n"; } I'm wondering if there's any way to clean all of those if's and else's up, as it seems especially error prone. It would be even better if it were possible to get the compiler complain like SML does when a case expression (or statement in C++) isn't exhaustive. I realize this question is a bit vague. Maybe, in sum, how would one represent an exhaustive truth table with an arbitrary number of variables in C++ succinctly? Thanks in advance.

    Read the article

  • How can I unit test my custom validation attribute

    - by MightyAtom
    I have a custom asp.net mvc class validation attribute. My question is how can I unit test it? It would be one thing to test that the class has the attribute but this would not actually test that the logic inside it. This is what I want to test. [Serializable] [EligabilityStudentDebtsAttribute(ErrorMessage = "You must answer yes or no to all questions")] public class Eligability { [BooleanRequiredToBeTrue(ErrorMessage = "You must agree to the statements listed")] public bool StatementAgree { get; set; } [Required(ErrorMessage = "Please choose an option")] public bool? Income { get; set; } .....removed for brevity } [AttributeUsage(AttributeTargets.Class)] public class EligabilityStudentDebtsAttribute : ValidationAttribute { // If AnyDebts is true then // StudentDebts must be true or false public override bool IsValid(object value) { Eligability elig = (Eligability)value; bool ok = true; if (elig.AnyDebts == true) { if (elig.StudentDebts == null) { ok = false; } } return ok; } } I have tried to write a test as follows but this does not work: [TestMethod] public void Eligability_model_StudentDebts_is_required_if_AnyDebts_is_true() { // Arrange var eligability = new Eligability(); var controller = new ApplicationController(); // Act controller.ModelState.Clear(); controller.ValidateModel(eligability); var actionResult = controller.Section2(eligability,null,string.Empty); // Assert Assert.IsInstanceOfType(actionResult, typeof(ViewResult)); Assert.AreEqual(string.Empty, ((ViewResult)actionResult).ViewName); Assert.AreEqual(eligability, ((ViewResult)actionResult).ViewData.Model); Assert.IsFalse(((ViewResult)actionResult).ViewData.ModelState.IsValid); } The ModelStateDictionary does not contain the key for this custom attribute. It only contains the attributes for the standard validation attributes. Why is this? What is the best way to test these custom attributes? Thanks

    Read the article

  • Google Analytics version 3 - How to apply it correctly?

    - by ephramd
    I've added google analytics to my app with the intention of obtaining information about the screens you and send custom events. I am obtained duplicate content ... Also I get different results: "com.package.app.MainScreen" - 300 views and "Main Screen" - 200 views I am interested to get only follow up with the custom name of the activity and not the package. And in any case, because both show different results? public class MainScreen extends Activity { private static final String GA_PROPERTY_ID = "UA-12345678-9"; private static final String SCREEN_LABEL = "Main Screen"; Tracker mTracker; EasyTracker easyTracker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_screen); mTracker = GoogleAnalytics.getInstance(this).getTracker(GA_PROPERTY_ID); mTracker.set(Fields.SCREEN_NAME, SCREEN_LABEL); // For Custom Name from activity mTracker.send(MapBuilder.createAppView().build()); easyTracker = EasyTracker.getInstance(this); // Analytics Events ... easyTracker.send(MapBuilder.createEvent("MainScreen", "Play", category.get(1), null).build()); //AnalyticsEvents ... } @Override public void onStart() { super.onStart(); EasyTracker.getInstance(this).activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance(this).activityStop(this); } } And analytics.xml: <?xml version="1.0" encoding="utf-8" ?> <resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes"> <!--Replace placeholder ID with your tracking ID--> <string name="ga_trackingId">UA-12345678-9</string> <!--Enable automatic activity tracking--> <bool name="ga_autoActivityTracking">true</bool> <!--Enable automatic exception tracking--> <bool name="ga_reportUncaughtExceptions">true</bool> </resources> Google Analytics Dev Guide

    Read the article

  • How to use accessors within the same class in Objective C?

    - by Azeworai
    Hi, I have a few properties defined in my header file like so @property (assign) bool connectivity_N; @property (assign) bool isConnected_N; In my implementation file I have an init and the synthesized properties like so @implementation Map @synthesize connectivity_N; @synthesize isConnected_N; a init to set the initial values like so -(id) init { if( (self=[super init]) ) { //initialise default properties self.connectivity_N=NO; self.isConnected_N=NO; } return self; } I'm running into an error that states Error: accessing unknown 'connectivity_N' class method. In this public method within the class +(bool) isConnectable:(directions) theDirection{ bool isTheDirectionConnectable= NO; switch (theDirection) { case north: isTheDirectionConnectable= self.connectivity_N; break; I'm not sure why is this so as I'm trying to grab the value of the property. According to the apple developer documentation "The default names for the getter and setter methods associated with a property are propertyName and setPropertyName: respectively—for example, given a property “foo”, the accessors would be foo and setFoo:" That has given me a clue that I've done something wrong here, I'm fairly new to objective C so would appreciate anyone who spends the time to explain this to me. Thanks!

    Read the article

  • LINQ to SQL: NOTing a prebuilt expression

    - by ck
    I'm building a library of functions for one of my core L2S classes, all of which return a bool to allow checking for certain situations. Example: Expression<Func<Account, bool>> IsSomethingX = a => a.AccountSupplementary != null && a.AccountSupplementary.SomethingXFlag != null && a.AccountSupplementary.SomethingXFlag.Value; Now to query where this is not true, I CAN'T do this: var myAccounts= context.Accounts .Where(!IsSomethingX); // does not compile However, using the syntax from the PredicateBuilder class, I've come up with this: public static IQueryable<T> WhereNot<T>(this IQueryable<T> items, Expression<Func<T, bool>> expr1) { var invokedExpr = Expression.Invoke(expr1, expr1.Parameters.Cast<Expression>()); return items.Where(Expression.Lambda<Func<T, bool>> (Expression.Not(invokedExpr), expr1.Parameters)); } var myAccounts= context.Accounts .WhereNot(IsSomethingX); // does compile which actually produces the correct SQL. Does this look like a good solution, and is there anything I need to be aware of that might cause me problems in future?

    Read the article

  • Member function overloading/template specialization issue

    - by Ferruccio
    I've been trying to call the overloaded table::scan_index(std::string, ...) member function without success. For the sake of clarity, I have stripped out all non-relevant code. I have a class called table which has an overloaded/templated member function named scan_index() in order to handle strings as a special case. class table : boost::noncopyable { public: template <typename T> void scan_index(T val, std::function<bool (uint recno, T val)> callback) { // code } void scan_index(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code } }; Then there is a hitlist class which has a number of templated member functions which call table::scan_index(T, ...) class hitlist { public: template <typename T> void eq(uint fieldno, T value) { table* index_table = db.get_index_table(fieldno); // code index_table->scan_index<T>(value, [&](uint recno, T n)->bool { // code }); } }; And, finally, the code which kicks it all off: hitlist hl; // code hl.eq<std::string>(*fieldno, p1.to_string()); The problem is that instead of calling table::scan_index(std::string, ...), it calls the templated version. I have tried using both overloading (as shown above) and a specialized function template (below), but nothing seems to work. After staring at this code for a few hours, I feel like I'm missing something obvious. Any ideas? template <> void scan_index<std::string>(std::string val, std::function<bool (uint recno, std::string val)> callback) { // code }

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >