Search Results

Search found 331 results on 14 pages for 'mutable'.

Page 5/14 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • XNA 4.0 - What happens when the window is minimized?

    - by Conrad Clark
    Hello. I'm learning F#, and decided to try making simple XNA games for windows using F# (pure enthusiasm) , and got a window with some images showing up. Here's the code: (*Methods*) member self.DrawSprites() = _spriteBatch.Begin() for i = 0 to _list.Length-1 do let spentity = _list.List.ElementAt(i) _spriteBatch.Draw(spentity.ImageTexture,new Rectangle(100,100,(int)spentity.Width,(int)spentity.Height),Color.White) _spriteBatch.End() (*Overriding*) override self.Initialize() = ChangeGraphicsProfile() _graphicsDevice <- _graphics.GraphicsDevice _list.AddSprite(0,"NagatoYuki",992.0,990.0) base.Initialize() override self.LoadContent() = _spriteBatch <- new SpriteBatch(_graphicsDevice) base.LoadContent() override self.Draw(gameTime : GameTime) = base.Draw(gameTime) _graphics.GraphicsDevice.Clear(Color.CornflowerBlue) self.DrawSprites() And the AddSprite Method: member self.AddSprite(ID : int,imageTexture : string , width : float, height : float) = let texture = content.Load<Texture2D>(imageTexture) list <- list @ [new SpriteEntity(ID,list.Length, texture,Vector2.Zero,width,height)] The _list object has a ContentManager, here's the constructor: type SpriteList(_content : ContentManager byref) = let mutable content = _content let mutable list = [] But I can't minimize the window, since when it regains its focus, i get this error: ObjectDisposedException Cannot access a disposed object. Object name: 'GraphicsDevice'. What is happening?

    Read the article

  • F#: how to find Cartesian power

    - by Nike
    I have a problem with writing a Cartesian power function. I found many examples about calculating Cartesian Product, but no one about Cartesian power. For example, [1;2] raised to power 3 = [ [1;1;1] ; [1;1;2] ; [1;2;1] ; [1;2;2] ; [2;1;1] ; [2;1;2] ; [2;2;1]; [2;2;2] ] I use following code to calculate Cartesian Product: let Cprod U V = let mutable res = [] for u in U do for v in V do res <- res @ [[u;v]] res And trying to calculate Cartesian power. I use following code to calculate Cartesian Product: let Cpower U n = let mutable V = U for i=0 to n-1 do V <- Dprod U V V Visual Studio said: Error The resulting type would be infinite when unifying ''a' and ''a list'. I will thankful for any help and links.

    Read the article

  • Why "do...while" does not exist in F#

    - by Kev
    I cannot find "do...while..." I have to code like this: let bubbleSort a= let n = Array.length a let mutable swapped = true let mutable i = 0 while swapped do swapped <- false for j = 0 to n-i-2 do if a.[j] > a.[j+1] then let t = a.[j] a.[j] <- a.[j+1] a.[j+1] <- t swapped <- true i <- i+1 The code is bad without "do...while". Sadly, "break/continue" are also not available. Is F# not suitable for non-functional-programming?

    Read the article

  • RAII: Initializing data member in const method

    - by Thomas Matthews
    In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member. Example: Loading from a data base struct MyClass { int get_value(void) const; private: void load_from_database(void); // Loads the data member from database. int m_value; }; int MyClass :: get_value(void) const { static bool value_initialized(false); if (!value_initialized) { // The compiler complains about this call because // the method is non-const and called from a const // method. load_from_database(); } return m_value; } My primitive solution is to declare the data member as mutable. I would rather not do this, because it suggests that other methods can change the member. How would I cast the load_from_database() statement to get rid of the compiler errors?

    Read the article

  • Scala, make my loop more functional

    - by Pengin
    I'm trying to reduce the extent to which I write Scala (2.8) like Java. Here's a simplification of a problem I came across. Can you suggest improvements on my solutions that are "more functional"? Transform the map val inputMap = mutable.LinkedHashMap(1->'a',2->'a',3->'b',4->'z',5->'c') by discarding any entries with value 'z' and indexing the characters as they are encountered First try var outputMap = new mutable.HashMap[Char,Int]() var counter = 0 for(kvp <- inputMap){ val character = kvp._2 if(character !='z' && !outputMap.contains(character)){ outputMap += (character -> counter) counter += 1 } } Second try (not much better, but uses an immutable map and a 'foreach') var outputMap = new immutable.HashMap[Char,Int]() var counter = 0 inputMap.foreach{ case(number,character) => { if(character !='z' && !outputMap.contains(character)){ outputMap2 += (character -> counter) counter += 1 } } }

    Read the article

  • Generating Fibonacci series in F#

    - by photo_tom
    I'm just starting to learn F# using VS2010 and below is my first attempt at generating the Fibonacci series. What I'm trying to do is to build a list of all numbers less than 400. let fabList = let l = [1;2;] let mutable a = 1 let mutable b = 2 while l.Tail < 400 do let c = a + b l.Add(c) let a = b let b = c My first problem is that on the last statement, I'm getting an error message "Incomplete structured construct at or before this point in expression" on the last line. I don't understand what I'm doing wrong here. While this seems to be an obvious way to build the list in a fairly efficient way (from a c++/C# programmer), from what little I know of f#, this doesn't seem to feel to be the right way to do the program. Am I correct in this feeling?

    Read the article

  • iphone: Help with AudioToolbox Leak: Stack trace/code included here...

    - by editor guy
    Part of this app is a "Scream" button that plays random screams from cast members of a TV show. I have to bang on the app quite a while to see a memory leak in Instruments, but it's there, occasionally coming up (every 45 seconds to 2 minutes.) The leak is 3.50kb when it occurs. Haven't been able to crack it for several hours. Any help appreciated. Instruments says this is the offending code line: [appSoundPlayer play]; that's linked to from line 9 of the below stack trace: 0 libSystem.B.dylib malloc 1 libSystem.B.dylib pthread_create 2 AudioToolbox CAPThread::Start() 3 AudioToolbox GenericRunLoopThread::Start() 4 AudioToolbox AudioQueueNew(bool, AudioStreamBasicDescription const*, TCACallback const&, CACallbackTarget const&, unsigned long, OpaqueAudioQueue*) 5 AudioToolbox AudioQueueNewOutput 6 AVFoundation allocAudioQueue(AVAudioPlayer, AudioPlayerImpl*) 7 AVFoundation prepareToPlayQueue(AVAudioPlayer*, AudioPlayerImpl*) 8 AVFoundation -[AVAudioPlayer prepareToPlay] 9 Scream Queens -[ScreamViewController scream:] /Users/laptop2/Desktop/ScreamQueens Versions/ScreamQueens25/Scream Queens/Classes/../ScreamViewController.m:210 10 CoreFoundation -[NSObject performSelector:withObject:withObject:] 11 UIKit -[UIApplication sendAction:to:from:forEvent:] 12 UIKit -[UIApplication sendAction:toTarget:fromSender:forEvent:] 13 UIKit -[UIControl sendAction:to:forEvent:] 14 UIKit -[UIControl(Internal) _sendActionsForEvents:withEvent:] 15 UIKit -[UIControl touchesEnded:withEvent:] 16 UIKit -[UIWindow _sendTouchesForEvent:] 17 UIKit -[UIWindow sendEvent:] 18 UIKit -[UIApplication sendEvent:] 19 UIKit _UIApplicationHandleEvent 20 GraphicsServices PurpleEventCallback 21 CoreFoundation CFRunLoopRunSpecific 22 CoreFoundation CFRunLoopRunInMode 23 GraphicsServices GSEventRunModal 24 UIKit -[UIApplication _run] 25 UIKit UIApplicationMain 26 Scream Queens main /Users/laptop2/Desktop/ScreamQueens Versions/ScreamQueens25/Scream Queens/main.m:14 27 Scream Queens start Here's .h: #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> #import <AudioToolbox/AudioToolbox.h> #import <MessageUI/MessageUI.h> #import <MessageUI/MFMailComposeViewController.h> @interface ScreamViewController : UIViewController <UIApplicationDelegate, AVAudioPlayerDelegate, MFMailComposeViewControllerDelegate> { //AudioPlayer related AVAudioPlayer *appSoundPlayer; NSURL *soundFileURL; BOOL interruptedOnPlayback; BOOL playing; //Scream button related IBOutlet UIButton *screamButton; int currentScreamIndex; NSString *currentScream; NSMutableArray *screams; NSMutableArray *personScreaming; NSMutableArray *photoArray; int currentSayingsIndex; NSString *currentButtonSaying; NSMutableArray *funnyButtonSayings; IBOutlet UILabel *funnyButtonSayingsLabel; IBOutlet UILabel *personScreamingField; IBOutlet UIImageView *personScreamingImage; //Mailing the scream related IBOutlet UILabel *mailStatusMessage; IBOutlet UIButton *shareButton; } //AudioPlayer related @property (nonatomic, retain) AVAudioPlayer *appSoundPlayer; @property (nonatomic, retain) NSURL *soundFileURL; @property (readwrite) BOOL interruptedOnPlayback; @property (readwrite) BOOL playing; //Scream button related @property (nonatomic, retain) UIButton *screamButton; @property (nonatomic, retain) NSMutableArray *screams; @property (nonatomic, retain) NSMutableArray *personScreaming; @property (nonatomic, retain) NSMutableArray *photoArray; @property (nonatomic, retain) UILabel *personScreamingField; @property (nonatomic, retain) UIImageView *personScreamingImage; @property (nonatomic, retain) NSMutableArray *funnyButtonSayings; @property (nonatomic, retain) UILabel *funnyButtonSayingsLabel; //Mailing the scream related @property (nonatomic, retain) IBOutlet UILabel *mailStatusMessage; @property (nonatomic, retain) IBOutlet UIButton *shareButton; //Scream Button - (IBAction) scream: (id) sender; //Mail the scream - (IBAction) showPicker: (id)sender; - (void)displayComposerSheet; - (void)launchMailAppOnDevice; @end Here's the top of .m: #import "ScreamViewController.h" //top of code has Audio session callback function for responding to audio route changes (from Apple's code), then my code continues... @implementation ScreamViewController @synthesize appSoundPlayer; // AVAudioPlayer object for playing the selected scream @synthesize soundFileURL; // Path to the scream @synthesize interruptedOnPlayback; // Was application interrupted during audio playback @synthesize playing; // Track playing/not playing state @synthesize screamButton; //Press this button, girls scream. @synthesize screams; //Mutable array holding strings pointing to sound files of screams. @synthesize personScreaming; //Mutable array tracking the person doing the screaming @synthesize photoArray; //Mutable array holding strings pointing to photos of screaming girls @synthesize personScreamingField; //Field updates to announce which girl is screaming. @synthesize personScreamingImage; //Updates to show image of the screamer. @synthesize funnyButtonSayings; //Mutable array holding the sayings @synthesize funnyButtonSayingsLabel; //Label that updates with the funnyButtonSayings @synthesize mailStatusMessage; //did the email go out @synthesize shareButton; //share scream via email Next line begins the block with the offending code: - (IBAction) scream: (id) sender { //Play a click sound effect SystemSoundID soundID; NSString *sfxPath = [[NSBundle mainBundle] pathForResource:@"aClick" ofType:@"caf"]; AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:sfxPath],&soundID); AudioServicesPlaySystemSound (soundID); // Because someone may slam the scream button over and over, //must stop current sound, then begin next if ([self appSoundPlayer] != nil) { [[self appSoundPlayer] setDelegate:nil]; [[self appSoundPlayer] stop]; [self setAppSoundPlayer: nil]; } //after selecting a random index in the array (did that in View Did Load), //we move to the next scream on each click. //First check... //Are we past the end of the array? if (currentScreamIndex == [screams count]) { currentScreamIndex = 0; } //Get the string at the index in the personScreaming array currentScream = [screams objectAtIndex: currentScreamIndex]; //Get the string at the index in the personScreaming array NSString *screamer = [personScreaming objectAtIndex:currentScreamIndex]; //Log the string to the console NSLog (@"playing scream: %@", screamer); // Display the string in the personScreamingField field NSString *listScreamer = [NSString stringWithFormat:@"scream by: %@", screamer]; [personScreamingField setText:listScreamer]; // Gets the file system path to the scream to play. NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: currentScream ofType: @"caf"]; // Converts the sound's file path to an NSURL object NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath]; self.soundFileURL = newURL; [newURL release]; [[AVAudioSession sharedInstance] setDelegate: self]; [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil]; // Registers the audio route change listener callback function AudioSessionAddPropertyListener ( kAudioSessionProperty_AudioRouteChange, audioRouteChangeListenerCallback, self ); // Activates the audio session. NSError *activationError = nil; [[AVAudioSession sharedInstance] setActive: YES error: &activationError]; // Instantiates the AVAudioPlayer object, initializing it with the sound AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil]; //Error check and continue if (newPlayer != nil) { self.appSoundPlayer = newPlayer; [newPlayer release]; [appSoundPlayer prepareToPlay]; [appSoundPlayer setVolume: 1.0]; [appSoundPlayer setDelegate:self]; //NEXT LINE IS FLAGGED BY INSTRUMENTS AS LEAKY [appSoundPlayer play]; playing = YES; //Get the string at the index in the photoArray array NSString *screamerPic = [photoArray objectAtIndex:currentScreamIndex]; //Log the string to the console NSLog (@"displaying photo: %@", screamerPic); // Display the image of the person screaming personScreamingImage.image = [UIImage imageNamed:screamerPic]; //show the share button shareButton.hidden = NO; mailStatusMessage.hidden = NO; mailStatusMessage.text = @"share!"; //Get the string at the index in the funnySayings array currentSayingsIndex = random() % [funnyButtonSayings count]; currentButtonSaying = [funnyButtonSayings objectAtIndex: currentSayingsIndex]; NSString *theSaying = [funnyButtonSayings objectAtIndex:currentSayingsIndex]; [funnyButtonSayingsLabel setText: theSaying]; currentScreamIndex++; } } Here's my dealloc: - (void)dealloc { [appSoundPlayer stop]; [appSoundPlayer release], appSoundPlayer = nil; [screamButton release], screamButton = nil; [mailStatusMessage release], mailStatusMessage = nil; [personScreamingField release], personScreamingField = nil; [personScreamingImage release], personScreamingImage = nil; [funnyButtonSayings release], funnyButtonSayings = nil; [funnyButtonSayingsLabel release], funnyButtonSayingsLabel = nil; [screams release], screams = nil; [personScreaming release], personScreaming = nil; [soundFileURL release]; [super dealloc]; } @end Thanks so much for reading this far! Any input appreciated.

    Read the article

  • Red Gate Coder interviews: Alex Davies

    - by Michael Williamson
    Alex Davies has been a software engineer at Red Gate since graduating from university, and is currently busy working on .NET Demon. We talked about tackling parallel programming with his actors framework, a scientific approach to debugging, and how JavaScript is going to affect the programming languages we use in years to come. So, if we start at the start, how did you get started in programming? When I was seven or eight, I was given a BBC Micro for Christmas. I had asked for a Game Boy, but my dad thought it would be better to give me a proper computer. For a year or so, I only played games on it, but then I found the user guide for writing programs in it. I gradually started doing more stuff on it and found it fun. I liked creating. As I went into senior school I continued to write stuff on there, trying to write games that weren’t very good. I got a real computer when I was fourteen and found ways to write BASIC on it. Visual Basic to start with, and then something more interesting than that. How did you learn to program? Was there someone helping you out? Absolutely not! I learnt out of a book, or by experimenting. I remember the first time I found a loop, I was like “Oh my God! I don’t have to write out the same line over and over and over again any more. It’s amazing!” When did you think this might be something that you actually wanted to do as a career? For a long time, I thought it wasn’t something that you would do as a career, because it was too much fun to be a career. I thought I’d do chemistry at university and some kind of career based on chemical engineering. And then I went to a careers fair at school when I was seventeen or eighteen, and it just didn’t interest me whatsoever. I thought “I could be a programmer, and there’s loads of money there, and I’m good at it, and it’s fun”, but also that I shouldn’t spoil my hobby. Now I don’t really program in my spare time any more, which is a bit of a shame, but I program all the rest of the time, so I can live with it. Do you think you learnt much about programming at university? Yes, definitely! I went into university knowing how to make computers do anything I wanted them to do. However, I didn’t have the language to talk about algorithms, so the algorithms course in my first year was massively important. Learning other language paradigms like functional programming was really good for breadth of understanding. Functional programming influences normal programming through design rather than actually using it all the time. I draw inspiration from it to write imperative programs which I think is actually becoming really fashionable now, but I’ve been doing it for ages. I did it first! There were also some courses on really odd programming languages, a bit of Prolog, a little bit of C. Having a little bit of each of those is something that I would have never done on my own, so it was important. And then there are knowledge-based courses which are about not programming itself but things that have been programmed like TCP. Those are really important for examples for how to approach things. Did you do any internships while you were at university? Yeah, I spent both of my summers at the same company. I thought I could code well before I went there. Looking back at the crap that I produced, it was only surpassed in its crappiness by all of the other code already in that company. I’m so much better at writing nice code now than I used to be back then. Was there just not a culture of looking after your code? There was, they just didn’t hire people for their abilities in that area. They hired people for raw IQ. The first indicator of it going wrong was that they didn’t have any computer scientists, which is a bit odd in a programming company. But even beyond that they didn’t have people who learnt architecture from anyone else. Most of them had started straight out of university, so never really had experience or mentors to learn from. There wasn’t the experience to draw from to teach each other. In the second half of my second internship, I was being given tasks like looking at new technologies and teaching people stuff. Interns shouldn’t be teaching people how to do their jobs! All interns are going to have little nuggets of things that you don’t know about, but they shouldn’t consistently be the ones who know the most. It’s not a good environment to learn. I was going to ask how you found working with people who were more experienced than you… When I reached Red Gate, I found some people who were more experienced programmers than me, and that was difficult. I’ve been coding since I was tiny. At university there were people who were cleverer than me, but there weren’t very many who were more experienced programmers than me. During my internship, I didn’t find anyone who I classed as being a noticeably more experienced programmer than me. So, it was a shock to the system to have valid criticisms rather than just formatting criticisms. However, Red Gate’s not so big on the actual code review, at least it wasn’t when I started. We did an entire product release and then somebody looked over all of the UI of that product which I’d written and say what they didn’t like. By that point, it was way too late and I’d disagree with them. Do you think the lack of code reviews was a bad thing? I think if there’s going to be any oversight of new people, then it should be continuous rather than chunky. For me I don’t mind too much, I could go out and get oversight if I wanted it, and in those situations I felt comfortable without it. If I was managing the new person, then maybe I’d be keener on oversight and then the right way to do it is continuously and in very, very small chunks. Have you had any significant projects you’ve worked on outside of a job? When I was a teenager I wrote all sorts of stuff. I used to write games, I derived how to do isomorphic projections myself once. I didn’t know what the word was so I couldn’t Google for it, so I worked it out myself. It was horrifically complicated. But it sort of tailed off when I started at university, and is now basically zero. If I do side-projects now, they tend to be work-related side projects like my actors framework, NAct, which I started in a down tools week. Could you explain a little more about NAct? It is a little C# framework for writing parallel code more easily. Parallel programming is difficult when you need to write to shared data. Sometimes parallel programming is easy because you don’t need to write to shared data. When you do need to access shared data, you could just have your threads pile in and do their work, but then you would screw up the data because the threads would trample on each other’s toes. You could lock, but locks are really dangerous if you’re using more than one of them. You get interactions like deadlocks, and that’s just nasty. Actors instead allows you to say this piece of data belongs to this thread of execution, and nobody else can read it. If you want to read it, then ask that thread of execution for a piece of it by sending a message, and it will send the data back by a message. And that avoids deadlocks as long as you follow some obvious rules about not making your actors sit around waiting for other actors to do something. There are lots of ways to write actors, NAct allows you to do it as if it was method calls on other objects, which means you get all the strong type-safety that C# programmers like. Do you think that this is suitable for the majority of parallel programming, or do you think it’s only suitable for specific cases? It’s suitable for most difficult parallel programming. If you’ve just got a hundred web requests which are all independent of each other, then I wouldn’t bother because it’s easier to just spin them up in separate threads and they can proceed independently of each other. But where you’ve got difficult parallel programming, where you’ve got multiple threads accessing multiple bits of data in multiple ways at different times, then actors is at least as good as all other ways, and is, I reckon, easier to think about. When you’re using actors, you presumably still have to write your code in a different way from you would otherwise using single-threaded code. You can’t use actors with any methods that have return types, because you’re not allowed to call into another actor and wait for it. If you want to get a piece of data out of another actor, then you’ve got to use tasks so that you can use “async” and “await” to await asynchronously for it. But other than that, you can still stick things in classes so it’s not too different really. Rather than having thousands of objects with mutable state, you can use component-orientated design, where there are only a few mutable classes which each have a small number of instances. Then there can be thousands of immutable objects. If you tend to do that anyway, then actors isn’t much of a jump. If I’ve already built my system without any parallelism, how hard is it to add actors to exploit all eight cores on my desktop? Usually pretty easy. If you can identify even one boundary where things look like messages and you have components where some objects live on one side and these other objects live on the other side, then you can have a granddaddy object on one side be an actor and it will parallelise as it goes across that boundary. Not too difficult. If we do get 1000-core desktop PCs, do you think actors will scale up? It’s hard. There are always in the order of twenty to fifty actors in my whole program because I tend to write each component as actors, and I tend to have one instance of each component. So this won’t scale to a thousand cores. What you can do is write data structures out of actors. I use dictionaries all over the place, and if you need a dictionary that is going to be accessed concurrently, then you could build one of those out of actors in no time. You can use queuing to marshal requests between different slices of the dictionary which are living on different threads. So it’s like a distributed hash table but all of the chunks of it are on the same machine. That means that each of these thousand processors has cached one small piece of the dictionary. I reckon it wouldn’t be too big a leap to start doing proper parallelism. Do you think it helps if actors get baked into the language, similarly to Erlang? Erlang is excellent in that it has thread-local garbage collection. C# doesn’t, so there’s a limit to how well C# actors can possibly scale because there’s a single garbage collected heap shared between all of them. When you do a global garbage collection, you’ve got to stop all of the actors, which is seriously expensive, whereas in Erlang garbage collections happen per-actor, so they’re insanely cheap. However, Erlang deviated from all the sensible language design that people have used recently and has just come up with crazy stuff. You can definitely retrofit thread-local garbage collection to .NET, and then it’s quite well-suited to support actors, even if it’s not baked into the language. Speaking of language design, do you have a favourite programming language? I’ll choose a language which I’ve never written before. I like the idea of Scala. It sounds like C#, only with some of the niggles gone. I enjoy writing static types. It means you don’t have to writing tests so much. When you say it doesn’t have some of the niggles? C# doesn’t allow the use of a property as a method group. It doesn’t have Scala case classes, or sum types, where you can do a switch statement and the compiler checks that you’ve checked all the cases, which is really useful in functional-style programming. Pattern-matching, in other words. That’s actually the major niggle. C# is pretty good, and I’m quite happy with C#. And what about going even further with the type system to remove the need for tests to something like Haskell? Or is that a step too far? I’m quite a pragmatist, I don’t think I could deal with trying to write big systems in languages with too few other users, especially when learning how to structure things. I just don’t know anyone who can teach me, and the Internet won’t teach me. That’s the main reason I wouldn’t use it. If I turned up at a company that writes big systems in Haskell, I would have no objection to that, but I wouldn’t instigate it. What about things in C#? For instance, there’s contracts in C#, so you can try to statically verify a bit more about your code. Do you think that’s useful, or just not worthwhile? I’ve not really tried it. My hunch is that it needs to be built into the language and be quite mathematical for it to work in real life, and that doesn’t seem to have ended up true for C# contracts. I don’t think anyone who’s tried them thinks they’re any good. I might be wrong. On a slightly different note, how do you like to debug code? I think I’m quite an odd debugger. I use guesswork extremely rarely, especially if something seems quite difficult to debug. I’ve been bitten spending hours and hours on guesswork and not being scientific about debugging in the past, so now I’m scientific to a fault. What I want is to see the bug happening in the debugger, to step through the bug happening. To watch the program going from a valid state to an invalid state. When there’s a bug and I can’t work out why it’s happening, I try to find some piece of evidence which places the bug in one section of the code. From that experiment, I binary chop on the possible causes of the bug. I suppose that means binary chopping on places in the code, or binary chopping on a stage through a processing cycle. Basically, I’m very stupid about how I debug. I won’t make any guesses, I won’t use any intuition, I will only identify the experiment that’s going to binary chop most effectively and repeat rather than trying to guess anything. I suppose it’s quite top-down. Is most of the time then spent in the debugger? Absolutely, if at all possible I will never debug using print statements or logs. I don’t really hold much stock in outputting logs. If there’s any bug which can be reproduced locally, I’d rather do it in the debugger than outputting logs. And with SmartAssembly error reporting, there’s not a lot that can’t be either observed in an error report and just fixed, or reproduced locally. And in those other situations, maybe I’ll use logs. But I hate using logs. You stare at the log, trying to guess what’s going on, and that’s exactly what I don’t like doing. You have to just look at it and see does this look right or wrong. We’ve covered how you get to grip with bugs. How do you get to grips with an entire codebase? I watch it in the debugger. I find little bugs and then try to fix them, and mostly do it by watching them in the debugger and gradually getting an understanding of how the code works using my process of binary chopping. I have to do a lot of reading and watching code to choose where my slicing-in-half experiment is going to be. The last time I did it was SmartAssembly. The old code was a complete mess, but at least it did things top to bottom. There wasn’t too much of some of the big abstractions where flow of control goes all over the place, into a base class and back again. Code’s really hard to understand when that happens. So I like to choose a little bug and try to fix it, and choose a bigger bug and try to fix it. Definitely learn by doing. I want to always have an aim so that I get a little achievement after every few hours of debugging. Once I’ve learnt the codebase I might be able to fix all the bugs in an hour, but I’d rather be using them as an aim while I’m learning the codebase. If I was a maintainer of a codebase, what should I do to make it as easy as possible for you to understand? Keep distinct concepts in different places. And name your stuff so that it’s obvious which concepts live there. You shouldn’t have some variable that gets set miles up the top of somewhere, and then is read miles down to choose some later behaviour. I’m talking from a very much SmartAssembly point of view because the old SmartAssembly codebase had tons and tons of these things, where it would read some property of the code and then deal with it later. Just thousands of variables in scope. Loads of things to think about. If you can keep concepts separate, then it aids me in my process of fixing bugs one at a time, because each bug is going to more or less be understandable in the one place where it is. And what about tests? Do you think they help at all? I’ve never had the opportunity to learn a codebase which has had tests, I don’t know what it’s like! What about when you’re actually developing? How useful do you find tests in finding bugs or regressions? Finding regressions, absolutely. Running bits of code that would be quite hard to run otherwise, definitely. It doesn’t happen very often that a test finds a bug in the first place. I don’t really buy nebulous promises like tests being a good way to think about the spec of the code. My thinking goes something like “This code works at the moment, great, ship it! Ah, there’s a way that this code doesn’t work. Okay, write a test, demonstrate that it doesn’t work, fix it, use the test to demonstrate that it’s now fixed, and keep the test for future regressions.” The most valuable tests are for bugs that have actually happened at some point, because bugs that have actually happened at some point, despite the fact that you think you’ve fixed them, are way more likely to appear again than new bugs are. Does that mean that when you write your code the first time, there are no tests? Often. The chance of there being a bug in a new feature is relatively unaffected by whether I’ve written a test for that new feature because I’m not good enough at writing tests to think of bugs that I would have written into the code. So not writing regression tests for all of your code hasn’t affected you too badly? There are different kinds of features. Some of them just always work, and are just not flaky, they just continue working whatever you throw at them. Maybe because the type-checker is particularly effective around them. Writing tests for those features which just tend to always work is a waste of time. And because it’s a waste of time I’ll tend to wait until a feature has demonstrated its flakiness by having bugs in it before I start trying to test it. You can get a feel for whether it’s going to be flaky code as you’re writing it. I try to write it to make it not flaky, but there are some things that are just inherently flaky. And very occasionally, I’ll think “this is going to be flaky” as I’m writing, and then maybe do a test, but not most of the time. How do you think your programming style has changed over time? I’ve got clearer about what the right way of doing things is. I used to flip-flop a lot between different ideas. Five years ago I came up with some really good ideas and some really terrible ideas. All of them seemed great when I thought of them, but they were quite diverse ideas, whereas now I have a smaller set of reliable ideas that are actually good for structuring code. So my code is probably more similar to itself than it used to be back in the day, when I was trying stuff out. I’ve got more disciplined about encapsulation, I think. There are operational things like I use actors more now than I used to, and that forces me to use immutability more than I used to. The first code that I wrote in Red Gate was the memory profiler UI, and that was an actor, I just didn’t know the name of it at the time. I don’t really use object-orientation. By object-orientation, I mean having n objects of the same type which are mutable. I want a constant number of objects that are mutable, and they should be different types. I stick stuff in dictionaries and then have one thing that owns the dictionary and puts stuff in and out of it. That’s definitely a pattern that I’ve seen recently. I think maybe I’m doing functional programming. Possibly. It’s plausible. If you had to summarise the essence of programming in a pithy sentence, how would you do it? Programming is the form of art that, without losing any of the beauty of architecture or fine art, allows you to produce things that people love and you make money from. So you think it’s an art rather than a science? It’s a little bit of engineering, a smidgeon of maths, but it’s not science. Like architecture, programming is on that boundary between art and engineering. If you want to do it really nicely, it’s mostly art. You can get away with doing architecture and programming entirely by having a good engineering mind, but you’re not going to produce anything nice. You’re not going to have joy doing it if you’re an engineering mind. Architects who are just engineering minds are not going to enjoy their job. I suppose engineering is the foundation on which you build the art. Exactly. How do you think programming is going to change over the next ten years? There will be an unfortunate shift towards dynamically-typed languages, because of JavaScript. JavaScript has an unfair advantage. JavaScript’s unfair advantage will cause more people to be exposed to dynamically-typed languages, which means other dynamically-typed languages crop up and the best features go into dynamically-typed languages. Then people conflate the good features with the fact that it’s dynamically-typed, and more investment goes into dynamically-typed languages. They end up better, so people use them. What about the idea of compiling other languages, possibly statically-typed, to JavaScript? It’s a reasonable idea. I would like to do it, but I don’t think enough people in the world are going to do it to make it pick up. The hordes of beginners are the lifeblood of a language community. They are what makes there be good tools and what makes there be vibrant community websites. And any particular thing which is the same as JavaScript only with extra stuff added to it, although it might be technically great, is not going to have the hordes of beginners. JavaScript is always to be quickest and easiest way for a beginner to start programming in the browser. And dynamically-typed languages are great for beginners. Compilers are pretty scary and beginners don’t write big code. And having your errors come up in the same place, whether they’re statically checkable errors or not, is quite nice for a beginner. If someone asked me to teach them some programming, I’d teach them JavaScript. If dynamically-typed languages are great for beginners, when do you think the benefits of static typing start to kick in? The value of having a statically typed program is in the tools that rely on the static types to produce a smooth IDE experience rather than actually telling me my compile errors. And only once you’re experienced enough a programmer that having a really smooth IDE experience makes a blind bit of difference, does static typing make a blind bit of difference. So it’s not really about size of codebase. If I go and write up a tiny program, I’m still going to get value out of writing it in C# using ReSharper because I’m experienced with C# and ReSharper enough to be able to write code five times faster if I have that help. Any other visions of the future? Nobody’s going to use actors. Because everyone’s going to be running on single-core VMs connected over network-ready protocols like JSON over HTTP. So, parallelism within one operating system is going to die. But until then, you should use actors. More Red Gater Coder interviews

    Read the article

  • Launching Intent.ACTION_VIEW intent not working on saved image file

    - by Savvas Dalkitsis
    First of all let me say that this questions is slightly connected to another question by me. Actually it was created because of that. I have the following code to write a bitmap downloaded from the net to a file in the sd card: // Get image from url URL u = new URL(url); HttpGet httpRequest = new HttpGet(u.toURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream instream = bufHttpEntity.getContent(); Bitmap bmImg = BitmapFactory.decodeStream(instream); instream.close(); // Write image to a file in sd card File posterFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/com.myapp/files/image.jpg"); posterFile.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(posterFile)); Bitmap mutable = Bitmap.createScaledBitmap(bmImg,bmImg.getWidth(),bmImg.getHeight(),true); mutable.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); // Launch default viewer for the file Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(posterFile.getAbsolutePath()),"image/*"); ((Activity) getContext()).startActivity(intent); A few notes. I am creating the "mutable" bitmap after seeing someone using it and it seems to work better than without it. And i am using the parse method on the Uri class and not the fromFile because in my code i am calling these in different places and when i am creating the intent i have a string path instead of a file. Now for my problem. The file gets created. The intent launches a dialog asking me to select a viewer. I have 3 viewers installed. The Astro image viewer, the default media gallery (i have a milstone on 2.1 but on the milestone the 2.1 update did not include the 3d gallery so it's the old one) and the 3d gallery from the nexus one (i found the apk in the wild). Now when i launch the 3 viewers the following happen: Astro image viewer: The activity launches but i see nothing but a black screen. Media Gallery: i get an exception dialog shown "The application Media Gallery (process com.motorola.gallery) has stopped unexpectedly. Please try again" with a force close option. 3D gallery: Everything works as it should. When i try to simply open the file using the Astro file manager (browse to it and simply click) i get the same option dialog but this time things are different: Astro image viewer: Everything works as it should. Media Gallery: Everything works as it should. 3D gallery: The activity launches but i see nothing but a black screen. As you can see everything is a complete mess. I have no idea why this happens but it happens like this every single time. It's not a random bug. Am i missing something when i am creating the intent? Or when i am creating the image file? Any ideas?

    Read the article

  • Get Asynchronous HttpResponse through Silverlight (F#)

    - by jack2010
    I am a newbie with F# and SL and playing with getting asynchronous HttpResponse through Silverlight. The following is the F# code pieces, which is tested on VS2010 and Window7 and works well, but the improvement is necessary. Any advices and discussion, especially the callback part, are welcome and great thanks. module JSONExample open System open System.IO open System.Net open System.Text open System.Web open System.Security.Authentication open System.Runtime.Serialization [<DataContract>] type Result<'TResult> = { [<field: DataMember(Name="code") >] Code:string [<field: DataMember(Name="result") >] Result:'TResult array [<field: DataMember(Name="message") >] Message:string } // The elements in the list [<DataContract>] type ChemicalElement = { [<field: DataMember(Name="name") >] Name:string [<field: DataMember(Name="boiling_point") >] BoilingPoint:string [<field: DataMember(Name="atomic_mass") >] AtomicMass:string } //http://blogs.msdn.com/b/dsyme/archive/2007/10/11/introducing-f-asynchronous-workflows.aspx //http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!194.entry type System.Net.HttpWebRequest with member x.GetResponseAsync() = Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse) type RequestState () = let mutable request : WebRequest = null let mutable response : WebResponse = null let mutable responseStream : Stream = null member this.Request with get() = request and set v = request <- v member this.Response with get() = response and set v = response <- v member this.ResponseStream with get() = responseStream and set v = responseStream <- v let allDone = new System.Threading.ManualResetEvent(false) let getHttpWebRequest (query:string) = let query = query.Replace("'","\"") let queryUrl = sprintf "http://api.freebase.com/api/service/mqlread?query=%s" "{\"query\":"+query+"}" let request : HttpWebRequest = downcast WebRequest.Create(queryUrl) request.Method <- "GET" request.ContentType <- "application/x-www-form-urlencoded" request let GetAsynResp (request : HttpWebRequest) (callback: AsyncCallback) = let myRequestState = new RequestState() myRequestState.Request <- request let asyncResult = request.BeginGetResponse(callback, myRequestState) () // easy way to get it to run syncrnously w/ the asynch methods let GetSynResp (request : HttpWebRequest) : HttpWebResponse = let response = request.GetResponseAsync() |> Async.RunSynchronously downcast response let RespCallback (finish: Stream -> _) (asynchronousResult : IAsyncResult) = try let myRequestState : RequestState = downcast asynchronousResult.AsyncState let myWebRequest1 : WebRequest = myRequestState.Request myRequestState.Response <- myWebRequest1.EndGetResponse(asynchronousResult) let responseStream = myRequestState.Response.GetResponseStream() myRequestState.ResponseStream <- responseStream finish responseStream myRequestState.Response.Close() () with | :? WebException as e -> printfn "WebException raised!" printfn "\n%s" e.Message printfn "\n%s" (e.Status.ToString()) () | _ as e -> printfn "Exception raised!" printfn "Source : %s" e.Source printfn "Message : %s" e.Message () let printResults (stream: Stream)= let result = try use reader = new StreamReader(stream) reader.ReadToEnd(); finally () let data = Encoding.Unicode.GetBytes(result); let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let JsonSerializer = Json.DataContractJsonSerializer(typeof<Result<ChemicalElement>>) let result = JsonSerializer.ReadObject(stream) :?> Result<ChemicalElement> if result.Code<>"/api/status/ok" then raise (InvalidOperationException(result.Message)) else result.Result |> Array.iter(fun element->printfn "%A" element) let test = // Call Query (w/ generics telling it you wand an array of ChemicalElement back, the query string is wackyJSON too –I didn’t build it don’t ask me! let request = getHttpWebRequest "[{'type':'/chemistry/chemical_element','name':null,'boiling_point':null,'atomic_mass':null}]" //let response = GetSynResp request let response = GetAsynResp request (AsyncCallback (RespCallback printResults)) () ignore(test) System.Console.ReadLine() |> ignore

    Read the article

  • NHibernate Proxy Creation

    - by Chris Meek
    I have a class structure like the following class Container { public virtual int Id { get; set; } public IList<Base> Bases { get; set; } } class Base { public virtual int Id { get; set; } public virtual string Name { get; set; } } class EnemyBase : Base { public virtual int EstimatedSize { get; set; } } class FriendlyBase : Base { public virtual int ActualSize { get; set; } } Now when I ask the session for a particular Container it normally gives me the concrete EnemyBase and FriendlyBase objects in the Bases collection. I can then (if I so choose) cast them to their concrete types and do something specific with them. However, sometime I get a proxy of the "Base" class which is not castable to the concrete types. The same method is used both times with the only exception being that in the case that I get proxies I have added some related entities to the session (think the friendly base having a collection of people or something like that). Is there any way I can prevent it from doing the proxy creating and why would it choose to do this in some scenarios? UPDATE The mappings are generated with the automap feature of fluentnhibernate but look something like this when exported <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"> <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Base" table="`Base`"> <id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Id" /> <generator class="MyIdGenerator" /> </id> <property name="Name" type="String"> <column name="Name" /> </property> <joined-subclass name="EnemyBase"> <key> <column name="Id" /> </key> <property name="EstimatedSize" type="Int"> <column name="EstimatedSize" /> </property> </joined-subclass> <joined-subclass name="FriendlyBase"> <key> <column name="Id" /> </key> <property name="ActualSize" type="Int"> <column name="ActualSize" /> </property> </joined-subclass> </class> </hibernate-mapping> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"> <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Container" table="`Container`"> <id name="Id" type="System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Id" /> <generator class="MyIdGenerator" /> </id> <bag cascade="all-delete-orphan" inverse="true" lazy="false" name="Bases" mutable="true"> <key> <column name="ContainerId" /> </key> <one-to-many class="Base" /> </bag> </class> </hibernate-mapping>

    Read the article

  • Writing a method to 'transform' an immutable object: how should I approach this?

    - by Prog
    (While this question has to do with a concrete coding dilemma, it's mostly about what's the best way to design a function.) I'm writing a method that should take two Color objects, and gradually transform the first Color into the second one, creating an animation. The method will be in a utility class. My problem is that Color is an immutable object. That means that I can't do color.setRGB or color.setBlue inside a loop in the method. What I can do, is instantiate a new Color and return it from the method. But then I won't be able to gradually change the color. So I thought of three possible solutions: 1- The client code includes the method call inside a loop. For example: int duration = 1500; // duration of the animation in milliseconds int steps = 20; // how many 'cycles' the animation will take for(int i=0; i<steps; i++) color = transformColor(color, targetColor, duration, steps); And the method would look like this: Color transformColor(Color original, Color target, int duration, int steps){ int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted return new Color(newRed, newGreen, newBlue); } The disadvantage of this approach is that the client code has to "do part of the method's job" and include a for loop. The method doesn't do it's work entirely on it's own, which I don't like. 2- Make a mutable Color subclass with methods such as setRed, and pass objects of this class into transformColor. Then it could look something like this: void transformColor(MutableColor original, Color target, int duration){ final int STEPS = 20; int redDiff = target.getRed() - original.getRed(); int redAddition = redDiff / steps; int newRed = original.getRed() + redAddition; // same for green and blue .. for(int i=0; i<STEPS; i++){ original.setRed(original.getRed() + redAddition); // same for green and blue .. Thread.sleep(duration / STEPS); // exception handling omitted } } Then the calling code would usually look something like this: // The method will usually transform colors of JComponents JComponent someComponent = ... ; // setting the Color in JComponent to be a MutableColor Color mutableColor = new MutableColor(someComponent.getForeground()); someComponent.setForeground(mutableColor); // later, transforming the Color in the JComponent transformColor((MutableColor)someComponent.getForeground(), new Color(200,100,150), 2000); The disadvantage is - the need to create a new class MutableColor, and also the need to do casting. 3- Pass into the method the actual mutable object that holds the color. Then the method could do object.setColor or similar every iteration of the loop. Two disadvantages: A- Not so elegant. Passing in the object that holds the color just to transform the color feels unnatural. B- While most of the time this method will be used to transform colors inside JComponent objects, other kinds of objects may have colors too. So the method would need to be overloaded to receive other types, or receive Objects and have instanceof checks inside.. Not optimal. Right now I think I like solution #2 the most, than solution #1 and solution #3 the least. However I'd like to hear your opinions and suggestions regarding this.

    Read the article

  • Setting ivar in objective-c from child view in the iPhone

    - by Ivan
    Hi there! Maybe a FAQ at this website. I have a TableViewController that holds a form. In that form I have two fields (each in it's own cell): one to select who paid (single selection), and another to select people expense is paid for (multiple selection). Both fields open a new TableViewController included in an UINavigationController. Single select field (Paid By) holds an object Membership Multiple select field (Paid For) holds an object NSMutableArray Both vars are being sent to the new controller identically the same way: mySingleSelectController.crSelectedMember = self.crPaidByMember; myMultipleSelectController.crSelectedMembers = self.crSelectedMembers; From Paid for controller I use didSelectAtIndexPath method to set a mutable array of Memberships for whom is paid: if ([[tableView cellForRowAtIndexPath:indexPath] accessoryType] == UITableViewCellAccessoryCheckmark) { [self.crSelectedMembers removeObject:[self.crGroupMembers objectAtIndex:indexPath.row]]; //... } else { [self.crSelectedMembers addObject:[self.crGroupMembers objectAtIndex:indexPath.row]]; //... } So far everything goes well. An mutable array (crSelectedMembers) is perfectly set from child view. But... I have trouble setting Membership object. From Paid By controller I use didSelectAtIndexPath to set Membership: [self setCrSelectedMember:[crGroupMembers objectAtIndex:indexPath.row]]; By NSlogging crSelectedMember I get the right selected member in self, but in parent view, to which ivar is pointed, nothing is changed. Am I doing something wrong? Cause I CAN call the method of crSelectedMembers, but I can't change the value of crSelectedMember.

    Read the article

  • Could not load ConfigurationSection class - type

    - by nCdy
    at web.config <section name="FlowWebDataProviders" type="FlowWebProvidersSection" requirePermission="false"/> <FlowWebDataProviders peopleProviderName="sqlProvider" IzmListProviderName="sqlProvider"> <PeopleProviders> <add name="sqlProvider" type="SqlPeopleProvider" connectionStringName="FlowServerConnectionString"/> <add name="xmlProvider" type="XmlPeopleProvider" schemaFile="People.xsd" dataFile="People.xml"/> </PeopleProviders> <IzmListProviders> <add name="sqlProvider" type="SqlIzmListProvider" connectionStringName="FlowServerConnectionString"/> </IzmListProviders> </FlowWebDataProviders> and public class FlowWebProvidersSection : ConfigurationSection { [ConfigurationProperty("peopleProviderName", IsRequired = true)] public PeopleProviderName : string { get { this["peopleProviderName"] :> string } set { this["peopleProviderName"] = value; } } [ConfigurationProperty("IzmListProviderName", IsRequired = true)] public IzmListProviderName : string { get { (this["IzmListProviderName"] :> string) } set { this["IzmListProviderName"] = value; } } [ConfigurationProperty("PeopleProviders")] [ConfigurationValidatorAttribute(typeof(ProviderSettingsValidation))] public PeopleProviders : ProviderSettingsCollection { get { this["PeopleProviders"] :> ProviderSettingsCollection } } [ConfigurationProperty("IzmListProviders")] [ConfigurationValidatorAttribute(typeof(ProviderSettingsValidation))] public IzmListProviders : ProviderSettingsCollection { get { this["IzmListProviders"] :> ProviderSettingsCollection } } } and public class ProviderSettingsValidation : ConfigurationValidatorBase { public override CanValidate(typex : Type) : bool { if(typex : object == typeof(ProviderSettingsCollection)) true else false } /// <summary> // validate the provider section /// </summary> public override Validate(value : object) : void { mutable providerCollection : ProviderSettingsCollection = match(value) { | x is ProviderSettingsCollection => x | _ => null } unless (providerCollection == null) { foreach (_provider is ProviderSettings in providerCollection) { when (String.IsNullOrEmpty(_provider.Type)) { throw ConfigurationErrorsException("Type was not defined in the provider"); } mutable dataAccessType : Type = Type.GetType(_provider.Type); when (dataAccessType == null) { throw (InvalidOperationException("Provider's Type could not be found")); } } } } } project : Web Application ... I need to find error first . . . why : Error message parser: Error creating configuration section handler for FlowWebDataProviders: Could not load type 'FlowWebProvidersSection'. ? by the way : syntax of nemerle (current language) is very similar C#, don't afraid to read the code... thank you

    Read the article

  • Why doesn't the F# Set implement ISet<T>?

    - by Sean Devlin
    The .NET Framework is adding an ISet<T> interface with the 4.0 release. In the same release, F# is being added as a first-class language. F# provides an immutable Set<'T> class. It would seem logical to me that the immutable set provided would implement the ISet<T> interface, but it doesn't. Does anyone know why? My guess is that they didn't want to implement an interface intended to be mutable, but I don't think this explanation holds up. After all, their Map<'Key, 'Value> class implements IDictionary, which is mutable. And there are examples elsewhere in the framework of classes implementing interfaces that are only partially appropriate. My other thought is that ISet<T> is new, so maybe they didn't get around to it. But that seems kind of thin. Does the fact that ISet<T> is generic (v. IDictionary, which is not) have anything to do with it? Any thoughts on the matter would be appreciated.

    Read the article

  • Tableview not updating correctly after adding person

    - by tazboy
    I have to be missing something simple here but it escapes me. After the user enters a new person to a mutable array I want to update the table. The mutable array is the datasource. I believe my issue lies within cellForRowAtIndexPath. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TextFieldCell *customCell = (TextFieldCell *)[tableView dequeueReusableCellWithIdentifier:@"TextCellID"]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; if (indexPath.row == 0) { if (customCell == nil) { NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"TextFieldCell" owner:nil options:nil]; for (id currentObject in nibObjects) { if ([currentObject isKindOfClass:[TextFieldCell class]]) customCell = (TextFieldCell *)currentObject; } } customCell.nameTextField.delegate = self; cell = customCell; } else { if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"]; cell.textLabel.text = [[self.peopleArray objectAtIndex:indexPath.row-1] name]; NSLog(@"PERSON AT ROW %d = %@", indexPath.row-1, [[self.peopleArray objectAtIndex:indexPath.row-1] name]); NSLog(@"peopleArray's Size = %d", [self.peopleArray count]); } } return cell; } When I first load the view everything is great. This is what prints: PERSON AT ROW 0 = Melissa peopleArray's Size = 2 PERSON AT ROW 1 = Dave peopleArray's Size = 2 After I add someone to that array I get this: PERSON AT ROW 1 = Dave peopleArray's Size = 3 PERSON AT ROW 2 = Tom peopleArray's Size = 3 When I add a second person I get: PERSON AT ROW 2 = Tom peopleArray's Size = 4 PERSON AT ROW 3 = Ralph peopleArray's Size = 4 Why is not printing everyone in the array? This pattern continues and it only ever prints two people, and it's always the last two people. What the heck am I missing?

    Read the article

  • Modify static variables while debugging in Eclipse

    - by sleske
    As an extension the the question "Modify/view static variables while debugging in Eclipse", I'd like to be able to modify static variables while debugging in Eclipse. For instance and local variables, I can just choose the variable in the "Variables" view of Eclipse, and use the context menu "Change value..." to change the value. This is not possible for arbitrary static variables, because they do not appear in the "Variables" view. What I tried: If you choose "Java / Show static variables" from the triangle menu in the "Variables" view, you can see and modify static member variables of the variables listed in the "Variables view". However, I did not find how to access a static member of a class whose instance does not appear in the "Variables view". You can of course enter a static member as an expression into the "Expression view" (using fully qualified name). Then you can see the value, but the "Expression view" does not have an option to modify the value (it does allow to modify members of an expression, but not the expression itself, even if the expression is a field). So, if I have a static variable like a boolean MyClass.disableAllBugs, is there a way to change MyClass.disableAllBugs during debugging? As an aside: I realize that even having public mutable static fields (i.e. mutable global variables) is very bad style. But some codebases have it, and then it's sometimes useful to modify it while debugging.

    Read the article

  • Returning the same type the function was passed

    - by Ken Bloom
    I have the following code implementation of Breadth-First search. trait State{ def successors:Seq[State] def isSuccess:Boolean = false def admissableHeuristic:Double } def breadthFirstSearch(initial:State):Option[List[State]] = { val open= new scala.collection.mutable.Queue[List[State]] val closed = new scala.collection.mutable.HashSet[State] open.enqueue(initial::Nil) while (!open.isEmpty){ val path:List[State]=open.dequeue() if(path.head.isSuccess) return Some(path.reverse) closed += path.head for (x <- path.head.successors) if (!closed.contains(x)) open.enqueue(x::path) } return None } If I define a subtype of State for my particular problem class CannibalsState extends State { //... } What's the best way to make breadthFirstSearch return the same subtype as it was passed? Supposing I change this so that there are 3 different state classes for my particular problem and they share a common supertype: abstract class CannibalsState extends State { //... } class LeftSideOfRiver extends CannibalsState { //... } class InTransit extends CannibalsState { //... } class RightSideOfRiver extends CannibalsState { //... } How can I make the types work out so that breadthFirstSearch infers that the correct return type is CannibalsState when it's passed an instance of LeftSideOfRiver? Can this be done with an abstract type member, or must it be done with generics?

    Read the article

  • How should I avoid memoization causing bugs in Ruby?

    - by Andrew Grimm
    Is there a consensus on how to avoid memoization causing bugs due to mutable state? In this example, a cached result had its state mutated, and therefore gave the wrong result the second time it was called. class Greeter def initialize @greeting_cache = {} end def expensive_greeting_calculation(formality) case formality when :casual then "Hi" when :formal then "Hello" end end def greeting(formality) unless @greeting_cache.has_key?(formality) @greeting_cache[formality] = expensive_greeting_calculation(formality) end @greeting_cache[formality] end end def memoization_mutator greeter = Greeter.new first_person = "Bob" # Mildly contrived in this case, # but you could encounter this in more complex scenarios puts(greeter.greeting(:casual) << " " << first_person) # => Hi Bob second_person = "Sue" puts(greeter.greeting(:casual) << " " << second_person) # => Hi Bob Sue end memoization_mutator Approaches I can see to avoid this are: greeting could return a dup or clone of @greeting_cache[formality] greeting could freeze the result of @greeting_cache[formality]. That'd cause an exception to be raised when memoization_mutator appends strings to it. Check all code that uses the result of greeting to ensure none of it does any mutating of the string. Is there a consensus on the best approach? Is the only disadvantage of doing (1) or (2) decreased performance? (I also suspect freezing an object may not work fully if it has references to other objects) Side note: this problem doesn't affect the main application of memoization: as Fixnums are immutable, calculating Fibonacci sequences doesn't have problems with mutable state. :)

    Read the article

  • Why Stream/lazy val implementation using is faster than ListBuffer one

    - by anrizal
    I coded the following implementation of lazy sieve algorithms using Stream and lazy val below : def primes(): Stream[Int] = { lazy val ps = 2 #:: sieve(3) def sieve(p: Int): Stream[Int] = { p #:: sieve( Stream.from(p + 2, 2). find(i=> ps.takeWhile(j => j * j <= i). forall(i % _ > 0)).get) } ps } and the following implementation using (mutable) ListBuffer: import scala.collection.mutable.ListBuffer def primes(): Stream[Int] = { def sieve(p: Int, ps: ListBuffer[Int]): Stream[Int] = { p #:: { val nextprime = Stream.from(p + 2, 2). find(i=> ps.takeWhile(j => j * j <= i). forall(i % _ > 0)).get sieve(nextprime, ps += nextprime) } } sieve(3, ListBuffer(3))} When I did primes().takeWhile(_ < 1000000).size , the first implementation is 3 times faster than the second one. What's the explanation for this ? I edited the second version: it should have been sieve(3, ListBuffer(3)) instead of sieve(3, ListBuffer()) .

    Read the article

  • Passing information safely between Wicket and Hibernate in long running conversations

    - by Peter Tillemans
    We are using Wicket with Hibernate in the background. As part of out UI we have quite long running conversations spanning multiple requests before the updated information is written back to the database. To avoid getting hibernate errors with detached objects we are now using value objects to transfer info from the service layer to Wicket. However we now end up with an explosion of almost the same objects : e.g. Answer (mapped entity saved in hibernate) AnswerVO (immutable value object) AnswerModel (A mutable bean in the session domain) IModel wrapped Wicket Model and usually this gets wrapped in a CompoundPropertyModel This plumbing becomes exponentially worse when collections to other objects are involved in the objects. There has to be a better way to organize this. Can anyone share tips to make this less onerous? Maybe make the value objects mutable so we can remove the need for a seaprate backing bean in Wicket? Use the entity beans but absolutely make dead-certain they are detached from hibernate. (easier said than done)? Some other tricks or patterns?

    Read the article

  • Best way to determine variable type and treat each one differently in F#

    - by James Black
    I have a function that will create a select where clause, but right now everything has to be a string. I would like to look at the variable passed in and determine what type it is and then treat it properly. For example, numeric values don't have single quotes around them, option type will either be null or have some value and boolean will actually be zero or one. member self.BuildSelectWhereQuery (oldUser:'a) = let properties = List.zip oldUser.ToSqlValuesList sqlColumnList let init = false, new StringBuilder() let anyChange, (formatted:StringBuilder) = properties |> Seq.fold (fun (anyChange, sb) (oldVal, name) -> match(anyChange) with | true -> true, sb.AppendFormat(" AND {0} = '{1}'", name, oldVal) | _ -> true, sb.AppendFormat("{0} = '{1}'", name, oldVal) ) init formatted.ToString() Here is one entity: type CityType() = inherit BaseType() let mutable name = "" let mutable stateId = 0 member this.Name with get() = name and set restnameval=name <- restnameval member this.StateId with get() = stateId and set stateidval=stateId <- stateidval override this.ToSqlValuesList = [this.Name; this.StateId.ToString()] So, if name was some other value besides a string, or stateId can be optional, then I have two changes to make: How do I modify ToSqlValuesList to have the variable so I can tell the variable type? How do I change my select function to handle this? I am thinking that I need a new function does the processing, but what is the best FP way to do this, rather than using something like typeof?

    Read the article

  • Why doesn't java.lang.Number implement Comparable?

    - by Julien Chastang
    Does anyone know why java.lang.Number does not implement Comparable? This means that you cannot sort Numbers with Collections.sort which seems to me a little strange. Post discussion update: Thanks for all the helpful responses. I ended up doing some more research about this topic. The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns. For a bit of review, java.lang.Number is the abstract super-type of AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long and Short. On that list, AtomicInteger and AtomicLong to do not implement Comparable. Digging around, I discovered that it is not a good practice to implement Comparable on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong and AtomicInteger are mutable. The API designers had the forethought to not have Number implement Comparable because it would have constrained implementation of future subtypes. Indeed, AtomicLong and AtomicInteger were added in Java 1.5 long after java.lang.Number was initially implemented. Apart from mutability, there are probably other considerations here too. A compareTo implementation in Number would have to promote all numeric values to BigDecimal because it is capable of accommodating all the Number sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.

    Read the article

  • Type classe, generic memoization

    - by nicolas
    Something quite odd is happening with y types and I quite dont understand if this is justified or not. I would tend to think not. This code works fine : type DictionarySingleton private () = static let mutable instance = Dictionary<string*obj, obj>() static member Instance = instance let memoize (f:'a -> 'b) = fun (x:'a) -> let key = f.ToString(), (x :> obj) if (DictionarySingleton.Instance).ContainsKey(key) then let r = (DictionarySingleton.Instance).[key] r :?> 'b else let res = f x (DictionarySingleton.Instance).[key] <- (res :> obj) res And this ones complains type DictionarySingleton private () = static let mutable instance = Dictionary<string*obj, _>() static member Instance = instance let memoize (f:'a -> 'b) = fun (x:'a) -> let key = f.ToString(), (x :> obj) if (DictionarySingleton.Instance).ContainsKey(key) then let r = (DictionarySingleton.Instance).[key] r :?> 'b else let res = f x (DictionarySingleton.Instance).[key] <- (res :> obj) res The difference is only the underscore in the dictionary definition. The infered types are the same, but the dynamic cast from r to type 'b exhibits an error. 'this runtime coercition ... runtime type tests are not allowed on some types, etc..' Am I missing something or is it a rough edge ?

    Read the article

  • Best Functional Approach

    - by dbyrne
    I have some mutable scala code that I am trying to rewrite in a more functional style. It is a fairly intricate piece of code, so I am trying to refactor it in pieces. My first thought was this: def iterate(count:Int,d:MyComplexType) = { //Generate next value n //Process n causing some side effects return iterate(count - 1, n) } This didn't seem functional at all to me, since I still have side effects mixed throughout my code. My second thought was this: def generateStream(d:MyComplexType):Stream[MyComplexType] = { //Generate next value n return Stream.cons(n, generateStream(n)) } for (n <- generateStream(initialValue).take(2000000)) { //process n causing some side effects } This seemed like a better solution to me, because at least I've isolated my functional value-generation code from the mutable value-processing code. However, this is much less memory efficient because I am generating a large list that I don't really need to store. This leaves me with 3 choices: Write a tail-recursive function, bite the bullet and refactor the value-processing code Use a lazy list. This is not a memory sensitive app (although it is performance sensitive) Come up with a new approach. I guess what I really want is a lazily evaluated sequence where I can discard the values after I've processed them. Any suggestions?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >