• What Do You Need Help With? V6
    7,544 replies, posted
just for context: fucking around with codeacademy. [cpp]var quarter = function(number){ return number; }; if (quarter(12) % 3 === 0 ) { console.log("The statement is true"); } else { console.log("The statement is false"); } [/cpp] Prints out as "The statement is true", but the error I receive is "Hmm, it looks like your quarter function doesn't return -25 for -100." However, [cpp]var quarter = function(number){ return number / 4; }; if (quarter(12) % 3 === 0 ) { console.log("The statement is true"); } else { console.log("The statement is false"); } [/cpp] Prints out as a true statement, and doesn't receive an error. What does it mean that my quarter function isn't returning -25 for -100? I'm lost. Sorry if this is pretty basic, just trying to get a grasp, and the CodeAcademy Q&A doesn't really help out too much other than providing the correct code.
[QUOTE=Epiclulz762;41575577]Any recommendations, or personal experience, I can use for getting started with some low level code? I am trying to comprehend concurrent and forked processes, as issues of buffering and memory stacks is blowing my mind. With all these articles about parallel computing with clusters and what-not, I am looking for a way to get my foot into the door.[/QUOTE] What issues of buffering and memory stacks? You can get some parallelism with multi-threading (either directly threads or through a high-level interface like Actors), but for massively parallel computing you probably want to look at something like CUDA or OpenCL for low-level languages; I don't know about any high-level approaches for that (not that I have in-depth knowledge about parallel computing). I can't name any specific title, but I'm sure there's a bunch of books about that topic. [QUOTE=Slippery-Q;41575692]just for context: fucking around with codeacademy. [cpp]var quarter = function(number){ return number; }; if (quarter(12) % 3 === 0 ) { console.log("The statement is true"); } else { console.log("The statement is false"); } [/cpp] Prints out as "The statement is true", but the error I receive is "Hmm, it looks like your quarter function doesn't return -25 for -100." However, [cpp]var quarter = function(number){ return number / 4; }; if (quarter(12) % 3 === 0 ) { console.log("The statement is true"); } else { console.log("The statement is false"); } [/cpp] Prints out as a true statement, and doesn't receive an error. What does it mean that my quarter function isn't returning -25 for -100? I'm lost. Sorry if this is pretty basic, just trying to get a grasp, and the CodeAcademy Q&A doesn't really help out too much other than providing the correct code.[/QUOTE] It means precisely what it says. For -100 your (former) quarter function does not return -25, so quarter(-100) !== -25.
I have something which is basically an implementation of the observer pattern (no, not implementing it just for the hell of it). What C++ data type (smart pointer or whatever) should I use for storing the observers inside a list in the observable? Is there some nice solution where I pass maybe an std::function to the observable and get back some object which perhaps unregisters the observer on destruction? Otherwise I have to add something which unregisters it in the destructor of every observer. Last, is there some good solution to decrease code repetition for this in C++? They will all work the same, registering observers and then notifying all of them. But I want different method names (e.g. addComponentObserver and onComponentAdd, addCollisionObserver and onCollision) and maybe different type signatures. Maybe, I can do this with macros generating the relevant methods and members, but I really hate preprocessor macros.
std::list<std::reference_wrapper<Observer>>. I presume you don't want to free the Observer, right? If the Observer destructs without unregistering itself you'll have an invalid pointer in your hands, but from the next question I presume you want to ensure that. Otherwise you'd need to store std::weak_ptrs and require a std::shared_ptr for the observable to be present. If you want O(log n) removal of observers, consider std::set. And note that std::list is not very cache friendly. std::vector might have other limitations you don't want though. In Boost there's also boost::flat_set for a cache-friendly (but iterator-invalidating) version of std::set. You could return a "UnregisterObservable"-struct, which stores references to the observable and observer (or even directly the iterator if the container provides non-invalidating iterators (std::list does, std::set does, std::vector does not)) and does oberservable.unregisterObserver(observer);. You should use an "warn if return value ignored"-annotation if your compiler supports it, or perhaps not return it but pass it via reference to the registerObserver function. If you can pass function-pointers as template parameter, then you could have a [cpp]template<void (Observer::*callback)(Arg0, Arg1)> struct ObservableEvent { std::list<Observer*> observers; void Invoke() { std::for_each(observers.begin(), observers.end(), callback); } //might need std::bind(callback, std::placeholders::_1); };[/cpp] But since you talked about std::function I presume you wanted something less static anyways (no on* functions)?
[QUOTE=ZeekyHBomb;41576675]std::list<std::reference_wrapper<Observer>> could work. Otherwise probably just a raw pointer. I presume you don't want to free the Observer, right? If the Observer destructs without unregistering itself you'll have an invalid pointer in your hands, but from the next question I presume you want to ensure that. Otherwise you'd need to store std::weak_ptrs and require a std::shared_ptr for the observable to be present. If you want O(log n) removal of observers, consider std::set. And note that std::list is not very cache friendly. std::vector might have other limitations you don't want though. You could return a "UnregisterObservable"-struct, which stores references to the observable and observer (or even directly the iterator if the container provides non-invalidating iterators (std::list does, std::set don't know, std::vector does not)) and does oberservable.unregisterObserver(observer);. You should use an "warn if return value ignored"-annotation if your compiler supports it, or perhaps not return it but pass it via parameter to the observable. If you can pass function-pointers as template parameter, then you could have a [cpp]template<void (Observer::*callback)(Arg0, Arg1)> struct ObservableEvent { std::list<Observer*> observers; void Invoke() { std::for_each(observers.begin(), observers.end(), callback); } //might need std::bind(callback, std::placeholders::_1); };[/cpp] But since you talked about std::function I presume you wanted something less static anyways (no on* functions)?[/QUOTE] Sorry, list was a bad choice of word on my part. I meant it as a generic term for containers. I will definitely use reference wrapper, didn't know about that. Thanks! Wasn't really talking about "dynamic" functions, more comparing them with passing a pointer to an implementation of an interface with just one function. So I think function pointers will be fine. With that template, what if I want to pass arguments? What if I want different types of callbacks which take different types and numbers of arguments?
Okay. list, set and vector are the ones you should take a closer look at. And boost::flat_set if you like std::set. Whoops [cpp]template<typename Args...> void Invoke(Args... &&args) { auto boundCallback = std::bind(callback, std::placeholders::_1, std::forward<Args...>(args...)); std::for_each(observers.begin(), observers.end(), boundCallback); }[/cpp] I'm unsure how to extract a template parameter list of the arguments from a function pointer type.
[QUOTE=ZeekyHBomb;41576856]Okay. list, set and vector are the ones you should take a closer look at. And boost::flat_set if you like std::set. Whoops [cpp]template<typename Args...> void Invoke(Args... &&args) { auto boundCallback = std::bind(callback, std::placeholders::_1, std::forward<Args...>(args...)); std::for_each(observers.begin(), observers.end(), boundCallback); }[/cpp] I'm unsure how to extract a template parameter list of the arguments from a function pointer type.[/QUOTE] Cool, but doesn't this mean that all observers will have to inherit from observer?
Neither the standard library nor Boost seem to supply that. But you can easily write your own trait-type to provide that info [cpp]template<typename T> struct FunctionArgumentTypes; template<typename R, typename Args...> struct FunctionArgumentTypes<R(*)(Args...)> { using Types = Args; };[/cpp] And this should be useful to you: [cpp]template<typename T> struct MemberFunctionPointerMember; //ugly name :( template<typename R, typename M, typename Args...> struct MemberFunctionPointerMember<R(M::*)(Args...)> { using Type = M; };[/cpp] [editline]24th July 2013[/editline] [QUOTE=thf;41576925]Cool, but doesn't this mean that all observers will have to inherit from observer?[/QUOTE] See above :)
[QUOTE=ZeekyHBomb;41576939]And this should be useful to you: [cpp]template<typename T> struct MemberFunctionPointerMember; //ugly name :( template<typename R, typename M, typename Args...> struct MemberFunctionPointerMember<R(M::*)(Args...)> { using Type = M; };[/cpp] [editline]24th July 2013[/editline] See above :)[/QUOTE] Thanks, but how exactly do I apply that to use wih your first template?
Well, apart from the stuff not compiling in the slightest, you can't pass member function pointers as template parameters. You'll either have to store function-pointers (or a wrapper like std::function) and live with indirect calls or use macros.
[QUOTE=ZeekyHBomb;41577074]Well, apart from the stuff not compiling in the slightest, you can't pass member function pointers as template parameters. You'll either have to store function-pointers (or a wrapper like std::function) and live with indirect calls or use macros.[/QUOTE] Yeah the thing I was mostly concerned with was avoiding duplicating this code: [cpp] ... void registerCollisionObserver (...) { ... } ... std::vector <CollisionObserver> observers; ... void onCollision (...) { ... } [/cpp] And also the definition of that particular observer interface. Thanks for the tip about the RemoveObserver type and for mentioning reference wrapper. Providing me with clean solutions like I've gotten from you before :v:
It seems [url=http://stackoverflow.com/a/14175854/1874964]Stackoverflow was wrong[/url], at least this specific answer. [url=http://stackoverflow.com/a/11746632/1874964]This Stackoverflow answer[/url] provides the syntax to make it possible. Not without macros, but the macro-less version is also very close to the desired interface.
[QUOTE=ZeekyHBomb;41577437]It seems [url=http://stackoverflow.com/a/14175854/1874964]Stackoverflow was wrong[/url], at least this specific answer. [url=http://stackoverflow.com/a/11746632/1874964]This Stackoverflow answer[/url] provides the syntax to make it possible. Not without macros, but the macro-less version is also very close to the desired interface.[/QUOTE] Thanks! I just realized that I probably want to be able to have two methods on an observer interface. Can't think properly about templates at the moment, so I'll just "repeat the code two times for the moment but I promise I will look into, try to understand your solution and try to refactor my code, probably before I add another observable.
Ooooh! I just found Boost.Signals. Will use that! [editline]24th July 2013[/editline] Fuck, thought it would automerge...
[QUOTE=ZeekyHBomb;41575803]What issues of buffering and memory stacks? You can get some parallelism with multi-threading (either directly threads or through a high-level interface like Actors), but for massively parallel computing you probably want to look at something like CUDA or OpenCL for low-level languages; I don't know about any high-level approaches for that (not that I have in-depth knowledge about parallel computing). I can't name any specific title, but I'm sure there's a bunch of books about that topic.[/QUOTE] I am waiting for a good book, and thank you. Without owning multiple machines, is it possible to use one as a host and with virtual machines emulate a cluster?
[QUOTE=thf;41580096]Fuck, thought it would automerge...[/QUOTE] There's a two-hour limit.
In regards to buffering and stacks, writing and reading regarding forked processes is something I am trying to comprehend. I am trying to find a good entrance into low level computing, something I can understand and use as I learn. [editline]24th July 2013[/editline] Fuck, I thought [i]this[/i] would automerge...
Kind of a noob question, but can someone link me to a decent tutorial on XML Serialization in C#? All the ones I've found are just snippets of code with little to no explanation.
This is in sql. I have a date column in my table with the format '01-JAN-99'. I need to display the difference between the current date, using sysdate, and the dates in my table. But I have to display it by Years and Months. So if the date is 148 months ago, then it would display 12 Years and 4 Months.
how the heck do you make a gif that updates like this, in real time? [url]http://gifcountdown.com/america-los_angeles/1375282800/fdfdfd/474747/fdfdfd/333333/ffff00/true/counter.gif[/url] - removed because it makes page constantly load I want to display some security cameras like this on a webpage. Normally MJPEG would be fine but I'd like it to be supported on mobile, which (at least for my phone) MJPEG isn't. [editline]24th July 2013[/editline] this is kinda web dev but not really, whatever
You program an HTTP server which first serves the header of the GIF file, and then every second serves an updated frame.
Do you know what they're called or any tutorials / examples? [editline]24th July 2013[/editline] I feel like I'd be better off just saving a jpeg and updating it with JS or something.
[QUOTE=dvondrake;41587831]What's the best way in C++ to read the output of a child process? I've tried using popen, but that only gives me any output once the process is finished and exits. I've also tried [url=http://libexecstream.sourceforge.net/]libexecstream[/url], which seems like it [i]should[/i] collect output as the program is running, but it doesn't. Doing some reading, it seems to be related to the program's stdout being buffered somehow, but I can't figure out how to unbuffer it. Would prefer not to use Qt and just stick with simpler libraries if possible.[/QUOTE] popen works fine for me. Just make sure that the sender flushes stdout.
Maybe that's a difference between Linux and Windows popen implementation, but as soon as it would appear in a console it should appear via popen. Although the flush might happen implicitly and the condition for the implicit flush is that it's printing to a console. Try [url=http://en.cppreference.com/w/c/io/setvbuf]setvbuf[/url] then.
I'm currently learning Python as my first programming language through Code Academy. In this exercise I must combine 2 functions, one to check if a number is evenly divisible by 3 and then call another function to cube that number. I know how to do that except for checking if a number is evenly divisible by 3. I checked the hint for clues and it says 'You can check if a number n is evenly divisible by three by seeing if n % 3 == 0.' Now I've always been terrible at maths and I can't understand how that works. I've been looking around doing 9 % 3 but everywhere it gives me 0.27 whereas if I calculate it in Python it gives me 0. Can someone explain me some math 4 dummies, I can't find anything nor make sense out of this. I study history if that explains anything
[QUOTE=gnisasas;41591698]I'm currently learning Python as my first programming language through Code Academy. In this exercise I must combine 2 functions, one to check if a number is evenly divisible by 3 and then call another function to cube that number. I know how to do that except for checking if a number is evenly divisible by 3. I checked the hint for clues and it says 'You can check if a number n is evenly divisible by three by seeing if n % 3 == 0.' Now I've always been terrible at maths and I can't understand how that works. I've been looking around doing 9 % 3 but everywhere it gives me 0.27 whereas if I calculate it in Python it gives me 0. Can someone explain me some math 4 dummies, I can't find anything nor make sense out of this. I study history if that explains anything[/QUOTE] '%' is programming means 'modulus' which means 'remainder of a division'.
[QUOTE=Jookia;41591860]'%' is programming means 'modulus' which means 'remainder of a division'.[/QUOTE] oh that makes much more sense now I understand things much appreciated!
I am in quite a pickle, I must create a function which calculates the price of renting a car per days, with discounts depending on the number of days. Basically, each day is $40, less than 3 days no discount, equal or more than 3 days $20 discount, equal or more than 7 days $50 discount. Discounts are not accumulative. Now I've tried with this code: [CODE] def rental_car_cost(days): if days < 3: days * 40 elif days >= 3 and days not >= 7: # elif days >= 3: / elif days >= 3 and not >= 7 days * 40 - 20 elif days >= 7: days * 40 - 50[/CODE] It gives me this error: [CODE] File "python", line 17 elif days >= 3 and days not >= 7: ^ SyntaxError: invalid syntax [/CODE] What's making the code go tits? I try to figure things out on my own, but I've been on this one for a while. I also don't want to clutter this thread with silly beginner problems, so I'll ask as well, say you're in the same spot as me or having some trouble as well, how would you try to work out what's wrong on your own? I realise if it doesn't work, try something else. But I'd like to learn why this particular code doesn't work. Also is there some chat or something like that where I can talk with people or someone so I don't clutter up this thread?
days not >= 7 is not valid Python syntax. not days >= 7 is what you want. not is an unary operator, like a single - (as in "-x", not as in "y - x"). First thing you can do is stripping the erroneous part out and trying to fix that. Sometimes it is not obvious what exactly produces the error. Next thing, if you don't see what's wrong but it doesn't work as intended, try an internet search engine; input the error you get and maybe some keywords describing the context. Asking someone you know and programs is probably an obvious thing, asking in some community is also fine. Like this thread, you probably don't need to worry about cluttering up this thread. Some have made their own thread instead of posing their questions in here, either because they didn't know about this thread or because of similar worries. Most of them are probably fine in here. Understanding what the problem is is important when learning, just dropping it and trying something else won't help you much. I think there's a fpcoders-channel on IRC somewhere. Someone should know about it, but iirc last time it was mentioned it was said that it is rather silent in there.
Never touched Python, but what about "not (days >= 7)"? EDIT: l-l-l-late [img]http://i.imgur.com/ZcVyGj3.png[/img]
Sorry, you need to Log In to post a reply to this thread.