text
stringlengths
8
267k
meta
dict
Q: looping through each array to create shapes I'm trying to make the paintCOmponent method loop through each element of an array and call a display method, so far i did this public void paintComponent (Graphics g) { super.paintComponent(g); for(int i = 0; i < drawObjects.length; i++){ drawObjects[i].display(g); } } I also tried a for each loop public void paintComponent (Graphics g) { super.paintComponent(g); for(Shape s : drawObjects) s.display(g); } I get this error with both Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at ShapePanel.paintComponent(ShapePanel.java:70) Could anyone explain to me what am i doing wrong? A: You created an array without filling it in completely. When you create an array, it's full of nulls, and when you try to use the . operator on null, you get the NullPointerException. You either need to make sure the array is fully populated before trying to iterate over it or else add a null check inside the loop so you only try to display() the thing if it's not null. If you really have a variable number of things to display, you should consider using some kind of List, like an ArrayList, rather than an array, as Lists can vary in size and won't contain a null unless you put one there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EXC_BAD_ACCESS crash when switching back and forth between views I'm getting a EXC_BAD_ACCESS crash when switching back and forth between views. I'm having a problem finding the cause of this crash. In the simulator it always goes back to the main.m file and reports the crash in it. But on my device the EXC_BAD_ACCESS show up on my custom UITableViewCell when I release it in the dealloc method. If I enable NSZombieEnabled my app doesn't crash at all. Here is the .h file #import <UIKit/UIKit.h> #define kWinsAmountTagValue 2 // how many wins you have #define kWinningsAmountTagValue 3 // how much money you won @interface MyStatsViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UINavigationBarDelegate, UINavigationControllerDelegate>{ NSArray *list; UITableView *theTable; UITableViewCell *theCell; } @property (nonatomic, retain) NSArray *list; @property (nonatomic, retain) IBOutlet UITableView *theTable; @property (nonatomic, retain) IBOutlet UITableViewCell *theCell; // dealloc and cleanup -(void) dealloc; // misc methods -(void)loadData; // demo data -(NSArray *)tableData; @end Here is my .m file #import "MyStatsViewController.h" @implementation MyStatsViewController @synthesize list; @synthesize theTable; @synthesize theCell; #pragma mark - dealloc and cleanup - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; NSLog(@"Memory Warning"); // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; self.list = nil; self.theTable = nil; self.theCell = nil; } - (void)dealloc { [super dealloc]; [list release]; [theTable release]; [theCell release]; } #pragma mark - misc methods -(void) loadData { self.list = [self tableData]; } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } -(void)viewWillAppear:(BOOL)animated { [self loadData]; [theTable reloadData]; } #pragma mark - Table Data Source Methods -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [list count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier =@"MyStatsCustomCellIdentifer"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier]; NSUInteger row = [indexPath row]; if (cell == nil) { if (row == [list count] -1) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } else { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyStatsCustomCell" owner:self options:nil]; if ([nib count] > 0) { cell = self.theCell; } else { NSLog(@"failed to load MyStatsCustomCell"); } } } // Add custom stuff here for rows //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; if (row == [list count] -1) { cell.textLabel.text = [list objectAtIndex:row]; } else { UILabel *prizeLevel = (UILabel *)[cell viewWithTag:kPrizeLevelTagValue]; prizeLevel.text = [[list objectAtIndex:row] objectForKey:@"prizeLevel"]; UILabel *winsAmount = (UILabel *)[cell viewWithTag:kWinsAmountTagValue]; winsAmount.text = [[list objectAtIndex:row] objectForKey:@"winsAmount"]; UILabel *winningsAmount = (UILabel *)[cell viewWithTag:kWinningsAmountTagValue]; winningsAmount.text = [[list objectAtIndex:row] objectForKey:@"winningsAmount"]; } //NSLog(@"theCell Retain: %i",[theCell retainCount]); return cell; } #pragma mark - Table View Delegate Methods -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - demo data -(NSArray *)tableData { NSArray *prizeLevels = [[NSArray alloc] initWithObjects: @"6-of-6", @"5-of-6", @"4-of-6",@"3-of-6", nil]; NSArray *winsAmount = [[NSArray alloc] initWithObjects: @"0", @"0", @"2", @"100", nil]; NSArray *winngingsAmount = [[NSArray alloc] initWithObjects: @"$0",@"$0", @"$45.50",@"$125.00", nil]; NSMutableArray *myGames = [[[NSMutableArray alloc] init] autorelease]; for (int i = 0; i < [prizeLevels count]; i++) { NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; [dict setObject:[prizeLevels objectAtIndex:i] forKey:@"prizeLevel"]; [dict setObject:[winsAmount objectAtIndex:i] forKey:@"winsAmount"]; [dict setObject:[winngingsAmount objectAtIndex:i] forKey:@"winningsAmount"]; [myGames addObject:dict]; [dict release]; } [prizeLevels release]; [winsAmount release]; [winngingsAmount release]; [myGames addObject:@"Spent: $1250.00"]; return myGames; } @end Any help would be appreciated. A: It is a good practice to clean up class's own variables before calling the super's destructor. A lot more details can be found here: Why do I have to call super -dealloc last, and not first?.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Memory management of vector I have a C++ class with a private "pointer to vector" member pV, I assign a new vector to it in the constructor... pV = new vector<FMCounter>(n, FMCounter(arg1))>; However when I delete in the destructor of the class delete pV; I get a segfault and a message that I'm trying to free pv that wasn't allocated in the first place. I checked that pV->size() was 4K something, so I am sure it was allocated memory by new. A: Pointer members with ownership semantics (allocating in constructor and deallocating in destructor) usually require to write a custom copy constructor and assignment operator (usually known as the Rule of Three), as the compiler generated ones will just copy the pointer member and not its underlying object. So if you at some point copy your containing object, you end up with two objects having the same pointer as member and the one destroyed secondly tries to delete an already deleted pointer. At the simplest you should make sure your copy constructor does something like TheClass::TheClass(const TheClass &rhs) : pV(new vector<FMCounter>(*rhs.pV)) { } and your assigment operator does something like TheClass& TheClass::operator=(const TheClass &rhs) { *pV = *rhs.pV return *this; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7624052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to have a fixed width/height image always centered in a div? I am looking for a way to have an image dynamically centered on any div size. How is this possible? I have posted a jsFiddle for better understanding here http://jsfiddle.net/4exmm/ but as I said the div size is changed using a PHP script. A: Make your div text-align: center. http://jsfiddle.net/4exmm/1/ #image { background: none repeat scroll 0 0 #FFFFFF; border: 1px solid #E1E1E1; float: left; margin-right: 10px; padding: 3px; width: 300px; text-align:center; } A: Just add this rule to #image: text-align:center; A: Why not just text-align: center on the div you could also make your img margin: 0 auto to keep it aligned withing whatever object A: Vertically and horizontally aligned: http://jsfiddle.net/4exmm/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7624056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compiling a .cpp file from the body of another .cpp file I've been working on an application that compiles raw .cpp files and analyzes their outputs, using Microsoft Visual Studio 2010 Command Prompt. I'm having a lot of trouble, and there doesn't seem to be much material about this online. Here's the troublesome code: #include <iostream> using namespace std; ... string name = "cl /EHsc "; name += "example.cpp"; system("setupcppenv.bat"); // A short batch file I wrote to launch the VC++ cmd prompt without launching another instance of cmd system(name.c_str()); When I execute (it attempts to compile example.cpp), I get an error: fatal error C1043: iostream: no include path set I'm not very experienced with batch files, or using the command prompt compiler. What am I doing wrong?! Additionally, is there a different way to compile from inside an application? Thanks! A: Each system() call invokes a separate process, so any environment variables you set in your setupcppenv.bat file will be discarded once that process ends. What you should do instead, is to add the environment variables you are setting in your .bat file to the system environment, or at least to the environment of the cmd instance from where you launch your application, so that they are inherited by the process started by the system() call. A: I don't know what's in setupcppenv.bat I would guess that you're making changes to environment variables in that batch file. What happens is that when the batch script ends, those environment variable changes are being lost becuase they're confined to the batch script's process and any children of that process. A way to set environment variables that will work is to use the setenv() or putenv() functions in your program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mojoportal - do i need the source code? I just inherited a site built on the mojoPortal CMS but we don't have the source code. Do I need it to continue developing the site? It seems like I do, but I'm wondering if there are any workarounds (something stored in the db?) that I'm unaware of considering I'm pretty new to mojoPortal. Thanks. A: Mark B, you can download the mojoPortal source code from every version since 2.2.7.6 here, see the "Other Downloads" box. To find out your current version, go to the Administration->System Information menu in your site, it looks like this:
{ "language": "en", "url": "https://stackoverflow.com/questions/7624085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checkbox actions I need the checkbox to be checked ONLY if $c (POST) is 1 or if $d['is'] is 1. Here is my code: if ( ($d['is'] == 1) OR $c == 1) $data = 'checked="checked"'; The problem is, if checkbox is checked, and I uncheck this and hit the submit button it is still checked because $d['is'] is still 1. So at the end: it should check the box only if $c (POST) is 1 or if $d['is'] is 1 but if $c == 0 (POST) (unchecked checkbox) checkbox shouldnt be checked. It's hard to desribe my problem, so if you don't understand anything, please just post a comment. A: So what you're saying is you want it checked if $c==1 or $d['is'] == 1, but not if $c==0? If this is the case, why does $d['is'] come into it at all? Just have it checked if $c==1 and you're done...
{ "language": "en", "url": "https://stackoverflow.com/questions/7624086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get Amazon EC2 Instance ID via PHP I'm looking to create a PHP script that will echo the unique ID of an Amazon EC2 instance. Anyone know how to do this? Found a way via command line: http://af-design.com/blog/2010/07/27/testing-your-aws-elastic-load-balancer/ Can I just use PHP w/ CURL to submit the query? A: You can use shell_exec to get the instance-id if you are using Amazon Linux AMI. $instance_id = shell_exec('ec2-metadata --instance-id 2> /dev/null | cut -d " " -f 2'); // if its not set make it 0 if (empty($instance_id)) { $instance_id = 0; } echo $instance_id; A: If the entire goal of your PHP script is to run another command, why not just run the other command directly? Why wrap it in PHP? If you need to use PHP for some reason (e.g., to do something with the instance id other than to echo it out, you could improve performance by using PHP's built in HTTP ability instead of running another process: #!/usr/bin/php <?php $instance_id = file_get_contents("http://instance-data/latest/meta-data/instance-id"); echo $instance_id, "\n"; ?> A: If you can get the instance id via the command line, you can get the results of the latter in PHP using the PHP's exec function. When you get the result, just echo it. $instance_id = exec([your command here]); echo $instance_id; Alternatively, after reading the post you linked to, you can also do it this way: $instance_id = file_get_contents( "http://169.254.169.254/latest/meta-data/instance-id"); echo $instance_id;
{ "language": "en", "url": "https://stackoverflow.com/questions/7624091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Issue with qTip2 I have 10 divs. Each one has an attribute data-tooltip="text here". I would something like: $('.my_div').qtip({ content: $(this).attr('data-tooltip'),'bottom middle' }, style: { tip: true, classes: 'ui-tooltip-red' } }); But it doesn't work. How can I get the tooltip text for each div without writing ten times the code with .qtip function? A: It looks like you need to loop with .each() instead. Something like this: $('.my_div').each(function(){ $(this).qtip({ content: $(this).attr('data-tooltip'), style: { tip: true, classes: 'ui-tooltip-red' } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7624092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any possible way to call drawRect from a UIViewcontroller class? I have a UIViewController class called AppController.h, AppController.m. I have thousands of lines of code in there, and that is the only reason why I didn't test this before I asked it. Is there any possible way to use drawRect in a UIViewController? that way I wouldn't have to make more delegates and methods and callbacks. I should have started off using drawRect to handle my drawing code, but I didn't, and there's severe lag with core graphics on the iPad. So, please let me know if there's any way to use drawRect in a UIViewController. Thanks! A: A view controller naturally has a pointer to its view, so of course you can call the view's -setNeedsDisplay method, which will cause the framework to call -drawRect: at the appropriate time. It's a little hard to understand exactly what you're asking, though... are you hoping to do the actual drawing in your view controller? You'd really be working against the framework if you try that -- move the drawing code into your view class instead. A: you just call setNeedsDisplay and you will be requested to draw at the next appropriate time. (read: don't call drawRect: directly) if you really need the behaviour you request, then just call setNeedsDisplay after creating a cached bitmap or CGImage/UIImage which is externally updated (e.g. in your controller logic) and then just draw that image when requested to draw. A: You should (refactor/rewrite and) create a subclass of a UIView (not a view controller) in order to have that view's drawRect delegate called with a proper drawing context when you need to do any drawing. Trying to draw without a proper drawing context can be painfully slow, if at all possible. Technically, you could allocate and create your own bitmap drawing context, put in in a custom object with a drawRect method, and call that drawRect and context. But then it might be just faster to just draw directly into your custom drawing context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTTP server correctness testing I've written a simple HTTP server, and I've stumbled upon a few bugs so far that proved difficult to track down. For example, not adding a blank line between headers and content of a response, or giving an incorrect challenge response for a WebSocket connection. With such bugs, it seems Firefox usually ignores them and displays the page anyway, and Chrome just closes the socket without giving any error message. Is there a simple, free program out there that will place some requests to my server and report every little thing it does wrong, so I can track down these bugs? I've seen a few such programs, but none free, and I don't really want to invest a lot into a hobby project. (Maybe Chrome even has a flag that makes it explain the problem when it closes a socket?) I'm not as concerned about dealing with weird requests from a client (as Apache Test seems to focus on) - what I need to verify is that sane requests get correct responses that won't confuse the client. A: Grab the tests for an existing server and pointing them at yours instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to associate view controller and xib file When I create a uiviewcontroller from the "new file..." wizard with "create xib file" option, I can load it by just SomeViewController *view = [[SomeViewController alloc] init]. But when I rename the xib file name, this code stops working, even though the file owner in the xib is still the right view controller. I found that I can only get the view up by calling initWithNib. I am just wondering what was linking the xib with the view controller behind the scene? Can I still use init to get the xib loaded after renaming the file? Regards Leo A: I can load it by just SomeViewController *view = [[SomeViewController alloc] init]. You can, but (IMO) you shouldn't. The designated initializer for UIViewController is -initWithNibName:bundle:. You might implement an -init method in your own view controller that calls [super initWithNibName:nil bundle:nil], but I think the code is clearer if you stick with the same name. Also, make sure you read the documentation for UIViewController, particularly the discussion, which says: If you specify nil for the nibName parameter, you must either override the loadView method and create your views there or you must provide a nib file in your bundle whose name (without the .nib extension) matches the name of your view controller class. This is why the view controller will load a .xib file that has the same name as the view controller's class (or the name returned by the -nibName method, as explaind a little further on in the docs). In short, UIViewController is functioning exactly as documented.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Security for AJAX requests from the client side accessing an API Let's say you want a third party site to copy and paste a snippet of javascript code you provide. This code uses an AJAX request to access a JSON API on your servers. How would you implement security so that, while associating API usage to a website that has signed up and received an API key, you would effectively disallow a site to abuse another site's API key/usage? Is this security not possible from the client side? Must the site access the API from the server? A: You can also check HTTP referrer of the request on your server site. I don't think changing javascript code can fake it. But it cannot stop someone sending custom package from a custom browser or some http client. Implementing a server-side solution is possible and not too hard, but it will stop many sites from using your script. You can let them send the request from their servers or let them keep the key on their servers, hash the key before sending it to the client (the hashed key changes after a time interval)... A: You can just check window.location, or some component thereof. A: The only way I can think of to enforce such security would be to go by the IP address, but that is risky at best, as there are many reasons why it would be a bad design. This would be the security on the server-side protecting the javascript file. You could just have a web service serve up the javascript so it can do the check before ever sending the file to the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Session handling in GWT RequestFactory Can somebody show me a simple example about session handling with GWT RequestFactory. Maybe it is very simple, but I can't figure it out. I read somewhere that I should use ThreadLocal. Well I did. Here is my code: public class EC_RequestFactoryServlet extends RequestFactoryServlet { private static final ThreadLocal < HttpServletRequest > uniqueReq = new ThreadLocal < HttpServletRequest > () { @Override protected HttpServletRequest initialValue() { return null; } }; @Override protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { uniqueReq.set(req); super.doPost(req, res); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { uniqueReq.set(req); super.doGet(req, res); }} And this saves the session: public class Authentication { public static void SetLoggedInUserToSession(User user) { EC_RequestFactoryServlet.getThreadLocalRequest() .getSession().setAttribute("LOGGED_IN_USER", user); } public static User GetLoggedInUserFromSession(){ return (User)EC_RequestFactoryServlet.getThreadLocalRequest() .getSession().getAttribute("LOGGED_IN_USER"); }} After the login, it is okay, but after another request, the session is empty. So what am I missing? Or is it a better way? A: Or you could just use RequestFactoryServlet.getThreadLocalRequest(). A: Oh, it's working now. I made a silly mistake somewhere else in the program. The code above it's working fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: W3 VALID cross browser css gradient, I am trying to find html conditional statement so that I can reference the required additional .css file. Opera, Ie8, Safari. I am using: background: -moz-linear-gradient(#ADD58A, #FFFFFF); for Firefox which is great. But having other browser css properties causes W3 css validation to fail! I believe with html conditional statements this can be done with valid code. Before you reply, yes I have looked at pie, i do not have the 3 green ticks of validation when using pie, hence wanting to use html conditional rather than having the browser 'drop' styles. A: The Jigsaw CSS3 validator should have an option for triggering warnings instead of errors on vendor extensions. Assuming you haven't used any other non-standard styles, your CSS should pass with a green, albeit with a few warnings, but nothing more. As to why Daniel A. White says not to worry about validation, well, "W3C valid cross-browser CSS3" is an oxymoron. In 2011 you simply can't achieve such a thing with most CSS3 features yet. Yes, validate your code for maximal cross-browser interoperability. But in the real world, that's only applicable to CSS2 stuff right now. When it comes to CSS3 features where the spec itself isn't yet finalized, let alone browsers' implementations (however they interpret the incomplete spec), validity doesn't make sense yet. Things like border-radius may work if you ignore less recent (I wouldn't say older) versions of most modern browsers, since the latest versions of every major browser now support the official property name, but nobody in the world has implemented the extensionless versions of any CSS gradients yet. You can tell them to trigger only warnings in the validator, or if you're so anal that you don't even want warnings, perhaps wait until next year. Hopefully things will be stable enough and major browsers will have dropped their prefixes for CSS3 gradients. A: the -moz is a vendor specific prefix for Firefox. I wouldnt worry about the css validation. Define the gradient with these too. * *linear-gradient - the eventual standard *-o-linear-gradient - opera *-webkit-linear-gradient - safari/chrome *-ms-linear-gradient - ie
{ "language": "en", "url": "https://stackoverflow.com/questions/7624115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Somehow accessing Javascript output? So, Say there's a remote PHP file that's generating some output in JavaScript. I can do <script src='some_file.php type='text/javascript'></script>, and the code will run, but when I click View Source it just shows the above code. Is there any way I can access the actual code that that PHP file is running? Also, when I right click on the output of the javascript and go to 'this frame' -> 'view frame source' I get the actual output. I want to be able to use it. A: This is inherently impossible. PHP runs on the server; the browser is never aware of it. A: Nope, PHP runs on the server and generates a html code as shown in your browser. Do you want it to show?
{ "language": "en", "url": "https://stackoverflow.com/questions/7624118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is root required for listening on the loopback in Java? How come when I try listening to a loopback host in Java (using a plain old socket), it requires root access, yet if I use nio, it doesn't? If I tried listening on any other language on the loopback, it doesn't require any elevated privileges too. This is my code right now: import java.net.*; class Test { public static void main( String[] args ) throws Exception { ServerSocket server = new ServerSocket( 80 ); while( true ) { Socket socket = server.accept(); System.out.print( "." ); } } } When I run this as a normal user, this exception is thrown: Exception in thread "main" java.net.BindException: Permission denied. Yet when I run this as root, it works fine as expected. A: You need root permissions to bind a socket in the port range 0-1023. These ports are used for common services like HTTP and SSH and it would be dangerous to allow random users to bind their arbitrary applications to these ports. See wikipedia: http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports Edit: Keep in mind that arbitrary applications can connect to well-known ports, just not bind to them. Otherwise users would not be able to run honest programs ssh or mozilla. This is likely why you are not able to reproduce this error in other languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error in XML Code? So I just finished creating a new UI in DroidDraw (relativelayout throughout), and I've imported it into my main.xml file. The problem is, whenever I run "check for xml errors" the output return states "cvc-elt.1: Cannot find the declaration of element 'RelativeLayout'. [8]" It's really bothersome, and I think it's what's causing my app to force close on run (there are no errors in the actual code itself). I'm fairly new to the whole android dev scene, so it's entirely likely that this is supposed to happen and I'm just being stupid. In any case, here is the block of text in which the error is returned: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/widget31" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"> </RelativeLayout> Any help would be much obliged. A: Yeah, I don't believe any of the tag names are actually declared. Notice that you're importing the Android namespace as android, so things prefixed with android: are declared. Anything that's not prefixed with android: isn't really being declared. This isn't a problem. Some would say it's a little sloppy of Google, since the XML won't validate, but the Android compiler doesn't have a problem with it. So I think you need do start looking elsewhere for the reason your app crashes on startup. (Are you developing in Eclipse? Run in debug mode and/or watch LogCat.) Incidentally, the reason that the element names aren't declared is because you can use your own. For example, if you write your own subclass of Button with the fully qualified name com.mydomain.MyAmazingButton, you can use it in your layouts like this: <com.mydomain.MyAmazingButton android:layout_width="..." android:layout_height="..." /> Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to limit a RegEx to With or Without a space, including a '-' without spanning more than 2 words Thankyou in advance, complete noob at regular expressions here! I'm searching HTML for a model number, for example. "ER-A320" Which can be expressed on a webpage as "ERA320", "ER A320" or "ER-A320" I've got stuck at about this: ER(\s*|.*)A320 I know this is completely wrong, the above expression isn't limited to 1 space, it will span a whole line unfortunately. e.g. "ER all the way to A320" And won't pick up no-space e.g. "ERA320" And addes a nasty '-' sign to the end. Thanks A: This regular expression should work: ER[ -]?A320 A: I don't know exactly what you're looking for, are you looking for this exact model "ERA320" or "aaa000". If you're looking for a pattern, use this: [A-Z]{2}[\s|\-]?A[0-9]{3}, assuming you're looking for "XXANNN", X means A-Z, A means A and N is a number. Otherwise use this: ER[\s-]?A320.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding the owner and group of a file (as a string) I am trying to get a C string of the owner and group of a file, After I do a stat() I get the user ID and group ID, but how do I get the name? A: You can use getgrgid() to get the group name and getpwuid() to get the user name: #include <pwd.h> #include <grp.h> /* ... */ struct group *grp; struct passwd *pwd; grp = getgrgid(gid); printf("group: %s\n", grp->gr_name); pwd = getpwuid(uid); printf("username: %s\n", pwd->pw_name); A: Try using getpwuid(); http://linux.die.net/man/3/getpwuid
{ "language": "en", "url": "https://stackoverflow.com/questions/7624127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Doubled quotes when using sqlite_escape_string I'm escaping blog posts with sqlite_escape_string(), and connecting to the database using the old object-oriented way. (Yes, I know, I should use PDO, I'll get to that later; converting this script would take quite a while.) When I have data like: It's raining cats and dogs!, it saves this to the database: It''s raining cats and dogs!. The problem is that it comes out of the database like that, and stripslashes() doesn't undo it. Magic Quotes is turned off. Every time I recall that data from the database and save it again, it adds more single-quotes. How would I stop it from doing that? Here's the abridged submission code: # Grab the data from form and escape the text $title = sqlite_escape_string(strip_tags($_POST['title'])); $text = sqlite_escape_string($_POST['text']); # Query for previous data $result = @$dbh->query("SELECT * FROM posts WHERE id=".$id); # Fetch previous data while($past = $result->fetchObject()) { $ptitle = $past->title; $ptext = $past->post; } # Set a base query to modify $base = "UPDATE posts SET "; # Run through scenarios if(stripslashes($ptitle) !== $title) { $base .= "title='".sqlite_escape_string($title)."', "; } if(stripslashes($ptext) !== $text) { $base .= "text='".sqlite_escape_string($text)."', "; } } # Remove last comma & space $base = substr($base, 0, -2); $base .= " WHERE id=".(int)$id; # Execute modified query @$dbh->query($base); And here's the code that reads the data back: # Sanitize and set variables $start = (int)$start; $limit = (int)$limit; $start = ($start - 1) * $limit; $dbh = $this->dbh; $this->limit = $limit; # Query the database for post data $this->result = $dbh->query("SELECT * FROM posts ORDER BY id desc LIMIT ".$start.", ".$limit); public function loop() { # Do we have any posts? if(!empty($this->result)) { # Convert query results into something usable $this->cur_result = $this->result->fetchObject(); # This while loop will remain true until we run out of posts while($post = $this->cur_result) { return true; } # At which point it turns false, ending the loop in the template file return false; } # We don't have any posts :( else { return false; } } public function content($excerpt = '') { # We didn't screw up and keep an empty query, did we? if(!empty($this->cur_result)) { echo stripslashes($this->cur_result->post); } } A: I suspect you have magic_quotes_sybase on. Post the values of: echo ini_get('magic_quotes_sybase'); echo get_magic_quotes_gpc() // Probably not relevant, but may as well be thorough. Both should be 0. EDIT: You're clearly double-escaping both $text and $title: $title = sqlite_escape_string(strip_tags($_POST['title'])); $text = sqlite_escape_string($_POST['text']); ... if(stripslashes($ptitle) !== $title) { $base .= "title='".sqlite_escape_string($title)."', "; } if(stripslashes($ptext) !== $text) { $base .= "text='".sqlite_escape_string($text)."', "; } As you know, prepared statements are the best solution. But if you're going to use escaping, escape every variable at the last possible moment. That's right before the DB call, not when you're reading input. If you're using escaping or prepared statements correctly, you will never have to call stripslashes or remove extra quotes when reading from the db. A: It looks like you are escaping the data twice. At the beginning of your code you have: $title = sqlite_escape_string(strip_tags($_POST['title'])); $text = sqlite_escape_string($_POST['text']); And then in the insert you have: if(stripslashes($ptitle) !== $title) { $base .= "title='".sqlite_escape_string($title)."', "; } if(stripslashes($ptext) !== $text) { $base .= "text='".sqlite_escape_string($text)."', "; } Remove the sqlite_escape_string from the if statements and I think the result will come out correctly now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validating and matching a specifically formatted string I have the following regex pattern which works fine: #^(.+?)=(.+?)$#D However I want to extend it so it supports the following example inputs: some text=some more text;something some text=some more text;something;something some text=some more text;something;something;something As you can see from the above example inputs the semi-colon (;) character is being used as a seperator and is used to seperate text (it is between text). I guess I can use the following regex pattern below - it will only work when theres is one, but won't if there is more text seperated by a semi-colon... I know I can probably add something like [;]* but I want the validation to be strict to ensure it is in that format (so there can't semi-colons just anywhere they have to be between text only). #^(.+?)=(.+?);(.+?)$#D If it helps I'm currently using PHP's preg_match() function (so the matches can be utilized in array() form). I'm not limited to using regex as that was the only method I could think of, therefore I'm welcome to other methods or any method which can be used alongside this (providing the results can be easily attained as an array LOL). Also I'd like to note whilst writing this (and flicking through the tagging system) I had a news flash...perhaps using preg_match_all() with the PCRE recursive functionality could be a possible solution? Appreciate all responses and thank you for all help. A: Why not just use explode() on the second half to explode on any semicolons? A: You can try this regex: #^(.+?)=((.+?)(;)?)+$#D A: Try: #^(.+?)=(.+?)(;(.+?))+?$#D A: I would try: #^(.+?)=(.+?)(?:;(.+?))+?$#D
{ "language": "en", "url": "https://stackoverflow.com/questions/7624145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I call static method for a generic type in a class? interface TerminationCondition { static bool IsSatisfied(some parameters); } Let's say some classes A and B implement this interface. Some other class C has a generic type: class C<termCondition> where termCondition : TerminationCondition I need to call IsSatisfied from C accordingly, whether I have passed A or B for the generic type. For some reason it is not possible termCondition.IsSatisfied(). To summarize, the question is How do I call static method for a generic type in a class? A: This is not possible. In fact, you can't have static methods in an interface at all. A: Since termCondition is required to be of type TerminationCondition, you could simple have IsSatisfied be an instance method of the classes that implement that interface. There's no need to have that method be static at all. A: bool result = C<TerminationCondition>.IsSatisfied(); As @SLaks pointed out, you can't have static methods in an interface. Having them in a generic type tends to be awkward. @Austin also makes a good point. You can have static generic methods (normally in non-generic types); these have their uses. public static bool IsSatisfied<T>(T condition) where T: TerminationCondition
{ "language": "en", "url": "https://stackoverflow.com/questions/7624151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to use context processors in Django without a request object? The Django documentation describes the use of context processors when you have a request instance -- typical usage is to use RequestContext instead of Context when rendering a template. But what if you want context processors, but are not operating within the request/response cycle? An example use case is rendering templates in response to signals or management commands for email reports. It's very inconvenient to have to either pre-render any content within a request cycle (and thus lose the advantage of loose-coupling that signals provide), or to have to manually invoke the context, such as "site", for every render invocation. Is there a way to get the default context processors when there is no request instance? A: Well, you can get what they are via ...settings.TEMPLATE_CONTEXT_PROCESSORS, but you can't use them since you need a request instance in order to do so. A: If rendering your templates requires the request, why not pass that in as the sender param when sending the signal def my_view(request): my_signal.send(sender=request, foo=True) return HttpResponse("YadaYadaYada")
{ "language": "en", "url": "https://stackoverflow.com/questions/7624155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Updating 'hidden' binary data in ASP.NET MVC on HTML5 'drop' event I need to figure out how to base64 encode the response from an HTML5 FileReader ... Here's the problem - I've added a 'drop' event listener on a div so you can drag-n-drop an image file on to my page ... this is an ASP.NET MVC3 Razor form which has an @html.HiddenFor(...) field which contains a byte array which represents an image ... If the user drops a file on to my div, then I want to update the 'value' of my hidden input field. My client-side drop handler looks a bit like this: dropArea.addEventListener("drop", function (evt) { var draggedFiles = evt.dataTransfer.files; if (typeof (draggedFiles) != "undefined") { xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { var hiddenInput = document.getElementById("myMvcHiddenInputField"); hiddenInput.value = base64.encode(e.target.result); }; })(draggedFiles[0]); reader.readAsBinaryString(draggedFiles[0]); } } xhr.open("post", "/MyController/SetTempImage", true); xhr.setRequestHeader("Content-Type", "multipart/form-data"); xhr.setRequestHeader("X-File-Name", draggedFiles[0].fileName); xhr.setRequestHeader("X-File-Size", draggedFiles[0].fileSize); xhr.setRequestHeader("X-File-Type", draggedFiles[0].type); xhr.send(draggedFiles[0]); evt.preventDefault(); evt.stopPropagation(); } }, false); ... the problem lies in how I'm handling the response from the FileReader ... I need to re-encode the results in a way that ASP.NET is expecting the hidden field (base64.encode is a jquery library I downloaded ... I'm pretty sure it's not what I need here, as I don't think it is designed to cope with encoding binary data) I guess my question is, when updating 'hidden' byte arrays in MVC pages, how do I encode file data on the client so that it can re-integrate with my model data when it's posted back to the server? ... It's late ... I suspect that sounds like gibberish ... but if anyone can make sense of my problem, your help would be greatly appreciated. A: I know this is old, but try: reader.readAsDataURL(draggedFiles[0]);
{ "language": "en", "url": "https://stackoverflow.com/questions/7624157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHPMailer: Hide body text from email address I was wondering if it was possible to hide certain parts of the body message in PHPMailer depending on the email address. I have 2 email addresses that are being sent the message, and the second email address needs to only see parts of what the first email address is seeing. Is there a way to identify that I only want the first email address to see the content. For example: $mail = new PHPMailer(); $mail->AddReplyTo($fromemail, "".$fromname.""); $mail->AddReplyTo("[email protected]", "Company ABC"); $mail->SetFrom($fromemail, "".$fromname.""); $mail->AddAddress("[email protected]", "Company ABC");//would see the whole email $mail->AddAddress("[email protected]", "Partner Company");//would only see 1st paragraph $subject = "Email Subject"; $mail->AltBody = "To view this message, please use an HTML compatible email viewer"; $mail_body .= " <html> <head> <title>Email Message</title> </head> <body> <p>This would be a paragraph that both email addresses see</p>"; if ($mail->AddAddress == "[email protected]") { $mail_body .= "<p>This would only be seen by the first address</p>"; } $mail_body .= "</body> </html>"; A: This will not be possible without sending two different messages to the recipients, having different body content. Although some mail clients out there might still support and execute Javascript without user intervention (I doubt it though), it could not be relied on at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I upgrade to IIS 7 in order to run ASP.NET application? On the IIS download page there is no one installer just a lot of items that could be installed. What do I need to install to run a ASP.NET application? I'm running Windows 7. A: IIS is part of Windows. Go to Programs and Features and click Turn On or Off Windows Components All of those downloads are optional addons that you probably don't need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make PlotLegend work with ParametricPlot in Mathematica? It seems I cannot use PlotLegend with ParametricPlot. Here's what I tried: ParametricPlot[{Sin[t], Cos[Sqrt[t]]}, {t, 0, 2 Pi}, PlotLegend -> {"My Plot"}] A: If you call the PlotLegends package first, it should work, though you might be better using the ShowLegends version than the PlotLegend option, for more control: Needs["PlotLegends`"] ParametricPlot[{Sin[t], Cos[Sqrt[t]]}, {t, 0, 2 Pi}, PlotLegend -> {"My Plot"}] ShowLegend[ ParametricPlot[{Sin[t], Cos[Sqrt[t]]}, {t, 0, 2 Pi}], {{{Graphics[{Blue, Disk[{0, 0}, 1]}], {Sin[t], Cos[Sqrt[t]]}}}}]
{ "language": "en", "url": "https://stackoverflow.com/questions/7624169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SQL Query to get number of appearence of a integer in Columns Values (Or Tips to do it in code) The title is a little confusing but I couldn't find a better one. here is what i want to do. I have a Table of this form: Name | Gender | Answers Tom | Male | 1,2,3 Kate | Female | 1,4 John | Male | 2,4 Maggy | Female | 1,3 I have 2 questions: 1) If there a query to get the number of integers appearing in the Answers column? In our example: Answer | Count 1 | 3 2 | 2 3 | 2 4 | 2 2)If the above is possible is there a way to breakdown by gender: In our example: Gender | Answer | Count Male | 1 | 1 Male | 2 | 2 Male | 3 | 1 Female | 1 | 2 Female | 3 | 2 I hope I was clear. I am using C#, and reading data from an excel sheet using an OleDB Connection. If there is no way to do it via SQL Query, how to do it in C# code. (I use a Datatable to fill the data I read) Thank you very much for any help A: You should not store multiple values in a field, you should normalise the table using a separate table for the answers: Person: Id Name Gender 1 Tom Male 2 Kate Female 3 John Male 4 Maggy Female Answer: Id Answer 1 1 1 2 1 3 2 1 2 4 3 2 3 4 4 1 4 3 Now you can easily get the number of answers using count selecct p.Name, count(*) as Cnt from Person p inner join Answer a on a.Id = p.Id group by p.Name You can just as easily group by gender and answer: selecct p.Gender, a.Answer, count(*) from Person p inner join Answer a on a.Id = p.Id group by p.Gender, a.Answer A: (I'll try to answer this in MSSql) You can manufacture a split function in sql like the example seen here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648 Note that you can modify the first example to this (it's the GroupOn code, which would be your "male" or "female" element): CREATE FUNCTION dbo.Split ( @RowData nvarchar(2000), @SplitOn nvarchar(5), @GroupOn nvarchar(100) ) RETURNS @RtnValue table ( Id int identity(1,1), Data nvarchar(100), GroupOn nvarchar(100) ) AS BEGIN Declare @Cnt int Set @Cnt = 1 While (Charindex(@SplitOn,@RowData)>0) Begin Insert Into @RtnValue (data) Select Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1))) Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData)) Set @Cnt = @Cnt + 1 End Insert Into @RtnValue (data, @GroupOn) Select Data = ltrim(rtrim(@RowData)) Return END And then you could just count and group on accordingly. EDIT Fixed a misspelling above. A: This query is for question 2. It can be trivially modified to match result from question 1. declare @t table ( name varchar(50), gender varchar(50), answers varchar(50) ) insert into @t select 'Tom', 'Male', '1,2,3' union select 'Kate', 'Female', '1,4' union select 'John', 'Male', '2,4' union select 'Maggy', 'Female', '1,3' select gender, answer, count = count(*) from ( select gender, -- here t2.c is an xml column, which holds values of this sort <a>1</a> -- 'data(.)' gets the value from the <a> tag answer = cast(t2.c.query('data(.)') as varchar) from ( select name, gender, -- represent answers in the xml, proper for xquery node function -- for example <root><a>1</a><a>2</a></root> answers = cast('<root><a>' + replace(answers, ',', '</a><a>') + '</a></root>' as xml) from @t ) t1 -- xquery nodes function reads the xml and -- in this case for each tag <a> it returns a separate row cross apply answers.nodes('/root/a') t2(c) ) t group by gender, answer order by gender desc, answer Note: the result will not match the one that you provided in part 2, because your result is not corresponding to your example data, if I understood your problem correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specify SQL Server connectionstring on a messed up network The current scenario before i start asking my question * *A C# Winforms application needs to be deployed on our LAN. *The network contains 200+ computers running Windows XP (& above) having the same domain/workgroup. *Unfortunately, there's still some mixups and IP conflicts throughout the network. *The network still works !!... (ahem..) *A central server (with unique name & IP) hosts the database (SQL Server 2008 R2) *The application has a provision to specify the connectionstring on the client machine *The application validates this string (open > close connection else exception) and stores in a local file. Now, My problem is that... The application connects successfully to the server (open > close connection) during the checking phase, but fails when there's actual datasets are to be fetched from the server. * *Which is the most reliable way to address the server in the connection string in this mixed up scene ? This holds true even if i use the "sa" account, i have used machine name / IP to address the server A: When you say your application "fails when there's actual datasets are to be fetched", what do you mean? What's the error? Encapsulate your SqlDataAdapter.Fill() method in a try catch block and out that error to a log or the GUI for quick debugging purposes. What does the error say? Is it a network or instance related issue..? The application connects successfully to the server Are you talking about the server as a physical machine, or are you talking about the SQL Server instance that houses the database you are trying to connect to? Here's a big "gotcha". If you are using a named instance, then you need to make sure that the SQL Server Browser service is running on the server that houses the SQL Server instance(s). That is the service that, when reached out over port 1434, tells the application what dynamic port the named instance is listening to. Also, your connection string could have some issues in it. Long story short, it is almost impossible to tell what your problem is with the very little given information. It is all just guessing troubleshooting here. Please give me more information. Edit: if you have a DHCP/DNS server on your network, then I don't see why you should be getting "messed up" workstation network issues, at least with IP assigning and name resolution. Your workstations need to be able to resolve the server name to reach it. But it doesn't sound like that's your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I create a java GUI so when I double click a .jar it launches a java GUI that acts like a console I have some code that requires input and output and I want to make this into a .jar file that when double clicked can launch a GUI console like application that will work with my code. The closest I've been able to find is this Create Java console inside a GUI panel But this doesn't really help because I also want the user to be able to input. Lets say I have this code below import java.util.Scanner; public class Name { public static void main(String[] args) { Scanner x = new Scanner(System.in); System.out.println("Please enter your name: "); String name = x.nextLine(); System.out.println(name); } } I want this to be able to be run in a console like environment but through a java GUI so I can use a .jar file. And please don't recommend a batch file because that is not what I'm looking for. For the code above here is exactly what I want. I want to be able to have this work exactly how it would normally when double clicked on as a batch file. Except I want it to be executed from a .jar file so I could just double click that and launch it from a mac or a pc in any directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does my index page disappear only in Safari? I have tried everything I can think of to track down this issue but can't turn up anything. I'm using the jquery address plugin for my site. After I login to my site the user gets redirected to the home page at which time I initialize the jquery address plugin. This works great on FF, IE, and Chrome, but Safari starts to load the page and then goes blank for some unknown reason. The last block of code it hits is this: $('a').address(); $.address.init(function(e) { // Address details can be found in the event object }); // Handle handle change events $.address.change(function(e) { var urlAux = e.value.split('='); var page = urlAux[0]; var arg = urlAux[1]; if (page == "/foo") { /* load foo */ } else if (page == "/bar") { /* load bar */ } else if (page == "/") { /* my index page loaded here */ $.address.title("Home Page"); $("#loadImage").show(); $('#main').load("home.php", function (e) { e.preventDefault(); $("#loadImage").hide(); }); } }); This get called outside of document ready. Any idea what might cause this issue in Safari? A: Here's what I would check: * *Check for js errors or warnings *Check for any failed net requests *Confirm that page and arg are both defined *Make sure all caching is disabled *Change the contents of home.php temporarily to make sure it's not something weird happening inside that request. *Check that it's working, but just being hidden (you are calling .hide() on an element...) Remember: the Developer Tools are your friend (Command+Alt+i) Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7624188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Group Listbox for Windows Phone 7? I'm looking for a way to group items similar to the way the applications below have it for there grouping. Is it possible to create a group listbox using View Models? I plan on having multiple customer groups for example: "AAA" (Group) -- "XDN" (Contact) "NCB" (Group) -- "XDN" (Contact) etc... I don't want it to be seperated by letters but instead by group names. Is this possible? Thanks. A: Nothing prevents you from creating a custom ordered collection that suits that precise purpose. Here's the collection type I usually use for it, when integrating it with the LongListSelector in the Silverlight Toolkit You'll obviously have to modify the GroupHeaderTemplate but that's very easy. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace LongListSample { public class LongListCollection<T, TKey> : ObservableCollection<LongListItem<T, TKey>> where T : IComparable<T> { public LongListCollection() { } public LongListCollection(IEnumerable<T> items, Func<T, TKey> keySelector) { if (items == null) throw new ArgumentException("items"); var groups = new Dictionary<TKey, LongListItem<T, TKey>>(); foreach (var item in items.OrderBy(x => x)) { var key = keySelector(item); if (groups.ContainsKey(key) == false) groups.Add(key, new LongListItem<T, TKey>(key)); groups[key].Add(item); } foreach (var value in groups.Values) this.Add(value); } } public class LongListItem<T, TKey> : ObservableCollection<T> { public LongListItem() { } public LongListItem(TKey key) { this.Key = key; } public TKey Key { get; set; } public bool HasItems { get { return Count > 0; } } } } Example of use:
{ "language": "en", "url": "https://stackoverflow.com/questions/7624189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I parse XML from a script tag in an HTML doc? I've been using Jsoup to scrape HTML data from a website, but there is one section of XML inside a javascript tag that I need to get because it has a bunch of URLs I need to pull out and download the images. Here is what it looks like: <script type="text/javascript"> var xmlTxt = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><mediaObject><mediaList rail="1"><carMedia thumbnail="http://images.blah.com/scaler/80/60/images/2011/9/22/307/179/22343202654.307179719.IM1.MAIN.565x421_A.562x421.jpg" url="http://images.blah.com/scaler/544/408/images/2011/9/22/307/179/22343202654.307179719.IM1.MAIN.565x421_A.562x421.jpg" type="INV_PHOTO" mediaLabel="" category="UNCATEGORIZED" sequence="2"/></mediaList></mediaObject>';' That is followed by a whole bunch of javascript code inside the script tag. What is the best way to extract those URLs from the page if I have a Jsoup Document? If I can't do it with Jsoup, how can I do it? The problem is that the images are held in a carousel and so the HTML on the page only shows the source for the ones currently displayed in the carousel. A: Fist, you can get xmlTxt into java using javascript binding. see http://developer.android.com/guide/webapps/webview.html#BindingJavaScript Second, parse your xml. I'm not sure you can use Jsoup in general XML(not HTML). If you can't , you can use android builtin xmlpullparser ( http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html ) or other xml libraries. A: Well, I did it the dirty way but it should work. I was hoping there was a more elegant solution, but for now I just converted the doc to a string ( doc.toString() ) and then get the start and ending index of the starting and ending XML tags that I want. From there I should be able to use the built in Java XML parser to do the rest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624191", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single step trap and sysenter on windows 7 Working on my own little user mode debugger, mainly for learning purposes. I am running into a problem here; I understand that a blocked syscall means that the calling thread must wait for the routine to finish. I seem to have an issue with having the trap flag set while hitting one of these. First question, would this normally cause a crash? Second, what is a good method to 'step-over' these. That is, if they are actually the culprit here. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7624193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you link correctly in C to stop symbols being stripped? I'm having some trouble linking properly against libraries in C. I'm sure this is one of those arcane C linking rules I don't fully understand, but I can't figure it out. I have libn, which I compile into a static libary, libn.a nm libn shows: doug@ninja:~/projects/libnw/build$ nm ../../libn/build/libn.a |grep nIndex 00000034 T nIndex 00000000 D nIndex_ 00000026 T nIndex_finalize 00000013 T nIndex_init 00000000 T nIndex_map I also have libnw, which depends on libn. nm on libnw shows: doug@ninja:~/projects/libnw/build$ nm libnw.a |grep Index U nIndex However, when I compile a programming linking against libnw and libn I get: doug@ninja:~/projects/libnw/build$ make [ 70%] Built target nw [ 80%] Built target test-template Scanning dependencies of target test-Core [ 85%] Building C object tests/nw/mvc/Core/CMakeFiles/test-Core.dir/Tests.c.o [ 90%] Building C object tests/nw/mvc/Core/CMakeFiles/test-Core.dir/test.c.o Linking C executable test-Core ../../../../libnw.a(Impl.c.o): In function `nwCore__Impl_init': /home/doug/projects/libnw/src/nw/mvc/Core/Impl.c:76: undefined reference to `nIndex' collect2: ld returned 1 exit status make[2]: *** [tests/nw/mvc/Core/test-Core] Error 1 make[1]: *** [tests/nw/mvc/Core/CMakeFiles/test-Core.dir/all] Error 2 make: *** [all] Error 2 The reason, is quite clear. When Tests.c --> Tests.c.o, it's not picking nIndex up as a symbol it needs to keep: doug@ninja:~/projects/libnw/build$ nm tests/nw/mvc/Core/CMakeFiles/test-Core.dir/Tests.c.o U MyController 000005a4 T Tests 00000000 D Tests_ 00000125 T Tests_can_attach_controller 00000080 T Tests_can_create_core 000003d3 T Tests_can_handle_native_event 000001c8 T Tests_can_set_controller 00000322 T Tests_can_update 00000000 t Tests_core_factory 0000056c T Tests_finalize 000005c0 T Tests_getType 0000048c T Tests_init U nFactory U nTest U nType_nalloc U nType_nfree U nwCore U nwDummyContext_getType U nwDummyEvents_getType U nwDummyRender_getType U nwIContext_getType U nwIEvents_getType U nwIRender_getType (Notice the total absence of U nIndex in the tests object file). So, I can fix this easily by adding a call to nIndex() in my tests script, but that doesn't solve the basic problem: Program depends on liba depends on libb, liba has missing symbols from libb it needs to resolve, but program has no references to those symbols, so they seem to be being stripped. What am I doing wrong? (Yes, I'm building using cmake and depending on the statically built versions of libn and libnw). Edit: Now with linker line: /usr/bin/gcc -std=c99 -g CMakeFiles/test-Core.dir/Tests.c.o \ CMakeFiles/test-Core.dir/test.c.o \ CMakeFiles/test-Core.dir/helpers/MyController.c.o \ CMakeFiles/test-Core.dir/helpers/MyModel.c.o \ -o test-Core -rdynamic \ /home/doug/projects/tapspin-android/source/deps/libn/build/libn.a \ ../../../../libnw.a A: I don't see you link line so i's hard to tell for sure but this seems like it could be an ordering problem If all of the symbols that are needed by libb are in liba, then you should list libb first, so that they are listed as symbols-to-be-resolved, and when libb is visited they will be resolved. This is not stripping per-se, it is just not including (i.e. it is omission not an active removal, am I splitting hairs? maybe) Also, sometimes if there is a cyclical dependency (liba needs some symbols from libb and libb needs some symbols from liba) one has to list the libs multiple times (this is not a cmake answer as I do not use cmake, but have used linkers for many years, this where is a common error). Note that unlike symbols from libraries, all symbols from object files are linked Easiest fix to try first is just swap the order of the two libs A: Since it is a problem of linking order, you can also solve it by using --start-group --end-group GCC: what are the --start-group and --end-group command line options? It works as long as we are speaking about static libraries/archive files. A: To find the correct order of dependent libraries, the following *nix command pipeline can be used: lorder libA.a libB.a ... | tsort If one gets an error about a cyclical reference, then although the above GCC kludge using --start-group and --end-group will work, or simply listing the offending libraries a second time, one really ought to fix the libraries so they don't have cyclical dependencies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Find all strings wanted and select them with QPlainTextEdit::setExtraSelections() I'm trying to highlight all strings find in a QPlainTextEdit widget , but find() will only return the first result. The following code isn't working out , why ? (textview is a class derivated from QPlainTextEdit) And please don't ask me to use QSyntaxHighlighter to set up colors , it's different. QList<QTextEdit::ExtraSelection> extraSelections; textview->moveCursor(QTextCursor::Start); while ( textview->find(key) ) { QTextEdit::ExtraSelection extra; extra.cursor = textview->textCursor(); extraSelections.append(extra); } textview->setExtraSelections(extraSelections); A: It's usually good to provide a little more detail about what doesn't work :) * *What text have you tried in the QPlainTextEdit? *What are you using for a key? *Can you clarify what find finds when running with the text specified in the first two items above? *Do you actually end up with a list of extra selections? *Is the lack of visible highlighting the only thing not working? I tried your code and it seems to find all the text instances correctly. The problem seems to be that you aren't actually setting any values for the format member of extra. After you set extra.cursor, try setting extra.format.fontUnderline(true); just to see if it is having any effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Texturing with Slick Library? So I have 2 issues. * *I have a 16x16 image that works fine... When I say the info the image size is 16x16 and the texture size is 16x16 I have a 100x100 image that when I say the info... The image size is 100x100 but, The texture size is 128x128... I don't know why this is but it screws everything up! * *The 16x16 is pixely (What I want) but I want to display it on a 100x100 surface and it blurs it! I don't want it blurred I want it to look like the original. Is this possible? A: You need to use a power of 2 texture when using basic OpenGL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Comparing two times using strtotime and time in PHP I have a start time of 3:30 pm and end time of 4:14:59 pm. Both the values are strings so I used strtotime() to convert them. I'm not sure it is taking into account the am while testing. I want to get the current time and check to see if the current time is between those two values. $server_time = strtotime("3:55 AM"); if($server_time > strtotime($start) && $server_time < strtotime($end)) { echo "TRUE"; } else { echo "FALSE"; } This should be false considering my server time is AM and my start and end are both PM. This is returning true though. Is there a better way to handle this? Any help would be appreciated. A: strtotime is extremely picky, i tend to use it only for mysql date conversion to timestamp. There should be no problem analyzing dates with AM and PM, but for the sake of simplicity, use military times if you don't want to have troubles converting your dates. For example: Military: 16:34:59 Standard: 4:34:59 PM
{ "language": "en", "url": "https://stackoverflow.com/questions/7624198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preventing Ctrl-C from closing program This is an extension to a question I asked before. Override Ctrl-C I have this code that is handling the signal for ctrl-c, while this worked on one machine, I ran it on another and it now once again exits the program after ctrl-c is pressed. When I asked my professor he told me that in the handler I will need to prevent the signal from being processed further, but I am not sure how to do this. #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <signal.h> #include "Input.h" #include "CircleBuff.h" sig_atomic_t sigflag = 0; void catch_int(int sig_num) { sigflag = 1; //printf("to do: Print history"); } void printHistory(CircleBuff hist) { cout << "Complete History:\n" << endl; hist.print(); cout << endl; } int main(int argc, char** argv) { signal(SIGINT, catch_int); //my code here do { //more code here if (sigflag != 0) { printHistory(history); sigflag = 0; } } while(report != 0); //which is assigned in the code Here is the reduced code: #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <signal.h> sig_atomic_t sigflag = 0; void catch_int(int sig_num) { sigflag = 1; printf("to do: Print history"); } int main(int argc, char** argv) { signal(SIGINT, catch_int); do { } while(1); } A: Did you try signal(SIGINT, SIG_IGN);? I assume that will work Edit: I went back and reduced your program just a bit and the handler seems to work (every invokation increases the flag), yet the actual syscall (sleep in mycase) is aborted. Can you retest and restate what is not working for you in this reduced sample? #include <stdio.h> #include <unistd.h> #include <signal.h> volatile sig_atomic_t ctrlCcount = 0; void catch_int(int sig_num){ ctrlCcount++; } int main(int argc, char** argv){ signal(SIGINT, catch_int); do{ sleep(5); printf("Ctrl-C count=%d\n", ctrlCcount); }while(1); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7624200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Get peer address within a thrift handler function I am implementing a small thrift (0.6.0) server in ruby to play a role of proxy to another protocol with several connections (multiple clients) to a single server. I want to be able and keep per-client data on the server side and track "session" parameters across multiple invocations of handler functions. I currently use Thrift::NonblockingServer as SimpleServer does not seem to allow concurrent connections. I know how to use TCPSocket::peeraddr but Thrift::NonblockingServer::IOManager::Worker::run creates a temporary MemoryBufferTransport with the frame it read and passes that as the input/output protocol down to the processor so it seems that the info is not passed down from there. Is there a clean way to do this? I was thinking of re-defining the above mentioned Thrift::NonblockingServer::IOManager::Worker::run to also include the fd, or other ID at an additional parameter to process or augment the proto instances but as I also have to worry about one layer of generated ruby code (process_* methods in class Processor) it seems a little heavy. I wonder if someone did anything like this before. Thanks! p.s. this is similar problem to this C++ thrift question A: Here is how I went about changing Thrift::NonblockingServer::IOManager::Worker::run to support this. Few caveats: * *As I mentioned in the question I don't consider it clean (if nothing else I will have to monitor future thrift versions for changes in this function, this is based on 0.6.0). *this is written to work with ruby 1.8 (or I would have gotten the non translated addr/port see my other question) *I'm a ruby newbie .. I'm sure I've done some of this "wrong" (for example, should $connections be @@connections in ConnEntry or a diff class?). *I am aware that the Thread.current hash for thread-local storage has a namespace pollution issue First, at some central module: module MyThriftExt $connections={} class ConnEntry attr_reader :addr_info, :attr def initialize(thrift_fd) @addr_info=thrift_fd.handle.peeraddr @attr={} end def self.PreHandle(fd) $connections[fd]=ConnEntry.new(fd) unless $connections[fd].is_a? ConnEntry # make the connection entry as short-term thread-local variable # (cleared in postHandle) Thread.current[:connEntry]=$connections[fd] end def self.PostHandle() Thread.current[:connEntry]=nil end def to_s() "#{addr_info}" end end end module Thrift class NonblockingServer class IOManager alias :old_remove_connection :remove_connection def remove_connection(fd) $connections.delete fd old_remove_connection(fd) end class Worker # The following is verbatim from thrift 0.6.0 except for the two lines # marked with "Added" def run loop do cmd, *args = @queue.pop case cmd when :shutdown @logger.debug "#{self} is shutting down, goodbye" break when :frame fd, frame = args begin otrans = @transport_factory.get_transport(fd) oprot = @protocol_factory.get_protocol(otrans) membuf = MemoryBufferTransport.new(frame) itrans = @transport_factory.get_transport(membuf) iprot = @protocol_factory.get_protocol(itrans) MyThriftExt::ConnEntry.PreHandle(fd) # <<== Added @processor.process(iprot, oprot) MyThriftExt::ConnEntry.PostHandle # <<== Added rescue => e @logger.error "#{Thread.current.inspect} raised error: #{e.inspect}\n#{e.backtrace.join("\n")}" end end end end end end end end Then at any point in the handler you can access Thread.current[:connEntry].addr_info for connection specific data or store anything regarding the connection in the Thread.current[:connEntry].attr hash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 2D Non-OpenGL Game : ViewControllers I'm building a very simple iOS game that doesn't require any OpenGL; I'd like to stick with Core Graphics & Core Animation. It seems as though I need two types of ViewControllers: Basic VCs for navigating between menu screens (ie. Settings, Main Menu, Level Select, etc.), and Gameplay VCs for managing all my UIViews and CALayers. What's a good way to manage/exchange these Views & VCs to preserve performance? Is it best practice to have one hierarchy of VCs like a traditional UINavigationController-based app, covering the NavBar when I'm displaying a Game VC? Or instead should I be removing all other ViewControllers from the stack when I enter "game mode", and setting it as my window.rootViewController property? Any alternatives / downsides to continually resetting window.rootViewController? My gut tells me the latter is better on resources+performance, but it seems heavy handed. Any advice + direction here would be appreciated. Thanks A: You can probably make the Game VC the rootViewController, and present the game selection as modal view controller on top of that controller. You can do that without animating at the beginning of the application. When the user is done with the setup, dismiss the view controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: facebook graph api returning empty json Using the link to my events automatically generated in the docs here: http://developers.facebook.com/docs/reference/api/ (Events: https://graph.facebook.com/me/events?access_token=...), I can get a json object populated with the events I'm RSVP'ed to. When I request them from my app (having gotten an access token authorized to view user_events), I get back an empty json object. My app can get back a populated friends list. I also can't get back a populated list of photo albums. Anybody got a guess for what's up? A: Sounds like a permissions problem, has your access token definitely got the user_events permission? Check with a call to /me/permissions You can also use the debug tool at https://developers.facebook.com/tools/debug (put the access token in there) and it will tell you what permissions the token was granted A: My app events are also an empry array. I fetch them via graph api. I guess it is because I created them on behalf of the user. Facebook displays (on the event page itself) as admins the user AND the app, which made me assume, both are owner/creator. The event array though lists only the app user (under the key #creator'). Confusing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: My list of pointers to std::string objects is not working right, and I can't figure out why Can you help me figure out this code: onCreate(xMsg) is called by the WindowProcedure on a WM_NCCREATE message. The problem is within the iterator dereferencing. I can't seem to set the iterator to the list's begin() and then get the contents of the iterator, which should be a pointer to a string which could be used with ->c_str() in a MessageBox. class MyController { public: MyController() { } ~MyController() { } void onCreate(xMessage *msg); protected: std::list<std::string *> m_stringlist; std::list<std::string *>::iterator m_stringlistiter; }; void onCreate(xMessage *msg) { std::string *first_string = new std::string("Hello world"); m_stringlist.push_back(first_string); // This is where my iterator comes into play and it doesn't seem to do the trick. m_stringlistiter = m_stringlist.begin(); MessageBox(NULL, (*m_stringlistiter)->c_str(), "Title", MB_OK); } A: We aren't given the full example, but I assume that you are doing other manipulations in between the creation and use of the iterator. Iterators are not guaranteed to be valid after varied operations on the container. You should not save them. I'm willing to bet that this will work? class MyController { public: MyController() : title("Hello World") {} void onCreate(xMessage *msg); { MessageBox(NULL, title.c_str(), "Title", MB_OK); } protected: std::string title; // generic lists of strings with // magic indexes are hard to maintain. }; This is easier to read and debug too, which costs a lot more than any other part of software development. You should use iterators as temporary objects, for the most part. Rarely do they extend outside of a function/method's scope. struct some_struct { some_struct() { gui_text.push_back( std::string("Hello World!") ); } void some_function() { std::list<std::string>::iterator iter = gui_text.begin(); for (; iter != gui_text.end(); iter++) { std::cout << *iter << std::endl; } } std::list<std::string> gui_text; }; Things like adding, deleting, etc from the container will invalidate iterators. So just recreate the iterator at each point. Strings and iterators are pretty lightweight, so you don't need to worry about optimizing in this way. Really.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extending the line to the end while plotting? In reference to this question here, I managed to plot an ECDF for my data. However, I was wondering if it is possible to extend the lines to the extreme left/right of the graph much like how base R plots it? Any suggestions? I want the lines to look more like this (extending to the extreme left/right of the graph and not ending abruptly as above): A: Probably, at the moment, there is no way to do automatically. You can set the range of drawing by adding manually limits to data frame. # sample data frame df <- data.frame(x = c(rnorm(100, -3), rnorm(100), rnorm(100, 3)), g = gl(3, 100)) df <- ddply(df, .(g), summarize, x = x, y = ecdf(x)(x)) # add x min/max for each levels df2 <- rbind(df, ddply(df, .(g), function(x) data.frame(x = range(df$x), y = c(0, 1)))) ggplot(df2, aes(x, y, colour = g)) + geom_line() A: If you need to ensure that the function is monotonic, you can use something like: monotonic.y <- y; n <- length(monotonic.y); for (i in 1:n) { monotonic.y[i] <- max(monotonic.y[1:i]); } and plot monotonic.y instead of y.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you get the most popular items based on visits? Let's say we have a table for items that looks like this item_id item_visits What should we add to this table, to be able to sort these items based on how many visits they have had in the last 7 days. And how do we query that to the db? A: Sorry, I misunderstood the ask... Well, of course you need to add a column named VisitTime which has type datetime. After that I would suggest to create a set of views to help you making the query. For example a view named DailyVisit which has the amount of view in day(indicated by a date) for every item. A: Your table is a bit confused. You don't want to keep track of the number of item visits. You just want to keep track of when an item was visited and maybe by whom and and where and which item. I would suggest the following: table visit ------------ id integer not null primary key auto_increment item_id integer not null foreign key fk_item_id references item(id) on delete cascade on update cascade visitor_id integer not null foreign key fk_visitor_id references visitor(id) on delete cascade on update cascade visit_date timestamp not null default current_timestamp engine = InnoDB This should give you all the details you need to know the visits per item and get details about items and visitors as well. -- select total number of visits per item for the last week. SELECT COUNT(*) as NrOfVisits , i.name as ItemName FROM visit v INNER JOIN item i ON (v.item_id = i.id) WHERE v.visit_date BETWEEN now() AND DATE_SUB(now(), INTERVAL 7 DAY) GROUP BY v.item_id WITH ROLLUP
{ "language": "en", "url": "https://stackoverflow.com/questions/7624220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java Desktop Browser popup window I use the below code to launch a web page in default system browser: String url = "http://www.google.com"; java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); however i want my web page to be displayed in a popup browser window with a given size (with,height) like we can do in javascript with Window Object. is there a way i can control from java the default browser and ask it to open a popup window with a given size? A: There are two ways I can think of to approach this problem: * *Instead of going directly to the target URL, open an intermediate URL like http://our.com/bouce.html?url=google.com&w=400&h=300 Then bounce.html uses JavaScript to open url @ w X h. *Use a JEditorPane. The much maligned editor pane is not ideal for real world browsing, but can deal with a variety of sites, and it is improving with each release (most of the time, anyway). A: There is no way to do this in pure Java. If you really need to do this, you will need some way to find out what the user's default browser is. Then launch you will need to launch a browser instance using System.exec, supplying the appropriate command line arguments. A: there is this good project http://browserlaunch2.sourceforge.net/ you invoke a new browser window like below. however it probably doesn't offer option for setting window height and width. BrowserLauncher browser =new BrowserLauncher(); browser.setNewWindowPolicy(true); browser.openURLinBrowser(url);
{ "language": "en", "url": "https://stackoverflow.com/questions/7624223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Java: Upload files to dropbox So i have a simple problem and am looking for a few pointers to a simple solution. I have a java app that must upload a file to dropbox. It will know the username and password of the dropbox account to upload to by default. All i need now is some way to put a file on my computer in any directory on to the dropbox in any directory of the dropbox. I've downloaded the dropbox API for java but am completely lost as to what to do with it. Can somebody please hand me the rod and point me the right way as to how to upload files to dropbox using java and preferably the dropbox API (and i think thats the only way to...is to use the dropbox java api). Thanks a bunch.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python 'in' Operator Inexplicably Failing My simple script to check for a certain word in files seems to be failing, and I cannot seem to explain it through documentation or searching. The code is below. I believe I have narrowed it down to the 'in' operator failing by printing the code itself and finding the word that I am looking for. If curious, this script is to find certain keywords in the Quake source code, since I'd rather not look through 30+ full source files. Any help would be appreciated, thanks! import os def searchFile(fileName, word): file = open(os.getcwd() + "\\" + fileName,'r') text = file.readlines() #Debug Code print text if(word in text): print 'Yep!' else: print 'Nope!' A: The reason it is failing is because you are checking if the word is within the text's lines. Just use the read() method and check in there or iterate through all the lines and each each individually. # first method text = file.read() if word in text: print "Yep!" # second method # goes through each line of the text checking # more useful if you want to know where the line is for i, line in enumerate(file): if word in line: print "Yep! Found %s on line: %s"%(word, i+1) A: text is a list of strings. That will return true if word is a line in text. You probably want to iterate through text, then check word against each lines. Of course, there are multiple ways to write that. See this simple example. A: for line_num, line in enumerate(file, 1): if word in line: print line_num, line.strip()
{ "language": "en", "url": "https://stackoverflow.com/questions/7624227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS - Div padding "all except z pixels" I have a div that needs to stretch the whole way across the page, but the actual content should only be z pixels wide, and centered. That is, the text is not centered, but the area where the content is - the interior of the div, if you will - is centered. The logical approach is to do something like this: <div> <!--I stretch across the entire page!--> <div> <!--I am z pixels wide, and my margins are auto. Content goes here.--> </div> </div> The only problem with this is that it seems really div-itis-y. This is something that should be able to be achieved using the box model. Is there anyway to do this without adding divs? A: body already stretches the width of the page, so just use that one interior div something like <body> <div></div> </body> and div{ width:980px; margin:0 auto; } This is what divs are meant to do. Now, depending on the content and whether or not you are using HTML5, you may want to wrap it all in another element tag, such as header, nav, section etc. But there is nothing inherently wrong with using divs, even nested ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rspec isn't finding examples I have an almost-new Rails 3.1.0 application, and rspec can't find my examples. duncan@duncan-notebook:~/myapp$ bundle exec rspec No examples found. Finished in 0.00004 seconds 0 examples, 0 failures My spec directory looks like this: spec/ |-- controllers | `-- welcome_controller_spec.rb |-- factories | `-- users.rb |-- helpers | `-- welcome_helper_spec.rb |-- models | `-- user_spec.rb |-- spec_helper.rb `-- views `-- welcome `-- index.html.haml_spec.rb And there are definitely examples in there. E.g. welcome_controller_spec.rb contains the following: require 'spec_helper' describe WelcomeController do describe "GET 'index'" do it "should be successful" do get 'index' response.should be_success end end end I'm running the following versions of rspec & related Gems: * *rspec (2.6.0) *rspec-core (2.6.4) *rspec-expectations (2.6.0) *rspec-mocks (2.6.0) *rspec-rails (2.6.1) *rubyzip (0.9.4) Could someone please tell me how to convince rspec to find my examples? I suspect I'm missing something very simple here. A: I'm getting the same results with bundle exec rspec, maybe it was deprecated. Try this instead: rspec spec A: @calebB is correct for <= 2.6, but the 2.7 release won't require you to include the directory (it will default to spec).
{ "language": "en", "url": "https://stackoverflow.com/questions/7624233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Aweber Wordpress Widget Wont work Im using the Aweber Wordpress plugin and every time I try to hit the submit button on the form, all it does is refresh the page without actually submitting. The form is supposed to behave like this: http://forms.aweber.com/form/01/2069621401.html however, when you check the form on my site, which is here: http://acnecuresite.com you will see what im talking about. Can anyone help me fix this thing? It has to be in the widge A: From the looks of it you're not wrapping your form propery with the <form> wrapper. Try wrapping your form on the widget properly so it includes its proper markup, i.e. <form action="http://www.aweber.com/scripts/addlead.pl" class="af-form-wrapper" method="post"> .... </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7624234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: centering FB html5 code Trying to get html5 code from Facebook Like box centered. Here is the default code: <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-like-box" data-href="http://www.facebook.com/mycreditdoctor" data-width="460" data-show-faces="true" data-stream="false" data-header="false"></div> I have tried searching this site and google but must not be putting in the right keywords (I am also a beginner in html) The wordpress plugin allows me to just paste in a script, so it is easy to get this to show up, but it is left aligned. Can someone please let me know what you can add to this html script so that it will be center aligned? A: Stick the code in a <center> ... </center>. A: I changed the data-width to a smaller value (should be proportional to the section you want to center) and used the <center> tag before the <div class> class. A: the center tag may be depreciated but it's the only one that works in this case. CSS techniques don't seem to have any effect.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to handle packet send/ack I'm building an application to communicate to an Xbee module via the Xbee API. Currently I have something working, but its fairly simple and has quite a few limitations. Sub processPackets() ' this runs as its own thread 'remove data from serial buffer and format in to packet 'if IO response generated remotely, not requested put in IOQueue 'Otherwise put in CMDQueue (response generate from request, ie cmd response or packet Ack End Sub Then as an example of a typical command request Send data to serial port Loop (with timeout) checking CMDQueue for packet, dequeue and check if it matches Otherwise timeout Now its pretty obvious the potential issues with this method. In particular, since the Xbee modules can sleep you may have to wait a considerably long time for an Ack. Plus it is dependent on order, etc. I would like to take a non-blocking approach. In this case, in order to act on the the Ack/response packet in most cases I need to know the original packet it was sent in response to. I'm thinking of creating a few threads. SendPacket will send the packet, load the sent packet, time sent, and timeout in to memory, also include callback function? (array?) PacketProc will parse packets, check the array of packets waiting for response and call the callback function. It will also check for any waiting packets that have timed out and call the callback to indicate timeout? Ultimately I'm looking for the ability to send packets to multiple devices (may response in any order) and act on those responses or act on the timeout. I'm not particularly familiar with .NET can anyone comment on this approach or recommend a better pattern to look in to? Any .Net methods I should look in to? A: Use the Task class. Imports System.Threading Imports System.Threading.Tasks ... Dim buffer As StringBuilder; Sub processPackets() ' this runs as its own thread ' Wait for packet ' put here command/loop that waits packet buffer.Append(packet); 'remove data from serial buffer and format in to packet 'if IO response generated remotely, not requested put in IOQueue If buffer.ToString() = "REMOTELY" Then ' Put IOQueuo buffer.Clear() Else 'Otherwise put in CMDQueue (response generate from request, ie cmd response or packet Ack ' Put in CMDQueue buffer.Clear() End If End Sub ... ' Create and execute the Task that will process the packets Dim t = Task.Factory.StartNew(Sub() processPackets()) http://www.dotnetcurry.com/ShowArticle.aspx?ID=491
{ "language": "en", "url": "https://stackoverflow.com/questions/7624237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: most appropriate form to make re-usable Ruby on Rails code more re-usable? I make a lot of rails applications, and there seems to be lots of way to make code reusable. Among the things I reuse are the following: css files, initializers, views/shared/ partials admin images application helpers haml view templates gems etc... I once tried to put all of this into a gem about a year ago and it backfired terribly mostly because of changing dependencies, and the fact that I was always tweaking the code and adding to it. This is not good as a gem, because to see a simple change take place you have to compile/publish/install the gem. So the gem is not right. What are recommended ways to keep all of this "personal" code more or less modular so I can "plop" it into a new rails project and edit it as normal rails code (no gem compiling / publishing). The two words that come to mind are engines and plugins, but I really don't know much about how either of them work. I've also heard of (confusingly) "templates", not the view kind. What are your suggestions. I'd love to get this figured out! A: You're on the right line of thinking with templates + engines. Templates are great for one-time use. They allow you to generate an application that conforms to a specific, um, template, which provides an excellent base for you to build on top of. You can find more information about templates in this wonderful guide. Engines, I think, are the better of the two. They allow you to provide that same base that templates would, but then also allow you to expand on that base for later. Within an engine you can have all the things you want. You can generate one of these fabulous creations by running this command: rails plugin new pixelearth_base --mountable This will generate the base of an engine, which then you can have all the things you wanted. Let me show you the ways. CSS files / images CSS files go into app/assets, just like in a Rails 3.1 application, and are then processed the same way. You can read more about them in the Asset Pipeline guide. You can reference them exactly the same way you would reference them if they were inside your application. Of course, any asset inside your application named identically to one inside your engine will take precedence. Initializers These go in config/initializers, just like an application (hint: this is a running theme with engines). They work the same way and are explained in this section of the Configuring Guide, although I reckon you know that much already. Shared views These go into app/views/shared in your engine. Any file in your application named identically will take precedence over the file in the engine. The application will be able to seamlessly access any file in this directory, since engines have their view paths added to the application's. Partials Ditto. Admin Have you tried the wonderful rails_admin engine for this? Perhaps that would suit you. If not, you can build this functionality into your engine just as you would in an application. Helpers Work in much the same way as everything else. Add them to your engine and you'll be good to go. Although I am not confident in that last point, you may have to do helper SomeHelper at the top of the controller to get them included. Haml Specify this as a dependency of the engine in the engine's pixelearth_base.gemspec file using a line like this: s.add_dependency 'haml', '3.1.3' Your engine (and by extension, your application) would be able to use haml in views. Templates I am not sure what you mean by this, so I am going to gloss over it. Gems Shared gem dependencies should be specified in the pixelearth_base.gemspec just like the haml example. Including the engine Now, you're going to need to include this engine into your application but you don't want to go through the pain of updating a gem all the time. I reckon the best way to do this is to push the gem to GitHub and then specify a line like this inside your application's Gemfile: gem 'pixelearth_base', :git => "git://github.com/pixelearth/pixelearth_base" Whenever you update this gem and push new changes to GitHub, you will need to run bundle update pixelearth_base to update your application with the latest version. Each time you run bundle update it will be locked to that specific version. Any further changes to the engine won't be acknowledged until you run bundle update ... again. Mounting the engine One final thing which you asked about in IRC is mounting. If you happen to go the route of having shared functionality in your engine (i.e. controllers and so on) then you'll need to mount your engine within your application. This is very easy and can be done by putting this line in your config/routes.rb: mount PixelEarth::Engine, :at => "pixelearth" The PixelEarth::Engine class is defined in your engine at lib/pixel_earth/engine.rb and provides all the functionality it needs by inheriting from Rails::Engine. Any functionality from your application will now be available at /pixelearth in your application. A: It depends on the file, if you want I can break an answer down for you. But my general advice is to keep your code small, lightweight and designed for one task. A good way of doing this is determining if the code you write is orthogonal. Wikipedia defines it in a computer science scope as this: Orthogonality is a system design property facilitating feasibility and compactness of complex designs. Orthogonality guarantees that modifying the technical effect produced by a component of a system neither creates nor propagates side effects to other components of the system. The emergent behavior of a system consisting of components should be controlled strictly by formal definitions of its logic and not by side effects resulting from poor integration, i.e. non-orthogonal design of modules and interfaces. Orthogonality reduces testing and development time because it is easier to verify designs that neither cause side effects nor depend on them. As far as constraining the size of your code you can leave that up to your own personal judgement on when and where you delegate methods and classes. However I like to keep in mind the separation of concerns and the single responsibility principle when working on breaking up the issues I face into smaller parts. However you cant just write good code and leave it at that, you need to have a good way of distributing your code. I have a development server on my LAN that hosts many private Git repositories however you can use any VCS or DVCS to keep your code organized. I can then use this to keep my projects sourcing the latest versions of the files from the server when I need to update them and make changes and I can always branch if my requirements change for the project I'm working on. With Git I always have my code in version control so I use submodules to let me keep the latest version of the code handy and up to date. Let me know if you want more information or if you dont use Git I can look for similar features on a VCS you are familiar with. Also I'd just like to note that this is a good question that has a lot of points and I'm glad you asked since I remember struggling with this and I'm sure others are tackling the same problem as well. A: When I write sw for my app that I feel could be re-usable in other projects, I write it as its own plugin. I copy the plugin dir model from one of the plugins that I'm already using.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jar file with admin privilege Is there a way in java to execute the jar file with administration privilege, when double click on jar file open with admin privilege ? i know this way: go to C:\Program Files\Java\jre6\bin and right click on javaw.exe file choose compatibility and click on run this program as an administrator. but this way isn't an appropriate for normal application users >>> Thanks. A: You could call the JRE from an executable and add an administrator manifest. Bat To Exe Converter works nice for such workarounds. It will allow you to write a batch file and convert it into an self-extracting executable that contains your .jar file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery tooltip when hovering text I currently have a custom tooltip which appears when a user hovers over text, and disappears when the cursor goes elsewhere. However, because of the spaces between text, the tooltip disappears and reappears in a very jittery fashion. What behavior should I keep in mind to avoid this? It seems that the only way to have hover() activate on a block of text is to have it when the cursor goes over the actual character (and hides when it reaches a gap). EDIT: Solved, onmouseenter() and onmousemove() were able to do the trick. Unfortunately this is just a drawback of hover() A: Try wrapping the text in a span and attach the hover to the span instead. A: Could you add a delay on the hover event to make sure that someone wants to hover? http://api.jquery.com/delay/
{ "language": "en", "url": "https://stackoverflow.com/questions/7624242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I look into the memory addresses of automatic variables in GDB? Follow-up Hmmm I am not sure if I am doing the right thing. Thanks for all the helps thus far. My previous thread: Is this really the address I am making new thread because this is really a separate problem, and the core problem. Please bear with me, thank you. Let me restate my goal: I want to be able to look into the memory address of each variable (we know the entry address of the program, and we know how many bytes are set aside from reading the assembly code). Suppose we are given the following source code: Source Code int main() { int a = 15; int b; int c; b = c; c = c+1; return 0; } We should be able to find out the address of variable a and c, and the values in these memory addresses. Using gdb layout asm I get this │0x80483f4 <main()> push %ebp │ │0x80483f5 <main()+1> mov %esp,%ebp │ │0x80483f7 <main()+3> sub $0x10,%esp │ │0x80483fa <main()+6> movl $0xf,-0x4(%ebp) │ │0x8048401 <main()+13> mov -0x8(%ebp),%eax │ │0x8048404 <main()+16> mov %eax,-0xc(%ebp) │ │0x8048407 <main()+19> addl $0x1,-0x8(%ebp) │ │0x804840b <main()+23> mov $0x0,%eax │ │0x8048410 <main()+28> leave │ │0x8048411 <main()+29> ret │ │0x8048412 nop // the statement int a = 15 is in the address 0x80483fa // I want to get the value 15 x/w 0x80483fd <== this will print 15 But it doesn't make sense to me because from what I recalled, the variables are supposed to be in ebp - 0x10 right? // the starting address of the program is 0x80483f4 // minus 0x10 we get 0x80483E4 x/w 0x80483E4 <== will print a big number // Since b = c, I should be able to get that as I decrement, but no luck I don't think I know what I am doing...? On one hand, the automatic variables are destroyed as soon as the program terminates... PS: I really can't use cout, or printf, or setting breakpoints or watcher while debugging. So doing print $ebp will not work because there is no active register (remember the program terminates - no breakpoint!). So commands like info locals, info registers aren't available. I have been spending the whole day trying to figure out what is going on. I really appreciate all the helps and I am looking forward to getting more. Thanks. What should I do?? I need to look at the value of variable a, b, c. How can this be done? Thank you very much. Not really a homework, but a class discussion. A: These variables do not have one particular memory location. They are stack variables. So you cannot rely on them being in memory after the program terminates, because they are considered out of scope after the function in which they are created returns, allowing the address at which they resided to be reused for storing other content. Imagine you have a function whose source looks like this: int foo(int x) { int y = x; if (y == 0) { return 0; } return foo(x-1)+1; } If you call foo(1), the variable y will exist at two different memory addresses, one for each of the two stack frames created for the two nested invocations of foo (foo(1) and foo(0)). If you call foo(10), there will be eleven instances of y, each one holding a different value and residing at a different memory address. If you do not use a breakpoint, then the variables for all intents and purposes do not exist. They only have storage allocated when the program is running and the current stack contains a frame from the function in which they reside. You cannot grab them postmortem (except from a core dump, which is a form of breakpoint really). Sum-up: if you do not analyze the program while it is running, either via breaking to a debugger or via adding some code that will print/set aside values, you can not inspect stack variables. These are stack variables. If you must have them be single-instance, you should make them heap-allocated global variables by moving them outside of function scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JTextPane - a phrase with TWO styles I just faced an interesting thing. I was changing selected text style. The thing is when I change style for ONE WORD one by one it's fine but next if I select a whole styled phrase and change its font color the whole phrase becomes ONE styled (the first style within the selected text) only :( Here is the problem snippet private void setFontColorStyle() { JTextPane editor=this.getTextPane(); String text=this.getTextPane().getSelectedText(); StyledDocument doc=(StyledDocument) editor.getDocument(); int selectionEnd=this.getTextPane().getSelectionEnd(); int selectionStart=this.getTextPane().getSelectionStart(); Element element=doc.getCharacterElement(selectionStart); AttributeSet as = element.getAttributes(); String family = StyleConstants.getFontFamily(as); int fontSize = StyleConstants.getFontSize(as); boolean isBold=StyleConstants.isBold(as); boolean isItalic=StyleConstants.isItalic(as); boolean isUnderlined=StyleConstants.isUnderline(as); StyleContext context = new StyleContext(); Style style; this.getTextPane().replaceSelection(""); style = context.addStyle("mystyle", null); style.addAttribute(StyleConstants.FontSize, fontSize); style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.Foreground, this.fontColor); style.addAttribute(StyleConstants.Bold, isBold); style.addAttribute(StyleConstants.Italic, isItalic); style.addAttribute(StyleConstants.Underline, isUnderlined); this.getTextPane().replaceSelection(""); try { this.getTextPane().getStyledDocument().insertString(selectionEnd - text.length(), text, style); } catch (BadLocationException ex) { } } And here is the bold making method code... () Italic and underlined all the same logic so I guess it is quite clear private void setFontBoldStyle() { if(this.getTextPane().getSelectedText()!=null) { String text = this.getTextPane().getSelectedText(); int selectionStart=this.getTextPane().getSelectionStart(); int selectionEnd=this.getTextPane().getSelectionEnd(); StyleContext context = new StyleContext(); Style style; Element element=doc.getCharacterElement(selectionStart); Enumeration en=doc.getStyleNames(); AttributeSet as = element.getAttributes(); /** * Get style from history... */ String family = StyleConstants.getFontFamily(as); int fontSize = StyleConstants.getFontSize(as); Color currentColor=StyleConstants.getForeground(as); boolean isBold=StyleConstants.isBold(as)?false:true; boolean isItalic=StyleConstants.isItalic(as); boolean isUnderlined=StyleConstants.isUnderline(as); String styleName=String.valueOf(Math.random()); style = context.addStyle(styleName, null); // style.addAttribute(StyleConstants.FontSize, fontSize); // style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.Foreground, currentColor); style.addAttribute(StyleConstants.FontFamily, family); style.addAttribute(StyleConstants.FontSize, fontSize); style.addAttribute(StyleConstants.Bold, isBold); style.addAttribute(StyleConstants.Italic, isItalic); style.addAttribute(StyleConstants.Underline, isUnderlined); this.getTextPane().replaceSelection(""); try { this.getTextPane().getStyledDocument().insertString(selectionEnd - text.length(), text, style); } catch (BadLocationException ex) { } }//if end... } Here is the bold method invokation code: private void setFontBold() { this.setFontBoldStyle(); } ... and color method invokation private void setFontColor(Color fontColor) { this.fontColor=fontColor; this.setFontColorStyle(); } ... and action listeners (for bold)... private void boldButtonActionPerformed(java.awt.event.ActionEvent evt) { this.getTextPane().requestFocusInWindow(); this.setFontBold(); } ... and for color private void colorButtonActionPerformed(java.awt.event.ActionEvent evt) { this.getTextPane().requestFocusInWindow(); ColorDialog colorEditor=new ColorDialog(); //returns rgb color... Color color=colorEditor.getSelectedColor(this.getDialog(), true,false); if(color==null){ JOptionPane.showMessageDialog(this.getDialog(), "null color"); return; } this.setFontColor(color); } I dearly need your advice about how to keep selected text styles unchanged (like bold or font family) when I want to change a whole different styled selected text color for example? To be more clear... For example I have text My Hello World is not pretty :) Next I select the whole phrase and change its color from black to lets say red. Next text becomes red but the whole phrase becomes bold according to first style. But the thing is it would be interesting to keep bold and italic styles but at the same time have the phrase red :) So quite simple but I have just confused how to control more than one style in the frames of selected text area? Any useful comment is much appreciated A: TextComponentDemo, discussed in How to Use Editor Panes and Text Panes, is a good example of how to manage this as well as other text component features. Addendum: TextComponentDemo relies on pre-defined Action objects to handle editing tasks. Conveniently, StyledEditorKit contains a series of nested classes that derive from StyledTextAction. As a concrete example, here's how one might add an AlignmentAction to the Style menu of TextComponentDemo in the method createStyleMenu(): protected JMenu createStyleMenu() { JMenu menu = new JMenu("Style"); Action action = new StyledEditorKit.AlignmentAction( "left-justify", StyleConstants.ALIGN_LEFT); action.putValue(Action.NAME, "Left"); menu.add(action); menu.addSeparator(); ... } The remaining (arbitrary) alignment action names are defined privately in StyledEditorKit. Addendum: setCharacterAttributes() is the common routine used by the nested editing actions. It invokes a method of the same name in StyledDocument, as proposed by @StanislavL. Addendum: I am unable to reproduce the effect you describe. When I set the color of the selection, the style attributes remain unchanged. Addendum: The StyledEditorKit actions work just as well with a JButton or JToolBar. new JButton(new StyledEditorKit.ForegroundAction("Red", Color.red)) A: Use this.getTextPane().getStyledDocument().setCharacterAttributes()
{ "language": "en", "url": "https://stackoverflow.com/questions/7624247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Which row was chosen by the user How can I tell which row (doesn't really matter to me which text field exactly) was chosen in the JTable. I want to be able to edit a row that was chosen by the user. I will appreciate any help. Thanks. A: Add a ListSelectionListener to the table's ListSelectionModel. It's quite easy to do. The ListSelectionEvent object passed into the valueChanged method can tell you the selected row(s). Or you could simply query the JTable via its getSelectedRow or getSelectedRows method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why is my deleted function not typeof "undefined" in Node.js? I'm using Node.js. After my "sum" function gets deleted, I would expect the typeof(sum) to return "undefined", but it doesn't. // functions are data in Javascript var sum = function ( a,b ) { return a + b; } var add = sum; delete sum; console.log ( typeof sum ); // should return undefined console.log ( typeof add ); // should return function console.log ( add( 1,2 ) ); // should return 3 I would think it should return: undefined function 3 But instead it returns: function function 3 A: You shouldn't use the delete operator on identifiers (in scope variables, functions - as sum - or function arguments). The purpose of the delete operator is to delete object properties. When you declare a variable a function declaration or function arguments, behind the scenes these identifiers are actually a properties that belongs to the environment record of the current scope where they were declared. Those properties are explicitly defined internally as non-configurable, they can't be deleted. Moreover, the usage of the delete operator has been so misunderstanded that on ES5 Strict Mode, its usage on identifiers has been completely disallowed, delete sum; should throw a ReferenceError. Edit: As @SLacks noted in the question comments, the delete operator does work with identifiers from the Firebug's console, that's because the Firebug uses eval to execute the code you input in the console, and the variable environment bindings of identifiers instantiated in code executed by eval, are mutable, which means that they can be deleted, this was probably to allow the programmer to delete at runtime dynamically declared variables with eval, for example: eval('var sum = function () {}'); typeof sum; // "function" delete sum; // true typeof sum; // "undefined" You can see how this happens also on the console: And that's probably what happened with the book you are reading, the author made his tests on a console based on eval. A: delete is only for deleting properties of object notations and not for deleting the declared variables as per this article. The snippet you have posted is there almost exactly as you've it here. EDIT: The same article referenced above clarifies the inconsistency that appears in Firebug as well in this section. Relevant excerpt: All the text in console seems to be parsed and executed as Eval code, not as a Global or Function one. Obviously, any declared variables end up as properties without DontDelete, and so can be easily deleted. Be aware of these differences between regular Global code and Firebug console.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: ASP.NET MVC3: model binding with hidden field Here's the view @using (Html.BeginForm("Deleted", "Location")) { Html.Hidden("LocationID", Model.LocationID ); <input type = "submit" value = "Delete" /> } And here's the method that's supposed to receive the data. public ActionResult Deleted(int LocationID) { //Do something with LocationID return View(); } When I run the code, LocationID is always null. Am I missing something? Thanks for helping A: Calling Html.Hidden returns an IHtmlString containing a hidden field. However, you aren't doing anything with the returned string. You need to render the string to the page using an @.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Codeigniter - should I access session data in a view? Should I grab some data from a session variable for my header from the header which needs to display a few details for the user currently logged in. Or, in each controller, load user data then send it to the corresponding view? Seems like I should do it from the controllers but having it in header requires less code. A: Should you? For the sake of maintainability and honoring the MVC pattern, I would say do it in the controller, I don't think one line of code is going to be an issue, you can get it all like this: $data['userdata'] = $this->session->all_userdata(); // returns and associative array Then pass that to the view, and get the stuff out in the view with $userdata['whatever'] which is the same amount of code as getting it from the header anyway. The function is located here Edit - 03 November 2015 As of version 3.0 $this->session->all_userdata(); has been depreciated. Instead directly accessing the $_SESSION object directly is the prefered method, however $this->session->userdata(); with no parameters could be used with older applications. $data['userdata'] = $_SESSION; // returns and associative array or $data['userdata'] = $this->session->userdata(); Documentation on userdata(): Gets the value for a specific $_SESSION item, or an array of all “userdata” items if not key was specified. NOTE: This is a legacy method kept only for backwards compatibility with older applications. You should directly access $_SESSION instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ruby on Rails: embed ActiveRecord object into JavaScript I have /invoices/ controller and @service object. When /services/1/invoices/new is called, a new @invoice form is created. The @service there is used to get quantity, price and discounts. I want to use @service.discounts in my Javascript to be able to update the @invoice.price field in the form everytime the quantity is being changed. How do I do this? Tried: invoices.coffee.erb service = <%= @service.to_json %> Doesn't work, because javascript is generated / cached before @service object is available. Something like service = <%= Service.find(1).to_json %> Obviously works, but it's the same problem: I need the object to be changed dynamically, according to /services/ID/invoices/new page A: If the object is retrieved in the action, and rendered in the controller, there shouldn't be an issue: all you're doing is multiplying the price by the quantity, which is pure JavaScript. If you're trying to update based on information not rendered in the template, then you'd probably want to use Ajax to get the updated data from the server, then make use of it in the template (or return already-rendered HTML, or a JavaScript fragment, etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7624264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I avoid Persistance and Mapping exceptions in NHibernate? So I've got the following code: try { var config = new Configuration(); config.Configure(); config.AddAssembly(typeof(Address).Assembly); var factory = config.BuildSessionFactory(); using (var session = factory.OpenSession()) using (var xaction = session.BeginTransaction()) { var address = createNewAddress(); session.Save(address); xaction.Commit(); var lastAddressID = address.AddressID; } } The problem is, I am using NHibernate to do some mapping, and when it hits the config.Configure() line, if I have the EmbeddeAsResource option set, it throws a "Can't compile mapper" exception. Weird, right? So I switched to "Content", and that worked. But then it got to session.Save(address) and threw a "No Persistance available" exception. I've been working on this for a couple hours and my head is spinning. I would appreciate any help you can give! Thanks! A: When you set it to 'Content' - it is ignored by NHibernate, so it isn't loaded - which gives you no problems configuring the sessionfactory - and also gives you the 'persister missing' exception when you start using the (un)mapped entity. So, we need to see your mapping - and the class that is mapped to help you further.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP mysql connection in index.html? I have noticed that on my website index.html file that contaisn php code to connect to a mysql database does not run and it's also possible to view the php source. Is this normal? I noticed that when I removed the code and put it in its own php file it was fine. A: By default, PHP code is only executed in .php files. HTML files contain raw markup and have nothing to do with PHP. You probably want to create index.php.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rijndael function i'm working at rijndael decryption, writing inverse function and get stack at InvMixColumns(); So, ref to wiki = http://en.wikipedia.org/wiki/Rijndael_mix_columns -- algorythm for MixColumns (there's also info about inverse MixColumns); Here my MixColumns(): protected static function MixColumns($s, $Nb) { $Nb = 4; for ($c=0; $c<4; $c++) { $a = array(4); // 'a' is a copy of the current column from 's' $b = array(4); // 'b' is a•{02} in GF(2^8) for ($i=0; $i<4; $i++) { $a[$i] = $s[$i][$c]; $b[$i] = $s[$i][$c]&0x80 ? $s[$i][$c]<<1 ^ 0x011b : $s[$i][$c]<<1; //However, this multiplication is done over GF(2^8). This means that the bytes being //multiplied are treated as polynomials rather than numbers. Thus, a byte "muliplied" //by 3 is that byte XORed with that byte shifted one bit left. //If the result has more than 8 bits (128 = 0x80), the extra bits are not simply discarded: instead, //they're cancelled out by XORing the binary 9-bit string 100011011 (0x11b) with the result //(shifted right if necessary). This string stands for the generating polynomial of the //particular version of GF(2^8) used; a similar technique is used in cyclic redundancy checks. } // b[n] = a•{02} in GF(2^8); // a[n] ^ b[n] = a•{03} in GF(2^8); $s[0][$c] = $b[0] ^ $b[1] ^ $a[1] ^ $a[2] ^ $a[3]; // 2 * a0 + 3 * a1 + a2 + a3 $s[1][$c] = $a[0] ^ $b[1] ^ $b[2] ^ $a[2] ^ $a[3]; // a0 * 2 * a1 + 3 * a2 + a3 $s[2][$c] = $a[0] ^ $a[1] ^ $b[2] ^ $b[3] ^ $a[3]; // a0 + a1 + 2 * a2 + 3 * a3 $s[3][$c] = $b[0] ^ $a[0] ^ $a[1] ^ $a[2] ^ $b[3]; // 3 * a0 + a1 + a2 + 2 * a3 } return $s; } I need to find inverseMixColumns(); protected static function InvMixColumns($s) { //a test... /* r0 = 14a0 + 9a3 + 13a2 + 11a1 r1 = 14a1 + 9a0 + 13a3 + 11a2 r2 = 14a2 + 9a1 + 13a0 + 11a3 r3 = 14a3 + 9a2 + 13a1 + 11a0 */ //$multiplyOf_ -- defined precalculated arrays from wikipedia; $t = array(); $a = array(219, 19, 83, 69); $t[0] = self::$multiplyOf14[$a[0]] ^ self::$multiplyOf9[$a[3]] ^ self::$multiplyOf13[$a[2]] ^ self::$multiplyOf11[$a[1]]; $t[1] = self::$multiplyOf14[$a[1]] ^ self::$multiplyOf9[$a[0]] ^ self::$multiplyOf13[$a[3]] ^ self::$multiplyOf11[$a[2]]; $t[2] = self::$multiplyOf14[$a[2]] ^ self::$multiplyOf9[$a[1]] ^ self::$multiplyOf13[$a[0]] ^ self::$multiplyOf11[$a[3]]; $t[3] = self::$multiplyOf14[$a[3]] ^ self::$multiplyOf9[$a[2]] ^ self::$multiplyOf13[$a[1]] ^ self::$multiplyOf11[$a[0]]; echo "<br /> t = ";self::array_show($t); //works! return $t; } //one of $multiplyOf__ protected static $multiplyOf14 = array( 0x00,0x0e,0x1c,0x12,0x38,0x36,0x24,0x2a,0x70,0x7e,0x6c,0x62,0x48,0x46,0x54,0x5a, 0xe0,0xee,0xfc,0xf2,0xd8,0xd6,0xc4,0xca,0x90,0x9e,0x8c,0x82,0xa8,0xa6,0xb4,0xba, 0xdb,0xd5,0xc7,0xc9,0xe3,0xed,0xff,0xf1,0xab,0xa5,0xb7,0xb9,0x93,0x9d,0x8f,0x81, 0x3b,0x35,0x27,0x29,0x03,0x0d,0x1f,0x11,0x4b,0x45,0x57,0x59,0x73,0x7d,0x6f,0x61, 0xad,0xa3,0xb1,0xbf,0x95,0x9b,0x89,0x87,0xdd,0xd3,0xc1,0xcf,0xe5,0xeb,0xf9,0xf7, 0x4d,0x43,0x51,0x5f,0x75,0x7b,0x69,0x67,0x3d,0x33,0x21,0x2f,0x05,0x0b,0x19,0x17, 0x76,0x78,0x6a,0x64,0x4e,0x40,0x52,0x5c,0x06,0x08,0x1a,0x14,0x3e,0x30,0x22,0x2c, 0x96,0x98,0x8a,0x84,0xae,0xa0,0xb2,0xbc,0xe6,0xe8,0xfa,0xf4,0xde,0xd0,0xc2,0xcc, 0x41,0x4f,0x5d,0x53,0x79,0x77,0x65,0x6b,0x31,0x3f,0x2d,0x23,0x09,0x07,0x15,0x1b, 0xa1,0xaf,0xbd,0xb3,0x99,0x97,0x85,0x8b,0xd1,0xdf,0xcd,0xc3,0xe9,0xe7,0xf5,0xfb, 0x9a,0x94,0x86,0x88,0xa2,0xac,0xbe,0xb0,0xea,0xe4,0xf6,0xf8,0xd2,0xdc,0xce,0xc0, 0x7a,0x74,0x66,0x68,0x42,0x4c,0x5e,0x50,0x0a,0x04,0x16,0x18,0x32,0x3c,0x2e,0x20, 0xec,0xe2,0xf0,0xfe,0xd4,0xda,0xc8,0xc6,0x9c,0x92,0x80,0x8e,0xa4,0xaa,0xb8,0xb6, 0x0c,0x02,0x10,0x1e,0x34,0x3a,0x28,0x26,0x7c,0x72,0x60,0x6e,0x44,0x4a,0x58,0x56, 0x37,0x39,0x2b,0x25,0x0f,0x01,0x13,0x1d,0x47,0x49,0x5b,0x55,0x7f,0x71,0x63,0x6d, 0xd7,0xd9,0xcb,0xc5,0xef,0xe1,0xf3,0xfd,0xa7,0xa9,0xbb,0xb5,0x9f,0x91,0x83,0x8d ); A: For InverseMixColumns(), as seen on the wikipedia page, you have: r0 = 14a0 + 9a3 + 13a2 + 11a1 r1 = 14a1 + 9a0 + 13a3 + 11a2 r2 = 14a2 + 9a1 + 13a0 + 11a3 r3 = 14a3 + 9a2 + 13a1 + 11a0 Addition is just the XOR-operator ^. For multiplication by 9, 11, 13 and 14, you either define a multiplication function or different lookup tables for multiplication by each of these numbers. You can find the tables on the wikipedia page. As for the function, just use the fact that x * y = log( exp(x) + exp(y) ) and lookup tables for logarithm and exponentiation of the same base.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Binding to Custom Control Property I am developing an Account List dropdown control which is to be used across my application. The dropdown will make a call to a service and retrieve the list of available accounts, and will expose a property "SelectedAccount" for the selected item in the dropdown. The SelectedAccount is going to be a DependencyProperty as it has to be bound by the consumers of the AccountDropdown control, and it has to be two-way bindable so it reflects an existing SelectedAccount. The AccountDropdown.asmx is simple, it contains a ComboBox: <ComboBox SelectedItem="{Binding Path=SelectedAccount, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"... The selected item of the combo box is bound to a property which is registered as a DependencyProperty.Register("SelectedAccount", typeof(IAccount), typeof(AccountDropdown), new UIPropertyMetadata(null)); ... and the usual property: #region SelectedAccount /// <summary> /// Selected account /// </summary> public IAccount SelectedAccount { get { return (IAccount)GetValue(SelectedAccountProperty); } set { SetValue(SelectedAccountProperty, value); } } #endregion SelectedAccount The properties are defined in the code-behind file... and the data context is set to "this"... so the binding is set correctly. When I use this control, I need to bind the SelectedAccount to the property of a ViewModel for another view, e.g.: <Controls:AccountDropdown SelectedAccount="{Binding Path=SelectedAccount, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> When I run the above code, and I change the selection on the dropdown, I get a System.StackOverflow exception. I can't even debug it, the exception is thrown from Windows.Base.dll. I've been struggling with this one for a day now... any help would be appreciated. **Note: **I have written several WPF Controls with Dependency Properties, and they work fine, but when I use them, I'm providing the value explicitly in the .asmx file. In this case I'm binding again when I use the property. I am guessing that exposing a bindable property may require some additional trick. A: Ok, as is often the case, the solution was simple. The DataContext of the AccountDropdown control was being implicitly set to itself, hence the infinite loop. Simply specifying the DataContext to use the DataContext of the control where it was being used (and therefore using the intended ViewModel binding): <Controls:AccountDropdown DataContext="{Binding}" SelectedAccount="{Binding Path=SelectedAccount, Mode=TwoWay}" /> I still have to figure out how to tell the control to use the data context of the control that is housing it... if I do figure it out, I will post it here... or if any of you know, please shed some light. Thanks again to those that responded. A: I guess the SelectedAccountChanged method updates the field and thereby causes infinite recursion which results in a stack overflow. To test: remove the SelectedAccountChanged from the DependencyProperty.Register call to make sure that this is the sources of the error and then examine the method itself. If you need help post the method there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get word under current cursor position in textarea in flex 4 I'm using flex4 for creating an editor. There I need to get word under current cursor position. say for example, this is the text in textarea, "Hi, this is a sample" and cursor under "this" word. If I click a button, then this "this" word must be returned. All this I need to implement in flex4 and actionscript3. Please provide any kind of suggestion or help. A: Take a look at TextField.caretIndex. It is the index position of the cursor in the textfield. Then you need to extract the current word using that position. One way is to look for spaces in both directions but I am sure there is some fancy Regular Expression out there that can do it for you using the caret index. A: I needed such a function for code hinting, this approach works nicely: public function currentWord(ta:RichEditableText):String { var wordBegin:int = ta.selectionAnchorPosition; var wordEnd:int = ta.selectionAnchorPosition; // while the previous char is a word character... let's find out where the word starts while (ta.text.charAt(wordBegin-1).search(/\w+/) > -1 && wordBegin > 0 ) { wordBegin--; } // while the next char is a word character... let's find out where the word ends while (ta.text.charAt(wordEnd).search(/\w+/) > -1 && wordEnd > 0 ) { wordEnd++; } return ta.text.substring(wordBegin, wordEnd); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7624290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CABasicAnimation increase width with static left-side origin point I'm trying to make a simple animation using Core Animation to draw a simple bar that grows (like a progress bar). So, the bar starts at x = 0 with 0 width and grows to fit the frame. But, when I animate bounds.size.width, the origin point is considered the center of the layer and it grows outwards in both x directions, whereas I want it the furthest left point of the bar to always be 0 and the furthest right to change with the animation -- again, like a progress bar. Do I have to animate an additional property or is there something other than bounds.size.width I should be using to achieve this? For reference, here's what I have right now: CABasicAnimation * animation; animation = [CABasicAnimation animationWithKeyPath:@"bounds.size.width"]; animation.fromValue = [NSNumber numberWithInt:0]; animation.toValue = [NSNumber numberWithInt:(self.frame.size.width / 2)]; [animation setValue:@"primary_on" forKey:@"animation_key"]; animation.duration = duration; [primaryMask addAnimation:animation forKey:@"primary_on"]; (primaryMask is a CALayer) Same thing happens in this scenario: animation = [CABasicAnimation animationWithKeyPath:@"bounds"]; CGRect oldBounds = CGRectMake(0, 0, 0, self.frame.size.height); CGRect newBounds = CGRectMake(0, 0, self.frame.size.width / 2, self.frame.size.height); animation.fromValue = [NSValue valueWithCGRect:oldBounds]; animation.toValue = [NSValue valueWithCGRect:newBounds]; A: You need to set layer.anchorPoint = CGPointZero; By default this property is {0.5, 0.5} which is the centre of the layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: OpenCV-"Homogeneous coordinates are not supported" when using cvProjectPoints2 "OpenCV Error: Bad argument (Homogeneous coordinates are not supported ) in unknown function, file ......\modules\calib3d\src\calibration.cpp, line 826" I think I'm getting this error when passing the following matrix into cvProjectPoints2() function CvMat *dstPoints2D = cvCreateMat (4, 1, CV_32FC3); cvProjectPoints2(srcPoints3D,rotation,translation,intrinsic_matrix,NULL,dstPoints2D); I'm using OpenCV 2.3.0 Full code: http://pastebin.com/TYthn6Nt Thanks in advance. A: The output needs to be two channels. Change the declaration to CvMat *dstPoints2D = cvCreateMat (4, 1, CV_32FC2); and you won't get the error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I automatically create an email address for anyone who signs up at my website? I know that just about the same thing was asked here: How can I... but I would like to use Google's servers because of blacklisting, is there any way for me to do this? Basically how can I have Google's servers route/forward the email to a PHP script? Also, it would be very useful to me if someone has the PHP code itself (if anyone has the script/code in any other programming language then I can do that to). Thank you all in advance. A: You can use Google Apps Enterprise, which has an API for creating users. Alternatively, you can set all email to go to a single catch-all address and read the To: field when checking email. Either way, you'll need to read the email using a POP or IMAP client in PHP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Garbage collection and property syntax I have a class that needs information from an xml file. I have another class which is constructed to meet that need. Once the information required is in the first class I want the xml reader to be garbage collected. Now the xml reader gets the information required and stores it in private fields. The first class queries these fields and retrieves the information. I know that if I query the fields using functions provided in the xml reader there will be no residual linkage, will this also be the case if I use properties in the xml reader? public float Var { get { return someVar; } set { someVar = value; } } A: Not quite clear your question. You could use the XmlReader in a using if you want to allow that instance to be garbage collected once you process your XML file. Assigning the properties to private variables as you have said sounds correct. GC can collect the XmlReader instance if there are no live references. You could try below example. using statement, defines a scope, outside of which an object or objects will be disposed. It's a good practice to call the Dispose method for objects like XmlReader that have file handlers. var myProperties; using (XmlReader reader = XmlReader.Create("file1.xml")) { while (reader.Read()) { // myProperties = reader.....; } } } Above code is a good way to check whether there is any issue with garbage collection because it will throw an exception in any case if you try to refer XmlReaders properties out side of the using statement. If you have assigned the values to private variables that should be fine. A: If you have a reference to the XmlReader (eg, in a field in your class), it cannot be garbage-collected while the owning instance is still alive. Once you don't have any references to it, it will be garbage-collected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NoSuchElementException error for which I have created a catch clause int num_lines = 0; try { if (file_stream.hasNextInt()) //line 81 { num_lines = file_stream.nextInt(); } } catch (NoSuchElementException e) { System.err.println("The input is not valid and cannot be processed."); } I keep getting this error even though I seem to have accounted for it in the code. The file_stream file is empty in this test case, so I wanted to see if the program would catch the error and apparently it fails to do so: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Program1.main(Program1.java:81) A: NoSuchElementException exception will be thrown when the iteration has no more elements where as the Scanner class methods return tokens. From JavaDoc : A simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. For instance, List<Integer> ints=new ArrayList<Integer>(); try { int value=ints.iterator().next(); }catch(NoSuchElementException ex) { System.out.println(ex); } A: I think you might be looking at the wrong place in the code. Unless you have multiple threads reading from that stream, there's no way you can get a NoSuchElementException after hasNextInt() returns true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to check whether the UITableViewCells are blank I am using indexpathforvisiblerows which gives the indexpaths of the visible rows in uitableview. How can i check for the blank cells in the returned indexpaths?. ` NSArray *visiblePaths = [self.rootViewController.accountTableView indexPathsForVisibleRows]; for (NSIndexPath *indexPath in visiblePaths) { UITableViewCell *cell = [self.rootViewController.accountTableView cellForRowAtIndexPath:indexPath]; // I am getting the issue when i call this function cell.detailTextLabel.text = [self getLastCallDate:indexPath]; } // getLastCallDate function Account *account = [self.fetchedResultsController objectAtIndexPath:indexPath]; NSString *lastCallDate; if ([[account Calls] count] > 0) { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"YYYY-MM-dd"]; Call *call = [[account Calls] objectAtIndex:0]; lastCallDate = [NSString stringWithFormat:@"Last Call Date: %@",[dateFormatter stringFromDate:call.date]]; //NSLog(@"detail - %@", cell.detailTextLabel.text); [dateFormatter release]; return lastCallDate; } else lastCallDate =@""; return lastCallDate; ` While searching fetched results controller will not have the values as many as the visible rows which leads to array bound execption A: Before calling getLastCallDate:, check whether indexPath.row is less than the number of items in your data source. Something like- for (NSIndexPath *indexPath in visiblePaths) { if(indexPath.row < [self.items count]) //items is your data source array { //your code } } A: I'm assuming that you have a plain UITableView without section header, just rows. Then the number of rows shown on the display tableView.frame.size.height / tableView.rowHeight. Subtract the number of visible rows. With the above algorithm I get total rows 16 visible cells 5. Now it's up to you to calculate 16 - 5.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala final variables in constructor I'm still pretty new to Scala, but I know you can define class variables that are initialized in the constructor like class AClass(aVal: String) which would be like doing the following in java class AClass { private String aVal; public AClass(String aVal) { this.aVal = aVal; } } In Java, I would declare aVal as final. Is there a way to make the aVal variable final in the Scala syntax? EDIT: Here is what I am seeing when I compile the following Scala class: class AClass(aVal: String) { def printVal() { println(aVal) } } I ran javap -private and got the output public class AClass extends java.lang.Object implements scala.ScalaObject{ private final java.lang.String aVal; public void printVal(); public AClass(java.lang.String); } When I change the scala class definition to have class AClass(**val** aVal: String) I get the following output from javap -private public class AClass extends java.lang.Object implements scala.ScalaObject{ private final java.lang.String aVal; public java.lang.String aVal(); public void printVal(); public AClass(java.lang.String); } The public method aVal is generated. I'm still learning here - can anyone explain why that is generated? Note I am using scala 2.9 A: Copied from my answer: Scala final vs val for concurrency visibility There are two meanings of the term final: a) for Scala fields/methods and Java methods it means "cannot be overridded in a subclass" and b) for Java fields and in JVM bytecode it means "the field must be initialized in the constructor and cannot be reassigned". Class parameters marked with val (or, equivalently, case class parameters without a modifier) are indeed final in second sense, and hence thread safe. Here's proof: scala> class A(val a: Any); class B(final val b: Any); class C(var c: Any) defined class A defined class B defined class C scala> import java.lang.reflect._ import java.lang.reflect._ scala> def isFinal(cls: Class[_], fieldName: String) = { | val f = cls.getDeclaredFields.find(_.getName == fieldName).get | val mods = f.getModifiers | Modifier.isFinal(mods) | } isFinal: (cls: Class[_], fieldName: String)Boolean scala> isFinal(classOf[A], "a") res32: Boolean = true scala> isFinal(classOf[B], "b") res33: Boolean = true scala> isFinal(classOf[C], "c") res34: Boolean = false Or with javap, which can be conveniently run from the REPL: scala> class A(val a: Any) defined class A scala> :javap -private A Compiled from "<console>" public class A extends java.lang.Object implements scala.ScalaObject{ private final java.lang.Object a; public java.lang.Object a(); public A(java.lang.Object); } If the class parameter of a non-case class is not marked as a val or var, and it is not referred to from any methods, it need only be visible to the constructor of the class. The Scala compiler is then free to optimize the field away from the bytecode. In Scala 2.9.1, this appears to work: scala> class A(a: Any) defined class A scala> :javap -private A Compiled from "<console>" public class A extends java.lang.Object implements scala.ScalaObject{ public A(java.lang.Object); } A: class AClass(aVal: String) In this code, aVal is a final variable. So You already have a final variable. class AClass(val aVal: String) In this code, aVal is final and you have getter of aVAl. So you can use it like below scala> val a= new AClass("aa") a: A1 = A1@1d7d58f scala> a.aVal res2: String = aa And finally, class AClass(var aVal: String) In this code, aVal is not final and you have getter and setter of aVal. So you can use it like below scala> val a= new AClass("aa") a: AClass = AClass@1c059f6 scala> a.aVal res3: String = aa scala> a.aVal = "bb" a.aVal: String = bb scala> a.aVal res4: String = bb
{ "language": "en", "url": "https://stackoverflow.com/questions/7624302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Unable to run Leak Instruments in xcode I am using xcode 4 and tried to run the leaks tool by clicking on the Product > Profile button in the top menu. I checked that I am using the development provisioning profile when running the tool (no issues with running the app in 'run' mode'. However, I got the following error. Any advise on how I can overcome this problem? A: I got around it by running normally via Xcode to install the app but then quitting and relaunching the app directly from Instruments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Stack Trace - Where is error shown? Why can't I see the method that throws the runtime exception in Android? Or is it there and I don't understand how to read the stack trace? In Flash, it's easy to see where the error is thrown. In Android, it not easy. Maybe because it throws in a different thread. I have no idea. Attached are the sceens. Can you see where the error is thrown in the stack trace? A: The issue is that you haven't let the stack trace "unroll" out enough yet. When the exception is thrown, you have to keep stepping through until you see the exception appearing within LogCat (which you should be able to see in the default Debug View). For example, here is my code: public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); throw new RuntimeException("Exception"); //setContentView(R.layout.main); } } When the exception is finally thrown all the way up the stack, I will finally see this within my LogCat window: If you look here, you can see at the top of the stack trace, the thrown exception. However, this doesn't tell you a whole lot (except what happened). Towards the bottom of the LogCat window, you can see what the actual cause was from (which you'll see once the entire exception unrolls). In this particular case, it occurred in my HelloAndroid.onCreate() method (which I have selected). When you double-click on this line, you will be taken to your code and where the exception actually occurred. A: I've never used debug mode but I use the LogCat View. You activate it in Window --> Show View --> Other --> Android --> LogCat. If an exception is thrown, the log show it in red. In my experience, the real problem never appear at the beginning of the exception, it appears after the line "Caused By" There you will see in which line in your code the exception was generated and be able to go there by simply double clicking it. A: Debug stacktrace mode does not show it. Logcat may.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Convert a 'const wchar_t *' to 'unsigned char *' In C++ is it possible to convert a 'const wchar_t *' to 'unsigned char *'? How can I do that? wstring dirName; unsigned char* dirNameA = (unsigned char*)dirName.c_str(); // I am creating a hash from a string hmac_sha256_init( hash, (unsigned char*)dirName.c_str(), (dirName.length)+1 ); A: Try using reinterpret_cast. So: unsigned char * dirNameA = reinterpret_cast<unsigned char *>(dirName.c_str()); That might not work because c_str returns a const wchar_t *so you can also try: unsigned char * dirNameA = reinterpret_cast<unsigned char *>( const_cast<wchar_t *>(dirName.c_str()) ); This works because hmac_sha256_init should accept a binary blob as its input, so the unicode string contained in dirName is an acceptable hash input. But there's a bug in your code - the length returned by dirName.length() is a count of characters, not a count of bytes. That means that passing too few bytes to hmac_sha256_init since you're passing in a unicode string as a binary blob, so you need to multiply (dirName.length()) by 2. A: You need to convert character by character. There are functions like wcstombs to do this. A: Since you're using WinAPI, use WideCharToMultiByte.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: overriding axis labels after plot in R -- not working if plotting an scb object? What should I check about the object I plot to be able to override the axis labels, which remain variable names generated be the scb call instead of my specification below? scb is in the locfit library: http://cran.r-project.org/web/packages/locfit/locfit.pdf fit2<-scb(closed_rule ~ lp(bl),deg=1,xlim=c(0,1),ev=lfgrid(100), family='binomial',alpha=cbind(0,0.3),kern="parm") pdf('figure1.pdf') plot(fit2,ylab = "Predicted closed rule probability", xlab="Lobbyist bias", xlim=c(0,1), ylim=c(0,1)) dev.off() I found no relevant object of fit2 to override -- and I am not even sure why this should be necessary if I specify labels myself. I see one called varnames, that has a single element corresponding to the future x-axis label, but overriding it does not help my labels show, and the ylabel is definitely coming from some completely other place anyway. A: The axis labels are kind of predefine in the plot.scb function. If you type > plot.scb you will see that either plot.scb.1d or plot.scb.2d are used. plot.scb.1d use the content of fit2$vnames[1] for the x axis. To change the ylab value you will have to hack the function by replacing the plot line in plot.scb.1d by something like that: ... plot(x$xev, fit, type = "l", ylim = yl, ylab = "Predicted closed rule probability", xlab="Lobbyist bias") ... For plot.scb.2d it is easier xlab=fit2$vnames[1] and ylab=fit2$vnames[2]. Here, I would change the value(s) of fit2$vnames.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which Merge do I need? I am finding merge a difficult concept (inner, outer, right, left...) so forgive the simplistic question. I want to merge each column that is generated to the column that came before. labelA <- array(letters[1:10], dim=c(10,1)) ## Function: test_values ## test_func = function(df, nameA, nameB) { test_values <- array(data=1, dim=c(10,1)) for (i in 1:10){ test_values[i] <- paste(nameA, nameB, i, sep="_") } merge (x=df, y=test_values, sort=FALSE, all=TRUE) # ?? } # Comparison #1 nameA <-"A" nameB <-"B" gran_total = test_func(labelA, nameA, nameB) # Comparison #2 nameA <-"C" nameB <-"D" gran_total = test_func(gran_total, nameA, nameB) But my output is a matrix of 30 rows by 1 column. BUT I want (cannot figure out how to return) a matrix of 10 rows and 3 columns V1 V2 V3 a A_B_1 C_D_1 b A_B_2 C_D_2 c A_B_3 C_D_3 d A_B_4 C_D_4 e A_B_5 C_D_5 ... A: Probably what you need is cbind or data.frame instead of merge. Here is an example: > labelA <- array(letters[1:3], dim=c(3,1)) > # simple way > data.frame(labelA, paste("A", "B", 1:3, sep = "_"), paste("C", "D", 1:3, sep = "_")) labelA paste..A....B...1.3..sep...._.. paste..C....D...1.3..sep...._.. 1 a A_B_1 C_D_1 2 b A_B_2 C_D_2 3 c A_B_3 C_D_3 > # generalize as a function > f <- function(df, nA, nB) paste(nA, nB, 1:nrow(df), sep = "_") > data.frame(labelA, f(labelA, "A", "B"), f(labelA, "C", "D")) labelA f.labelA...A....B.. f.labelA...C....D.. 1 a A_B_1 C_D_1 2 b A_B_2 C_D_2 3 c A_B_3 C_D_3 > # more generalize for flexible arguments > f2 <- function(df, labels) + data.frame(df, do.call("cbind", llply(labels, + function(x) do.call("paste", c(as.list(x), list(1:nrow(df)), sep = "_"))))) > f2(labelA, list(c("A", "B"), c("C", "D"))) df X1 X2 1 a A_B_1 C_D_1 2 b A_B_2 C_D_2 3 c A_B_3 C_D_3 > f2(labelA, list(c("A", "B"), c("C", "D"), c("E", "F", "G"))) df X1 X2 X3 1 a A_B_1 C_D_1 E_F_G_1 2 b A_B_2 C_D_2 E_F_G_2 3 c A_B_3 C_D_3 E_F_G_3
{ "language": "en", "url": "https://stackoverflow.com/questions/7624314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: XPath select descendent of parents sibling This html is within my page: <tr> <td class="padded2" bgcolor="#103A74"><font color="White">Refine by Vehicle Types</font></td> </tr><tr> <td class="padded2" bgcolor="White"><div> <table border="0"> <tr> <td class="padded2"><font color="#103A74"><ul><li><a class="padded2"> Cars</a></li><li><a class="padded2">Marine Engines</a></li><li><a class="padded2">Trucks</a></li></ul></font></td> </tr> </table> </div></td> </tr> I'm wanting to scrape "Cars" and "Trucks" based on the fact that they are after "Refine by Vehicle Type". I've tried many diferent ways and this is as close as I can get, but returns NULL. $Nodes = $xPath->query("//tr/td/font[text()[contains(., 'Refine by Vehicle Type')]]/following-sibling::tr/td/div/table/tr/td/font/ul/li/a")->item(0)->nodeValue; What am I missing? A: Your error is in this: ...font[...]/following-sibling::tr/... It is easy to see that in the provided XML fragment, the <font> element has no sibling elements. Here is one correct XPath expression: tr[td[contains(., 'Refine by Vehicle Types')]] /following-sibling::tr /td/div/table /tr/td/font /ul/li/a When evaluated against the following XML document (your provided fragment wrapped by a <table>): <table> <tr> <td class="padded2" bgcolor="#103A74"> <font color="White">Refine by Vehicle Types</font> </td> </tr> <tr> <td class="padded2" bgcolor="White"> <div> <table border="0"> <tr> <td class="padded2"> <font color="#103A74"> <ul> <li> <a class="padded2"> Cars</a> </li> <li> <a class="padded2">Marine Engines</a> </li> <li> <a class="padded2">Trucks</a> </li> </ul> </font> </td> </tr> </table> </div> </td> </tr> </table> the following elements are selected: <a class="padded2"> Cars</a> <a class="padded2">Marine Engines</a> <a class="padded2">Trucks</a> XSLT - based verification: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/*"> <xsl:copy-of select= "tr[td[contains(., 'Refine by Vehicle Types')]] /following-sibling::tr /td/div/table /tr/td/font /ul/li/a "/> </xsl:template> </xsl:stylesheet> when this transformation is applied on the XML document above, the selected elements are output: <a class="padded2"> Cars</a> <a class="padded2">Marine Engines</a> <a class="padded2">Trucks</a> I would recommend using an XPath Visualizer to get quickly up with writing correct and elegant XPath expressions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error : Thread was being aborted when writing to xml document on asp.net I have this code to write a XML document: System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; MemoryStream stream = new MemoryStream(); XmlTextWriter myXmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8); // building xml document myXmlTextWriter.WriteEndDocument(); myXmlTextWriter.Flush(); stream.Seek(0, SeekOrigin.Begin); myXmlTextWriter.Close(); stream.Close(); response.Write( System.Text.ASCIIEncoding.ASCII.GetString(stream.GetBuffer())); Context.Response.End(); Then in the xml file, there is a line: "Error : Thread was being aborte"
{ "language": "en", "url": "https://stackoverflow.com/questions/7624316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB.net Cascading ComboBoxes Connected to DataSet from Access - Changing Units, & Decimal to Fractions I've got a fairly complex ComboBox scenario, and being new to programming I'm struggling with what the best approach to take is. I have a DataSet with a DataTable that has several numeric columns of Data. The numeric data is composed of distances given in U.S. Standard units. I currently have my ComboBoxes set up and working, but I need to expand on what I currently have in two ways. * *I need to be able to convert the Decimal numbers in my data column being displayed to Fractions, is there a way to do this and maintain databinding? In this case its the Display Member of the data source... *I need to be able to display my drop down options in different sets of units... I've written Unit Conversion classes to help take care of this, but I don't know if I can somehow do this as well and maintain databinding? I'd like to convert the units on the display members as well... Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted Select Case ComboBox1.SelectedItem Case "Tire1" With ComboBox2 .DataSource = Tire1BindingSource .ValueMember = "OD" .DisplayMember = "OD" End With Case "Tire2" With ComboBox2 .DataSource = Tire2BindingSource .ValueMember = "OD" .DisplayMember = "OD" End With Case "Tire3" With ComboBox2 .DataSource = Tire3BindingSource .ValueMember = "OD" .DisplayMember = "OD" End With Case "HubCap" ComboBox3.DataSource = Nothing With ComboBox2 .DataSource = HubcapBindingSource .ValueMember = "ID" .DisplayMember = "ID" End With End Select End Sub Private Sub ComboBox2_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox2.SelectionChangeCommitted Select Case ComboBox1.SelectedItem Case "Tire1" With ComboBox3 .DataSource = Tire1BindingSource .ValueMember = "ID" .DisplayMember = "Weight" End With Case "Tire2" With ComboBox3 .DataSource = Tire2BindingSource .ValueMember = "ID" .DisplayMember = "Weight" End With Case "Tire3" With ComboBox3 .DataSource = Tire3BindingSource .ValueMember = "ID" .DisplayMember = "Weight" End With Case "HubCap" ComboBox3.DataSource = Nothing With ComboBox2 .DataSource = HubCapBindingSource .ValueMember = "ID" .DisplayMember = "ID" End With End Select What is the best approach for using ComboBoxes when dealing with issues such as displaying fractions and units... A: Yes you can draw fractional without affecting DataBindings. You have to set DrawMode property and handle DrawItem and MeasureItem events. For more information read this MSDN article;
{ "language": "en", "url": "https://stackoverflow.com/questions/7624318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VirtualStringTree Correct/recommended use I have been using virtualstringtree for a while now. I use it for two different things, first a s a normal tree for selecting ,displaying data and secondly as a grid to show outputs from SQL statements. All my data loaded in to the trees is from a database. For the tree example, i have a parentId field to distinguish the heirarchy, and for the grid examples i simply use an SQL statement with a customized record for each tree (that is unique). My questions relates to the preferred/best way to populate the tree. I have read from the VST docs that you should use the onInitNode event along with rootnodecount. However i have found that using the AddChild() method to be very similar, even though it is not encouraged. Let me show some (simplified) examples: 1. Heirarchy type PData = ^rData; rData = packed record ID : Integer; ParentID : Integer; Text : WideString; end; procedure Loadtree; var Node : PVirtualNode; Data : PData; begin Q1 := TQuery.Create(Self); try Q1.SQL.Add('SELECT * FROM Table'); Q1.Open; Q1.Filter := 'ParentID = -1'; //to get the root nodes Q1.Filtered := True; while not Q1.Eof do begin Node := VST.AddChild(nil); Data := VST.GetNodeData(Node); Data.ID := Q1.Fields[fldID].AsInteger; Data.ParentID := Q1.Fields[fldParentID].AsInteger; Data.Text := Q1.Fields[fldText].AsString; //now filter the query again to get the children of this node PopulateChildren(Data.ParentID,Node); //add children to this node and do it recursively Q1.Next; end; finally Q1.free; end; end; 2. Grid procedure LoadGrid; var Node : PVirtualNode; Data : PData; begin Q1 := TQuery.Create(self); try Q1.SQL.Add('SELECT * FROM Table'); Q1.Open; while not Q1.eof do begin Node := VST.AddChild(nil); Data.ID := Q1.Fields[fldID].AsInteger; Data.Text := Q1.Fields[fldText].AsString; Q1.Next; end; finally Q1.Free; end; end; So essentially i am bypassing the RootNodeCount and OnInitNode methods/property and using the old fashioned way to add nodes to the tree. It seems to work fine. Note in the example i create and destroy my queries at runtime. The reason i started using the tree in this manner is that i could load all the data in the tree once and then free the TQuery after i had finished using it. I was thinking that regardless of keeping the TQuery alive/created i would still need to use my rData record to store the data, hence using up more memory if i did not destroy the TQuery. Currently my application uses about 250+MB when fully loaded, and can increase when i run SQL reports and display them in the VST. I have seen it use about 1GB of ram when i have run a SQL report with 20000+ nodes and 50+ columns. What i would like to know if the way i am using the VST incorrect with regards to minimizing memory usage? Would i be better off creating a query for the lifetime of the tree and using the onInitNode event? So that when data is requested by the tree it fetches it from the TQuery using the onInitNode/OnInitChildren event (i.e. the pure virtual paradigm of the tree)? Thus i would need to keep the TQuery alive for the duration of the form. Would there be any memory benefit/performance benefit in using it this way? In the above situations the i can see the difference for the grid example would be far less (if any) than the heirarchy - due to the fact that all nodes need to be initialized when populated. A: The reason why AddChild() is not encouraged is that it breaks the virtual paradigm of the component - you create all the nodes, even though you may never need them. Say the query returns 100 records but the tree shows 10 nodes at the time. Now if the user nevers scrolls down you have wasted resources for 90 nodes as they are never needed (don't became visible). So if you're worried about memory usage, AddChild() is bad idea. Another thing is that if the resultset is big, populating the tree takes time and your app isn't responsive at that time. When using virtual way (RootNodeCount and OnInitNode) the tree is "ready" immediately and user doesn't experience any delay. Then again, in case of (relatively) small resultsets using AddChild() might be the best option - it would allow you to load data in one short transaction. Ie in case of tree structure it would make sense to load whole "level" at once when user expands the parent node. Using DB with VT is a bit tricky as the DB query is special resource too, with it's own constraints (you want to keep transactions short, it is relatively slow, the DB might only support one way cursor etc). So I'd say it is something you have to decide on each individual case, depending on the use case and amount of data, ie * *small resultset is OK to load all at once with AddChild() or into internal data structure and then using it throught VT's events; *loading one level at time is probably good compromise for trees; *in case of very large resultsets loading in batches might give good perfomance and memory usage compromise but adds complexity to the code managing VT. A: TQuery provide array-like access to records. If you check with the documentation you can jump to each record using the RecNo property and you can jump to each field using Fields[i] (by it's index). There is no holding back using TVirtualStringTree as virtual mode connecting with database. Once you execute the query the data is available in memory as TDataSet anyway so why don't use it as a data container? PS: Accessing fields using their index is faster than FieldByName.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to create unix process binary trees? Can some one help me out here, not necessarily complete my homework. I need to create a process tree using fork(); in Unix/C so far the best I can get to to the 4th level here is my code: /* Includes */ #include <unistd.h> /* Symbolic Constants */ #include <stdio.h> /* Input/Output */ #include <stdlib.h> /* General Utilities */ int main() { pid_t childpid; pid_t pid; int i; childpid=fork(); waitpid(); i=0; for (; i<1; i++) { int b=0; for (; b<1;b++) { childpid=fork(); fprintf(stderr,"the value of i is %d, i am %ld , my parent is %ld\n", i, (long)getpid(), (long)getppid()); if (childpid==0) { break; } } if (childpid==0) { break; } } sleep(1); } I am very new to C programming, well programming in general, so I wanted to ask the general public what steps I am missing. The tree depth needs to be user specified so I figured I would use n a for loop but that only multiplies across a level rather than creating new levels. Can someone help me out and point me in the right direction :) I need it to fork like this i / \ / \ / \ / \ / \ i i / \ / \ / \ / \ i i i i / \ / \ / \ / \ i i i i i i i i A: The waitpid() function requires arguments. The initial childpid = fork(); is unexpected. You can sensibly write: for (int i = 0; i < 1; i++) for the loops unless you insist on using C89 instead of C99 syntax. Attempt 2 Example output Start 46480 i am 46480, my parent is 30775 i am 46482, my parent is 46480 i am 46481, my parent is 46480 i am 46483, my parent is 46481 i am 46484, my parent is 46482 i am 46486, my parent is 46482 i am 46487, my parent is 46483 Exit 46487 i am 46488, my parent is 46484 Exit 46488 i am 46485, my parent is 46481 i am 46491, my parent is 46484 Exit 46491 i am 46489, my parent is 46483 Exit 46489 Exit 46483 i am 46492, my parent is 46486 Exit 46492 Exit 46484 i am 46490, my parent is 46486 Exit 46490 i am 46493, my parent is 46485 Exit 46493 Exit 46486 Exit 46482 i am 46494, my parent is 46485 Exit 46494 Exit 46485 Exit 46481 Exit 46480 Example source #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> static pid_t fork_ok(void) { pid_t pid; if ((pid = fork()) < 0) { fprintf(stderr, "Fork failure in pid %d\n", (int)getpid()); exit(1); } return pid; } int main(void) { fprintf(stderr, "Start %d\n", (int)getpid()); for (int level = 0; level < 3; level++) { if (fork_ok() == 0 || fork_ok() == 0) continue; break; } fprintf(stderr, "i am %d, my parent is %d\n", (int)getpid(), (int)getppid()); while (wait(0) > 0) ; fprintf(stderr, "Exit %d\n", (int)getpid()); return(0); } This uses a loop, a somewhat unusual loop. At each level, the parent process forks two children; the children each 'continue' to the next level, while the parent is done and exits the loop. The clean up code is the same as before (see below). Recursive variant #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> static pid_t fork_ok(void) { pid_t pid; if ((pid = fork()) < 0) { fprintf(stderr, "Fork failure in pid %d\n", (int)getpid()); exit(1); } return pid; } static void new_level(int level) { if (level > 3) return; if (fork_ok() == 0 || fork_ok() == 0) new_level(level+1); else { printf("i am %d, my parent is %d\n", (int)getpid(), (int)getppid()); while (wait(0) > 0) ; printf("Exit %d\n", (int)getpid()); } } int main(void) { printf("Start %d\n", (int)getpid()); fflush(0); new_level(0); return(0); } Attempt 1 I'm not convinced you need any loops. This seemed to do the trick for me: Example output Start 44397 i am 44397, my parent is 30775 i am 44400, my parent is 44397 i am 44401, my parent is 44397 Exit 44401 i am 44399, my parent is 44397 i am 44398, my parent is 44397 i am 44404, my parent is 44400 Exit 44404 i am 44403, my parent is 44399 i am 44402, my parent is 44398 i am 44405, my parent is 44398 i am 44407, my parent is 44398 Exit 44407 Exit 44400 i am 44406, my parent is 44399 Exit 44406 i am 44408, my parent is 44402 i am 44410, my parent is 44402 i am 44411, my parent is 44405 Exit 44410 Exit 44411 i am 44409, my parent is 44403 Exit 44409 Exit 44405 i am 44412, my parent is 44408 Exit 44412 Exit 44403 Exit 44399 Exit 44408 Exit 44402 Exit 44398 Exit 44397 Source Code #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> int main(void) { fprintf(stderr, "Start %d\n", (int)getpid()); if (fork() < 0 || fork() < 0 || fork() < 0 || fork() < 0) { fprintf(stderr, "Fork failure in pid %d\n", (int)getpid()); exit(1); } fprintf(stderr, "i am %d, my parent is %d\n", (int)getpid(), (int)getppid()); while (wait(0) > 0) ; fprintf(stderr, "Exit %d\n", (int)getpid()); return(0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7624325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Shouldn't css3 transitions animate between height: 100% and height: 200px? css3 transitions will interpolate the state of the height of a div. Currently, chrome13 will not interpolate if you set the height with a different unit than the previous height i.e.: * set height to 100% * set height to 50% (on a different rendering frame) * height will animate correctly (assuming proper use of transition) * set height to 100px * height will not animate Chrome bug? spec bug? Illustrative jsfiddle for the motivated: http://jsfiddle.net/zDywJ/21/ A: I don't think this is a bug in Chrome or in the spec. As far as I can see, CSS has no way to change a percentage into a pixel unit... so it would not have a way to compare the beginning and end in order to execute the transition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining shape objects to create a composite i have a program i have to do where i have to take individual shape objects and combine them to create a final car shape. we are given premade shapes such as front tire, back tire, body, windshield, and roof and supposed to combine them into one car shape. the code already given to me is the following: CompositeShape shape = new CompositeShape(); final double WIDTH = 60; Rectangle2D.Double body = new Rectangle2D.Double(0, WIDTH / 6, WIDTH, WIDTH / 6); Ellipse2D.Double frontTire = new Ellipse2D.Double(WIDTH / 6, WIDTH / 3, WIDTH / 6, WIDTH / 6); Ellipse2D.Double rearTire = new Ellipse2D.Double(WIDTH * 2 / 3, WIDTH / 3, WIDTH / 6, WIDTH / 6); shape.add(body); shape.add(frontTire); shape.add(rearTire); now, i have to create the compositeShape class which is where the combining takes place, but im not sure what to do in the add(Shape) method. we were also told that we were supposed to use a pathiterator method, but we werent really taught about pathiterator or what we are supposed to do with it. Im not asking for someone to tell me what exactly to code, just some helpful starter points. the first thing that came to my mind was something like this: public class CompositeShape implements Shape { Graphics2D g2; public void add(Shape shape){ g2.draw(shape); } but it doesnt work because i cant instantiate a new graphics object and i get a null pointer exception. after that, im pretty much stumped as to what to do. any help would be greatly appreciated. thanks! A: Probably, instead of drawing the Shape inside the add() method, you're just supposed to store the added Shape for drawing later. You could do that by giving CompositeShape some kind of collection to hold Shapes that are added, and that's all I'd put in the add() method. Beyond that, it would depend what other behavior CompositeShape is supposed to have. If you have to be able to draw a CompositeShape, then you'll probably be given an Graphics object to draw on. You won't have to create your own. Then drawing a CompositeShape would be drawing all of the Shapes that it contains. A: java.awt.geom.Area can combine multiple shapes with methods add, subtract, exclusiveOr, and intersect. It's a ready-made class for CompositeShape. It seems extremely weird that you've been asked to recreate it as "CompositeShape", because Area already does what you want. The solution could be as simple as class CompositeShape extends java.awt.geom.Area {} and you're done. Or, the fact that you've been given a hint about PathIterator, it might be that you're being encouraged to manage the added shapes in a list manually, then implement all the methods of the Shape interface in terms of iterating over the other shapes. E.g., getBounds() needs to return the rectangular bounds of the shape, so get the rectangular bounds of the first, then use Rectangle.union to join it with the bounds of the others. And for getPathIterator(), return a new inner class implementing PathIterator that will iterate over all the shapes in your collection, and iterate the path segments of each of their getPathIterator methods, returning each path segment. It all sounds unnecessary in practice, since the needed class already exists. I think you should get clarification on what is wanted. Good luck. To clarify what I said about the implementation of getPathIterator, return something like this. I didn't test this. This assumes your list is called shapes. public PathIterator getPathIterator(final AffineTransform at, final double flatness) { return new PathIterator() { private PathIterator currentPathIterator; private Iterator<Shape> shapeIterator = shapes.iterator(); { nextShape(); } private void nextShape() { if (shapeIterator.hasNext()) { currentPathIterator = shapeIterator.next().getPathIterator(at, flatness); } else { currentPathIterator = null; } } public int getWindingRule() { return WIND_NON_ZERO; } public boolean isDone() { for (;;) { if (currentPathIterator == null) return true; if (!currentPathIterator.isDone()) return false; nextShape(); } } public void next() { currentPathIterator.next(); } public int currentSegment(float[] coords) { return currentPathIterator.currentSegment(coords); } public int currentSegment(double[] coords) { return currentPathIterator.currentSegment(coords); } }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7624329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Replacing the last lines of a group of text using AWK I have this output from doing various commands d41d8cd98f00b204e9800998ecf8427e 1317522632 /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document.txt d41d8cd98f00b204e9800998ecf8427e 1317522632 /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy.txt d41d8cd98f00b204e9800998ecf8427e 1317522632 /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy (2).txt d41d8cd98f00b204e9800998ecf8427e 1317506438 /home/evan/school_work/unix/Projects/Project2/finddups/.svn/tmp/tempfile.tmp 2430ffcf28e7ef6990e46ae081f1fb08 1317522636 /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2 - Copy.txt 2430ffcf28e7ef6990e46ae081f1fb08 1317506569 /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2.txt I want to pipe it through awk to make it look like this Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document.txt Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy.txt Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy (2).txt Original: /home/evan/school_work/unix/Projects/Project2/finddups/.svn/tmp/tempfile.tmp Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2 - Copy.txt Original: /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2.txt Any ideas? Some clarifications: The last file before the newline or EOF will awalys be the original file, everything before should be marked as a duplicate. The first column is the md5sum of the file, second is the modification date. You will notice the last file in a group will always have the oldest time stamp, this is the criteria I am using to determine what file is "original", the oldest file. Here are the commands im using the to get the list of all duplicates find ${PWD} -type f -exec stat -c %Y {} \; -exec md5sum '{}' \; | sed -r 'N;s/([0-9]+)\n([^ ]+) /\2 \1/g' | sort -r | uniq -w 32 --all-repeated=separate A: Sort the lines (using sort), store the hash in a temporary variable and compare it with the current using an if statement. Another if statement should get rid of possible blank lines. For example: | sort | awk '{ if ($0) { if (TEMP != $1) { print "Original: " $0 } else { print "Duplicate:" $0 } TEMP = $1 } }' Edit: Since you provided those clarifications, you could do it this way: | tac | awk '{ if ($0) { if (TEMP != $1) { print "Original: " $0 } else { print "Duplicate:" $0 } TEMP = $1 } else { print "" } }' | tac tac inverts the line order, achieving exactly what sort did in the first example. The second tac restores the original order. A: This sed oneliner might work: sed '$G' source | # append a newline to source sed -nr '$!{N;s/^([^ ]+ )[^ ]+ +(.*\n)\1/Duplicate: \2\1/;s/^[^ ]+ [^ ]+ +(.*\n)$/Original: \1/;P;D}' By appending a newline to the source file the problem becomes two substitutions negating any EOF inelegance. I guess a sed solution is acceptable as you used sed in the source file prep. A: How do you know what's a duplicate and what's a copy? That would be my question. It would be easy if the duplicates all had Copy in the name, but your first example, one of the first duplicates is called New Text Document.txt, and the original is in the .svn directory which should never have been looked at. It looks like you have the MD5 hash in the first column which means you could sort on that, and then use awk to loop through your output and print a blank line whenever the hash changes. That would group your files together. The original vs. copy is going to be much more difficult. You'll have to work out a good criteria for that. You might choose the earliest modification date (mdate). You could sort on that too. When you break on the hash, you could simply assume the first file in the list (because it has the earliest date) to be the original. Or, you could simply assume that the ones with the word Copy embedded in the file name are the copies. And, then, it might not really matter all that much. Do you want the program to merely identify duplicates or delete them? If the program is merely identifying duplicates, there's no need to figure out which ones are the original and which ones are the duplicates. You can probably do that better with your eye than any algorithm. By the way, what exactly are the three columns. I'm assuming the first is a has, and the last is the file name, but what is the middle one? A: Maybe this will work, if blank lines appear after the last line of each group, including the very last group, and if the file names never contain blanks. It hinges on the presence of the blank lines. awk 'NF == 3 { if (save != "") { printf("Duplicate: %s\n", save); } save = $3; } NF == 0 { printf("Original: %s\n", save); save = ""; }' If the last blank line is missing, the last line will not be printed. This doesn't work because of the blanks in the file names (so most lines do not have just 3 fields). Awk is not really the most appropriate tool. I tend to use Perl when Awk is not suitable: #!/usr/bin/env perl use strict; use warnings; my $save = ""; while (<>) { chomp; if ($_ =~ m/^ (?:[\da-fA-F]+) \s+ (?:\d+) \s+ (\S.*)/x) { print "Duplicate: $save\n" if $save ne ""; $save = $1; } else { print "Original: $save\n\n"; $save = ""; } } This produces: Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document.txt Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy.txt Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New Text Document - Copy (2).txt Original: /home/evan/school_work/unix/Projects/Project2/finddups/.svn/tmp/tempfile.tmp Duplicate: /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2 - Copy.txt Original: /home/evan/school_work/unix/Projects/Project2/finddups/test/New folder/junk2.txt If you must use Awk, then you'll need to work on $0 when NF >= 3, removing the hash and inode number (or whatever the second value on the data line is) to find the filename. A: awk '{ for (i = 0; ++i < NF;) print "Duplicate:", $i print "Original:", $NF }' FS='\n' RS= infile
{ "language": "en", "url": "https://stackoverflow.com/questions/7624331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: randomly select some numbers c# Let's say we have this numbers 51,53,58,60,78. How can we select a number randomly in such a way if its already selected/picked, it will not be selected in the next run. Also, after all numbers are selected, everything is restarted and the process repeats itself. A: Put the numbers into an array and then do the Knuth Shuffle on the array. The contents of the array are then in a random order, and if you iterate through it, you won't get repeats. Be careful; it is easy to get the shuffle wrong. A: Load your integers into an array. Create an instance of the Random class. Call the Random.Next(int minValue, int maxValue) method with 0 being the minValue, and your array count minus 1 being your maxValue. Then use that random integer to reference your integer array. Random rnd = new Random(); int nextArrayIndex; int[] randomNumbers = new int[] {51, 53, 58, 60, 78}; nextArrayIndex = rnd.Next(0, randomNumbers.Count() - 1); Console.Writeline("Random Value: {0}", randomNumbers[nextArrayIndex].ToString()); Edit: for non repeating data, just store the index that was already use of the integer array in a separate list and prior to utilizing the random number, do a check on the list to see if it was already used. If so, then re-run the random number code. If it is full, then don't allow that to continue in an endless loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Applescript in Objective C project I am trying to run this shell script command through applescript on my mac application. It works fine in the applescript editor but when I run it in xcode as shown below, it does not work. Am I doing it wrong? NSString *asString = [[NSString alloc] initWithFormat:@"property MACaddr : \"gg:gg:gg:gg:gg:gg\"\n property WAN_IP_address : \"255.255.255.255\"\n property port_number : \"9\"\n " "on run\n set command to \"/usr/bin/php -r \" & quoted form of (\"$mac = \" & quoted form of MACaddr & \"; $porttemp = \" & quoted form of port_number & \";$ip = \" & quoted form of WAN_IP_address & \"; \" & \"" "$mac_bytes = explode(\\\":\\\", $mac); " " $mac_addr = \\\"\\\"; " " for ($i=0; $i<6; $i++) " " $mac_addr .= chr(hexdec($mac_bytes[$i]));" " $packet = \\\"\\\"; " " for ($i=0; $i<6; $i++) " " $packet .= chr(255); " "for ($i=0; $i<16; $i++) " "$packet .= $mac_addr;" " $port = $porttemp; " "$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);" "socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE);" "socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port);" "socket_close($sock);\") " "do shell script command \n" "end run" ]; NSLog(@"the applescript %@", asString); NSAppleScript *asScript = [[NSAppleScript alloc] initWithSource:asString]; [asScript executeAndReturnError:nil]; [asString release]; [asScript release]; Here is the exact applescript that runs fine in my Applescript editor. I have edited the above part with the correct backslashes and all and its the same as my applescirpt which works. However, it still does not work in xcode and the magic packet is not being sent. (using wireshark to monitor this.) any ideas whats wrong? I even added the on run part. property MACaddr : "gg:gg:gg:g4:g5:gg" property WAN_IP_address : "255.255.255.255" property port_number : "9" on run set command to "/usr/bin/php -r " & quoted form of ("$mac = " & quoted form of MACaddr & "; $porttemp = " & quoted form of port_number & ";$ip = " & quoted form of WAN_IP_address & "; " & " $mac_bytes = explode(\":\", $mac); $mac_addr = \"\"; for ($i=0; $i<6; $i++) $mac_addr .= chr(hexdec($mac_bytes[$i])); $packet = \"\"; for ($i=0; $i<6; $i++) /*6x 0xFF*/ $packet .= chr(255); for ($i=0; $i<16; $i++) /*16x MAC address*/ $packet .= $mac_addr; $port = $porttemp; $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE); socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port); socket_close($sock); ") do shell script command end run anyways, I have got it working FINALLY. no idea what exactly it was but here is the code for someone who wants to run a php script for WOL(wake on lan) magic packet through PHP as a shell script by applescript in a objective c environment. yup. here is the editied and working one: NSString *asString = [[NSString alloc] initWithFormat:@"property MACaddr : \"gg:gg:gg:gg:gg:gg\"\n property WAN_IP_address : \"255.255.255.255\"\n property port_number : \"9\"\n " "on run\n set command to \"/usr/bin/php -r \" & quoted form of (\"$mac = \" & quoted form of MACaddr & \"; $porttemp = \" & quoted form of port_number & \";$ip = \" & quoted form of WAN_IP_address & \"; \" & \"\n" "$mac_bytes = explode(\\\":\\\", $mac);\n " " $mac_addr = \\\"\\\";\n " " for ($i=0; $i<6; $i++) " " $mac_addr .= chr(hexdec($mac_bytes[$i]));\n" " $packet = \\\"\\\";\n " " for ($i=0; $i<6; $i++)\n " " $packet .= chr(255);\n " "for ($i=0; $i<16; $i++)\n " "$packet .= $mac_addr;\n" " $port = $porttemp;\n " "$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);\n" "socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE);\n" "socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port);\n" "socket_close($sock);\")\n " "do shell script command \n" "end run" ]; NSLog(@"the applescript %@", asString); NSString *script2 = [asString stringByReplacingOccurrencesOfString:@"gg:gg:gg:gg:gg:gg" withString:AirportMAC]; NSAppleScript *asScript = [[NSAppleScript alloc] initWithSource:script2]; [asScript executeAndReturnError:nil]; [asString release]; [asScript release]; Thank you all so much for your help! A: Never do this: NSLog([asScript stringValue]); Always do this: NSLog("%@",[asScript stringValue]); Passing unknown format strings to NSLog() is a quick path to the crash bin. A: Definitely an issue with the backslashed characters. NSLog your asString variable and try running that printed code in the editor and you'll see the error. Where you have quotes within the string, you'll need triple backslashes! "$mac_bytes = explode(\":\", $mac); " should be "$mac_bytes = explode(\\\":\\\", $mac); " and in other places as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to "accept" nested class object instances by running a custom method before to store those? I am using Ruby on Rails 3.1.0 and I would like to run a :reject_if method (as described in the official documentation related to the accepts_nested_attributes_for method in the "One-to-many" association section) on class object instances "at all" (that is, to run the :reject_if method not on attributes - as made in the linked documentation - but on records that should be "subsequently" stored in the database). In few words, I would like to reject\filter some nested model\class object instances that should be stored in the database by running a custom method on those instances. For example, if I have the following: class User < ActiveRecord::Base has_one :article, accepts_nested_attributes_for :article end I would like to make something like this (the following code does not work): class User < ActiveRecord::Base has_one :article, # Note: by using 'article' in the block I (would like to) refer to class # object instances accepts_nested_attributes_for :article, :reject_if => { |article| article.can_be_created? } end class Article < ActiveRecord::Base def can_be_created? true if user.has_authorization? end end Is it possible? If so, how can I make that? A: Make a method that returns a boolean, and give the method name as a symbol to :reject_if, eg: accepts_nested_attributes_for :article, :reject_if => :article_uncreateable? def article_uncreateable? !Article.new(article_attributes).can_be_created? end
{ "language": "en", "url": "https://stackoverflow.com/questions/7624349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a 'IsInDesignMode' property in WinRT? I'm trying to port my application from Phone 7 and can't find the way to detect when control is in Design mode. Got it - Windows.ApplicationModel.DesignMode.DesignModeEnabled A: I am using this: if (Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator) and this _isInDesignMode = Windows.ApplicationModel.DesignMode.DesignModeEnabled to check the current developing situation
{ "language": "en", "url": "https://stackoverflow.com/questions/7624351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Combo preference in Android My desired custom preference looks very much like the out-of-box EditTextPreference, only that it behaves like a "split button" which combines two Preferences: if user clicks on the text on the left, the edit text dialog pops up; which allows user to set the "label" for the preference; if user clicks on the button on the right, another window pops up that allows user to set the "date" for the preference. I guess I could extend EditTextPreference but I am not sure how I can maintain two separate keys for a single preference control (or "widget" in Android's term). Or is it possible to "mix up" two Preferences without subclassing? A: Really you do not have to use the built in preference widgets to manage your preferences; for example, in my application, i use a PreferenceScreen to bring up a multiple selection dialog with a custom listview/adapter. If you wish to handle your own key/value store, you could bind to the preference with findPreference(), set the value in the PreferenceActivity's onCreate() and persist the value in the activity's onPause(). Examining the key / value preference store can be done via getSharedPreferences(file,MODE.PRIVATE) and an associated getter method. To edit them, take the SharedPreferences object that's returned and call edit() / commit() on it once changes have been made. Does this answer you question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7624365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Any way to extend the line in the legend? Let us say I have the following graph plotted using ggplot: Is there anyway to extend how much line length is displayed in the legend? Sometimes, it just gets impossible to identify which line correspond to which line in the graph using the legend. A: here is an option legend.key.width: # sample data frame df <- data.frame(x = c(rnorm(100, -3), rnorm(100), rnorm(100, 3)), g = gl(3, 100)) df <- ddply(df, .(g), summarize, x = x, y = ecdf(x)(x)) ggplot(df, aes(x, y, colour = g, linetype = g)) + geom_line() + theme(legend.key.width = unit(10, "line")) A: opts is not working with ggplot2. You need to use theme, so instead you need to type: + theme(legend.key.width = unit(10, "line"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7624368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Python: Novice Class object prac and __main__ I've been trying to practice testing my modules by adding if __name__ == '__main__': to the end of the module. The idea is to run the module as a script, and get an output and able to import it from another script or an interactive python session. I'm using Python 2.6.6 here's the whole code class Prac: ''' This module is a practice in creating a main within a module. ''' def Fun(self): print "testing function call" if __name__ == ' __main__': Fun() A: That isn't a function, it's a method. You need to call the method off an object. p = Prac() p.Fun() Read this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Preferred way of creating links with backbone.js I'm trying to wrap my head around backbone.js but I'm finding it hard due to the lack of (IMO) good examples. First of all, what is the best way of getting a link to an object. If I want to get the edit url of an Album model I could do album.url() + '/edit', is this really the best way? Also, I'm trying to make my application work 100% without javascript so I don't want my URLs/links to say /albums/#1/edit, I want it to be /albums/1/edit and override this in JS. I'm thinking I create normal URLs and use jQuery.live to call router.navigate in backbone.js I never got this to work however, when I call router.navigate('/albums/2', true) the URL changes but my show action is never called. If I refresh it's called so the route is matched. What am I missing? A: Also, I'm trying to make my application work 100% without javascript; so I don't want my URLs/links to say /albums/#1/edit, I want it to be /albums/1/edit and override this in JS. you can do exactly this w/ pushState. just enable it in your Backbone.history.start call: Backbone.history.start({pushState: true}) this tells Backbone to use the HTML5 History API (a.k.a. "PushState"), which uses full URLs exactly like you're wanting. read up on the history api here: http://diveintohtml5.ep.io/history.html and I wrote up a 2 part series on using pushstate w/ the second part focusing on progressive enhancement in backbone, to do what you're needing: http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-1-introducing-pushstate/ and http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-2-progressive-enhancement-with-backbone-js/ hope that helps :) A: The basic answer, which is kind of frustrating, is "there is no preferred way!". Backbone.js doesn't tell you how to set up links, you can do it any way you like. I found this flexibility just as annoying as you do, at least at first. So here's the way I'm approaching this on my current project, with the (big) caveat that this is just one of many ways to do things in Backbone: * *For the most part, I don't use actual links. There's no explicit reason not to, but it means you have to keep track of a bunch of URL strings that have to be consistent. I would rather stick all the URL formatting in my routers and not deal with it elsewhere. *To open a new "top-level" view, like an editing screen, I set something that fires an event. In the application I'm currently working on, I have a global State model, and to open a new view I call state.set({ topview: MyTopView }). This causes the state object to trigger change:topview. *Any piece of the UI that needs to change when the top-level view changes has an update method bound to change:topview. When the event fires, they look at state.get('topview') and update as necessary. *I treat my routers as only marginally specialized parts of the UI - they're essentially views that render in the browser address bar, rather than the window. Like other views, they update the state object on UI events (i.e. a new URL), and like other views, they listen to the state object for changes that cause them to update. The logic that the editing screen has the URL albums/<albumid>/edit is fully encapsulated in the router, and I don't refer to it anywhere else. This works well for me, but it adds an entirely new pattern, the global State object, to the Backbone structure, so I can hardly call this the "preferred" approach. Update: Also note that .url(), in the Backbone idiom, refers to the model's URL in the back-end API, not the front-end URL (it's not like Django's get_absolute_url). There is no method in the default Backbone setup that gives you a user-facing URL for your model - you'd have to write this yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What is Select 'X'? sSQL.Append(" SELECT 'X' "); sSQL.Append(" FROM ProfileInsurancePlanYear "); sSQL.Append(" WHERE ProfileID = " + profileid.ToString() + " AND CropYear = " + cropyear.ToString()); This was a query that was originally hitting an access back end. I have moved it over to SQLCE and am perplexed about what this query is supposed to do. The table structure it hits is: ProfileID InsurancePlanID CropYear INsurance_Price Levels_XML I am assuming this would select something from the Levels_XML column where the profileid and cropyear match? Does this even work in sqlCE? A: This type of query is typically used to see if a row exists. If a row is found, the query will return a single character, X. Otherwise, it will be an empty result set... You could also say sSQL.Append(" SELECT count(*) "); sSQL.Append(" FROM ProfileInsurancePlanYear "); sSQL.Append(" WHERE ProfileID = " + profileid.ToString() + " AND CropYear = " + cropyear.ToString()); Which will return a result with either 0 or some positive number. Different approaches both asking the database simply to indicate whether or not any records existing matching the condition. A: In general, Select 'X' is used with the EXISTS, as the EXISTS predicate does not care about the values in the rows but just if those rows exist. For example:- Q.Find employees who have at least one person reporting to them. SELECT last_name, employee_id FROM employee outer WHERE EXISTS (SELECT 'X' FROM employee manager_id=outer.employee_id)
{ "language": "en", "url": "https://stackoverflow.com/questions/7624376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: LINQ to Entities integer division incorrect? I'm trying to do a little partitioning, dividing list entries into 6-month blocks. Using this LINQ to Entities query, I get results that imply that integer division is not taking place: from e in enrollments let AgeInHalfYears = e.AgeMonths / 6 select new { e.AgeMonths , AgeInHalfYears, AgeFloor = ((int)AgeInHalfYears) * 6 } My results are: AgeMonths AgeInHalfYears AgeFloor 68 11 68 41 7 41 34 6 34 I would have expected 66, 36, and 30 in that last column. I rewrote the LINQ pretty simply as AgeFloor = e.AgeMonths - (e.AgeMonths % 6) But I'm still curious about why the division operation is clearly floating point, even with that (int) cast in there... I wouldn't have expected that. A: The Entity Framework is probably ignoring your cast when generating the SQL. LINQ-based SQL generators are rarely (if ever) perfect. In particular, .Net's type system is different enough from SQL's that they probably ignore all casts. Try calling Math.Floor instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: StructureMap with Windows Forms I'm used to work with StructureMap with Web Apps... but now, I'm working on a Windows Forms project and I'd like to use it, but I don't how to configure it. In web, I'd have a bootstrapper class that is invoked on Application_Start on Global.asax, but I don't know how to do the same on WinForms. Thanks! A: You can initialize the container in the static main method that starts your application. Then retrieve your form instances from the container, so that any necessary dependencies can be injected. You could still put the initialization code in a Bootstrapper. static class Program { [STAThread] static void Main() { ObjectFactory.Initialize(...); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(ObjectFactory.GetInstance<Form1>()); } } A: For a Winforms application the counter part to Application_Start would be the main method that initializes the first Form. When using ORM mappers with web applications you generally have the thumb rule of creating a data context/session per http request. For a Winforms application you tend to go for a context per operation or per form. A: You'd structure the bootstrapping and IoC configuration in the same ways (though I'm not sure how you'd include the form classes themselves, I haven't worked with WinForms much). The only real difference that you'd need is when/where the initializer gets called. It just has to be in the startup of the application. For web applications, you do indeed call it from Application_Start. I think in WinForms apps it would be in the OnLoad event of the main form. If you have a main method anywhere (similar to a console app) then that would work as well. This could be if the WinForms app was ported from a console app, for example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7624380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }