text
stringlengths
8
267k
meta
dict
Q: Storing custom objects in NSUserDefaults I am trying to save an object in NSUserDefaults but i have not been successful in it. Scenario is that, I have an object syncObject of class SyncObjct. I have implemented following methods in SyncObject class - (NSMutableDictionary*)toDictionary; + (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary; - (id) initWithCoder: (NSCoder *)coder; - (void) encodeWithCoder: (NSCoder *)coder; And also the SyncObject class is NSCoding class. Now SyncObject class contains an NSMutableArray with name jobsArray. This array contains objects of class JobsObject. I implemented same above methods for this class as well to make it coding compliant. In toDictionary method of SyncObject class, i am storing this array in dictionary by writing following line. [dictionary setValue:jobsArray forKey:@"jobsArray"]; and I am retrieving it in getFromDictionary method of SyncOject class by writing following line. + (SyncObject*)getFromDictionary :(NSMutableDictionary*)dictionary { NSLog(@"SyncObject:getFromDictionary"); SyncObject *syncObject = [[SyncObject alloc] init]; @try { syncObject.noOfJobs = [[dictionary valueForKey:@"noOfJobs"] intValue]; syncObject.totalJobsPerformed = (TotalJobsPerformed*)[dictionary valueForKey:@"totalobsPerformed"]; syncObject.jobsArray = [dictionary valueForKey:@"jobsArray"]; } @catch (NSException * e) { NSLog(@"EXCEPTION %@: %@", [e name], [e reason]); } @finally { } return syncObject; } And also I am storing syncObject in NSUserDefault by writing following lines. NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:syncObject]; [userStorage setObject:myEncodedObject forKey:SYNC_OBJECT]; I am retrieving the object from NSUserDefaults by writing following lines NSData *myEncodedObject = [userStorage objectForKey: SYNC_OBJECT]; syncObject = (SyncObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject]; Problem is that i am not able to retrieve jobsArray correctly. Some invalid object is returned and app crashes when trying to access it. Please can anyone tell me the reason of this problem? Best Regards A: I believe the problem is that NSUserDefaults does not support storing of custom object types. From Apple's documentation when using -setObject: The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSDictionary objects, their contents must be property list objects. You can review the remaining documentation directly from Apple's NSUserDefault Class Reference manual. A: Custom class .h #import <Foundation/Foundation.h> @interface Person : NSObject @property(nonatomic, retain) NSArray *names; @property(strong,nonatomic)NSString *name; @end custom class .m #import "Person.h" @implementation Person @synthesize names; - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.name forKey:@"name"]; } - (id)initWithCoder:(NSCoder *)decoder { if((self = [super init])) { //decode properties, other class vars self.name = [decoder decodeObjectForKey:@"name"]; } return self; } @end To create Person class object and store and retrieve your stored data from NSUserDefaults Stored your object : #import "ViewController.h" #import "Person.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UITextField *textBox; @end NSMutableArray *arr; @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)saveButton:(id)sender { Person *person =[Person new]; person.name = _textBox.text; arr = [[NSMutableArray alloc]init]; [arr addObject:person]; NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:arr]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:encodedObject forKey:@"name"]; [defaults synchronize]; } - (IBAction)showButton:(id)sender { _label.text = @""; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *storedEncodedObject = [defaults objectForKey:@"name"]; NSArray *arrStoreObject = [NSKeyedUnarchiver unarchiveObjectWithData:storedEncodedObject]; for (int i=0; i<arrStoreObject.count; i++) { Person *storedObject = [arrStoreObject objectAtIndex:i]; _label.text = [NSString stringWithFormat:@"%@ %@", _label.text , storedObject.name]; } } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7635886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to optimise/scale-proof this algorithm? My website currently displays content in order of rank with a similar algorithm to this: rank = points/age The only problem is as there is more and more content added it won't be practical to generate a content rank for every piece of content on every page request. We can't put the rank in the database because it changes each second. Anyone have any ideas on how to go about optimizing this? In pseudo code: content_items = getContentFromDb(); foreach( content_items -> item ){ calRank(item); } sort(content_items); foreach( content_items -> item ){ display(item); } A: There you go, the way you now show the problem, it is quite obvious that is mainly a matter of caching the ranking information. If you want to share the caclulated rankings across a farm, I suggest a simple key/value database. There are plenty of those around, but unfortunately I haven't used any of the in any serious capacity. I suggest you read up on NoSql and perhaps look at memcached, couchdb, mongodb. However, for now, I'd just look at caching the rankings. Period. Optimize when necessary
{ "language": "en", "url": "https://stackoverflow.com/questions/7635888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the name of a data structure that acts like a shift register It has a predetermined finite size, and when you 'push' a new value on, it becomes the new 'head' and all other values are moved down the line. The last value in the list is discarded. I know of several different ways to implement this, that's not the problem. My question is, is there a standard name for this type of data structure? A: I think a queue comes closest. A: A ring buffer. A: I believe the correct name for this structure is Stack. You push new items on top of the stack, and take items from the top. Also known as LIFO (Last In First Out).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why sometimes my application stops working and gives Program received signal: “SIGABRT” error? I have four views in my navigational based application. MainView, AddView, ShowView and DetailView. MainView has a NSMutableArray. When i click on button add, then i go to AddView and then i add an object in NSMutable array of MainView. Then i come back and go to ShowView which is a tableView. From MainView i am calling createList function of ShowView like this: ShowView *show = [[ShowView alloc] init]; [show createList: self.savedObjectsList]; [self.navigationController pushViewController: show animated: YES]; [runListController release]; In ShowView createList looks like this: - (void) createRunsList: (NSMutableArray *) list{ objList = [list retain]; } where objList is NSMutableArray in ShowView. every cell of table view creates a DetailView of an object of NSMutbaleArray. Problem is sometimes my applications stop working and i get this error: 2011-10-03 15:35:55.076 RunnoIPhoneApp[2750:707] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array' *** Call stack at first throw: ( 0 CoreFoundation 0x3399964f __exceptionPreprocess + 114 1 libobjc.A.dylib 0x30b16c5d objc_exception_throw + 24 2 CoreFoundation 0x33904069 -[__NSArrayM objectAtIndex:] + 184 3 RunnoIPhoneApp 0x0000b79f -[PostRunDetailViewController createRunDetail:] + 90 4 RunnoIPhoneApp 0x0000fd2f -[RunListViewController tableView:didSelectRowAtIndexPath:] + 182 5 UIKit 0x3203f51b -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 662 6 UIKit 0x320a30eb -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 130 7 Foundation 0x32ba26d5 __NSFireDelayedPerform + 368 8 CoreFoundation 0x33970a47 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 14 9 CoreFoundation 0x33972ecb __CFRunLoopDoTimer + 850 10 CoreFoundation 0x33973845 __CFRunLoopRun + 1088 11 CoreFoundation 0x33903ec3 CFRunLoopRunSpecific + 230 12 CoreFoundation 0x33903dcb CFRunLoopRunInMode + 58 13 GraphicsServices 0x3162e41f GSEventRunModal + 114 14 GraphicsServices 0x3162e4cb GSEventRun + 62 15 UIKit 0x32019d69 -[UIApplication _run] + 404 16 UIKit 0x32017807 UIApplicationMain + 670 17 RunnoIPhoneApp 0x00002553 main + 70 18 RunnoIPhoneApp 0x00002508 start + 40 ) terminate called after throwing an instance of 'NSException' Program received signal: “SIGABRT”. warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.5 (8L1)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found). Program received signal: “SIGABRT”. (gdb) Can anybody tell me why is it happening? DetailView of some first objects works fine but then i get this error. Thanks in advance. A: Looking at the stack trace, the exception is thrown in your [PostRunDetailViewController createRunDetail:] method, which is called when you select a row in your RunListViewController's UITableView. You are trying to access an element in the array that is out of bounds. Put a break point at the start of this method and step through it in the debugger. Work out which array access is causing the exception and then think why the array might not contain the elements that you expect. A: Just comment this line [runListController release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7635890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OnItemClickListner is not working android i am using listview in android with ratingbar as well as check box, here is my problem,if i am setting onitemclick listner to the listview, it is not working? Please any one can help me.. Thanks in advance. A: Yes, I see the exact same thing. If you remove the checkbox and rating bar, then OnItemClick works, but with these widgets in your view, Android thinks the user wants to interact with them. So instead you have to handle the user click in the view itself (rather than the listview). OnTouchListener pressItemListener =new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent arg1) { HomeActivity ha = (HomeActivity) getContext(); ha.handleLocationTouchEvent(position, arg1); return false; } } newView.setOnTouchListener(pressItemListener); In the above example, HomeActivity is my parent activity. So I handle the user touch event in the custom view and then pass it off to the parent activity where you can do with it what you want. You might also want to handle onLongTouch. Hope this helps. A: In your xml file............. In checkbox.......... android:focusable="false"
{ "language": "en", "url": "https://stackoverflow.com/questions/7635891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: serializing NLog LogLevel Datatype through a WCF Web Service I have a wcf WebService with a method which takes LogLevel type (part of Nlog) as a parameter, the LogLevel is build in type comes with a framework for logging called NLog, Problem is WCF doesnt know how to marshal the loglevel parameter i guess cause its not decorated with DataContract. is there is any way i can marshal LogLevel through the webservice ? Note im trying not to wrap it in a custom class. A: You can't transport the entire LogLevel instance. But you can use the string name instead. Call your method with the property value loglevelInstance.Name and recreate a LogLevel instance at the server side using LogLevel.FromName(theString). A: It is could by due to the LogLevel being an enum. Convert it to a text, send it over and then convert it back on the client side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I read an image from a URL in Android? I want to read an image from a this URL photo and I'm using the following code public static Bitmap DownloadImage(String URL) { Bitmap bitmap=null; InputStream in=null; try { in=networking.OpenHttpConnection("http://izwaj.com/"+URL); BitmapFactory.Options options=new BitmapFactory.Options(); options.inSampleSize=8; bitmap=BitmapFactory.decodeStream(in, null, options); in.close(); } catch (Exception e) { // TODO: handle exception } return bitmap; } public class Networking { public InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in=null; int response = -1; URL url=new URL(urlString); URLConnection conn=url.openConnection(); if(!(conn instanceof HttpURLConnection)) { throw new IOException("Not an HTTP connection"); } try { HttpURLConnection httpconn=(HttpURLConnection)conn; httpconn.setAllowUserInteraction(false); httpconn.setInstanceFollowRedirects(true); httpconn.setRequestMethod("GET"); httpconn.connect(); response=httpconn.getResponseCode(); if(response==HttpURLConnection.HTTP_OK) { in=httpconn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } The bitmap always returned to me null.. I used also other functions found on the internet. all returned the bitmap as null value :S A: I would check the %20 spacing on the picture http://184.173.7.132/RealAds_Images/Apartment%20for%20sale,%20Sheikh%20Zayed%20_%201.jpg To me the %20 will not render a space so ensure this is noted in your code if you change the file to apartmentforsalesheikhzayed20201.jpg or something like as a test apartment.jpg it will work. Personally instead of using spaces in your image names i would use an underscore between the spaces so no other code is needed try_renaming_your_photo_to_this.jpg :) A: use this function it may help you. public Bitmap convertImage(String url) { URL aURL = null; try { final String imageUrl =url.replaceAll(" ","%20"); Log.e("Image Url",imageUrl); aURL = new URL(imageUrl); URLConnection conn = aURL.openConnection(); InputStream is = conn.getInputStream(); //@SuppressWarnings("unused") BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm = BitmapFactory.decodeStream(new PatchInputStream(bis)); if(bm==null) {} else Bitmap bit=Bitmap.createScaledBitmap(bm,72, 72, true);//mention size here return bit; } catch (IOException e) { Log.e("error in bitmap",e.getMessage()); return null; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conditional Rate Limiting (Nginx or Webapp)? I am implementing a REST API which requires throttling. I know that, ideally, you would place this logic in nginx. However, I have some unique constraints. Namely, I have one class of users who should NOT be rate limited. It would not be useful to implement a rate limit on a per IP basis (the nginx way). Users of the API are differentiated on a APIKey basis. Using a caching system, I could count requests per APIKEY and handle rate limiting accordingly. That involves more setup and is not as scalable, I would imagine. Any suggestions? A: You could setup multiple virtual hosts that are individually throttled at different limits. You could do your count and then redirect selected users to these virtual hosts to be throttled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing nothing to an AsyncTask in Android How do I instantiate and call and class extending AsyncTask if I am passing nothing to it? Also, I am setting a textview in the UI to the calculated result. Thanks, Ben A: Example implementation for Async without params and result Bitmap in onPostExecute result /** * My Async Implementation without doInBackground params * */ private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> { @Override protected Bitmap doInBackground(Void... params) { Bitmap bitmap; .... return bitmap; } protected void onPostExecute(Bitmap bitmap) { .... } } In your activity, you should to add this implementation: MyAsyncTask myAsyncTask = new MyAsyncTask(); myAsyncTask.execute(); A: I think what you meant to ask was how do I write an AsyncTask that doesn't ask for any parameters. The trick is to define what you expect to use as parameter and return value in the extension of your class: class MyClass extends AsyncTask<Void, Void, Void> for example doesn't expect any parameters and doesn't return any either. AsyncTask<String, Void, Drawable> expects a String (or multiple strings) and returns a Drawable (from its own doInBackground method to its own onPostExecute method)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Get maximum HorizontalScrollView scroll amount I'm adding floating arrows to my HorizontalScrollView which will let the user know that there are more item's outside of the current view. What I need is how to tell if the View has been scrolled to it's maximum. You would have thought the method getMaxScrollAmount() would give you this - it doesn't, in my code it gives me the width of the View. Go figure why. Here's my code - nice and simple: final ImageView leftArrow = (ImageView) toReturn.findViewById(R.id.leftArrow); final ImageView rightArrow = (ImageView) toReturn.findViewById(R.id.rightArrow); final HorizontalScrollView scrollView = (HorizontalScrollView) toReturn.findViewById(R.id.actionBarHoriztonalScroll); final GestureDetector gd = new GestureDetector(new SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if(scrollView.getScrollX() == 0) { leftArrow.setVisibility(View.GONE); } else { leftArrow.setVisibility(View.VISIBLE); } if(scrollView.getScrollX() == scrollView.getMaxScrollAmount() || scrollView.getMaxScrollAmount() == 0) { rightArrow.setVisibility(View.GONE); } else { rightArrow.setVisibility(View.VISIBLE); } Log.v(ClientDetailsFragment.class.getSimpleName(), "max: " + scrollView.getMaxScrollAmount() + "current: " + scrollView.getScrollX()); return super.onScroll(e1, e2, distanceX, distanceY); } }); scrollView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent ev) { gd.onTouchEvent(ev); return false; } }); Output from the above debugging: 10-03 14:36:16.343: VERBOSE/(20508): max: 240 current: 126 10-03 14:36:16.363: VERBOSE/(20508): max: 240 current: 127 10-03 14:36:16.386: VERBOSE/(20508): max: 240 current: 132 10-03 14:36:16.398: VERBOSE/(20508): max: 240 current: 143 10-03 14:36:16.417: VERBOSE/(20508): max: 240 current: 149 10-03 14:36:16.433: VERBOSE/(20508): max: 240 current: 152 10-03 14:36:16.449: VERBOSE/(20508): max: 240 current: 152 10-03 14:36:16.468: VERBOSE/(20508): max: 240 current: 152 (152 is the Max in this case) A: The child of the horizontal scrollview should have the correct width. Try this Log.e("ScrollWidth",Integer.toString(horizontalScrollview.getChildAt(0).getMeasuredWidth()- getWindowManager().getDefaultDisplay().getWidth())); This should be the max scroll amount. Put the following code in your onCreate method ViewTreeObserver vto = scrollView.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(this); Log.e("ScrollWidth",Integer.toString(horizontalScrollview.getChildAt(0) .getMeasuredWidth()-getWindowManager().getDefaultDisplay().getWidth())); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: (New to ViewStates) What is the best way(s) to save a dynamically generated control into the viewstate? I am creating a web application in Asp.net and I'm still fairly new. I'm just starting to wrap my head around the basics of the ViewState. In my application, people are searching through a database and I give them ways to narrow their search. When they have entered a valid search constraint (ex: date past 10/1/11) I dynamically add another set of controls allowing them to add another constraint. I want to save the contents of the previous constraint (a set of Controls) so that I can still have it on the webpage when they enter the next constraint. If it makes any difference, one constraint set consists of a drop-down list of attributes, a few literal control, and one or two text fields depending on what attribute was chosen from the drop down list. How would I go about this? Thanks so much guys. A: The easiest way to track viewstate for dynamic controls is to recreate the controls in OnInit and assign the same ID to the controls every time the page is posted back. If the controls are assigned the same ID each time they're created, when the ViewState is loaded, the controls will be repopulated. protected override void OnInit(EventArgs e) { TextBox txt = new TextBox(); txt.ID = "txt1"; this.Controls.Add(txt); } EDIT To make things easier, try using the DynamicControlsPlaceHolder. Just put the control on the page, and it will persist the controls and their values behind the scenes: http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx A: Check out this link: * *https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx *http://www.codeproject.com/KB/viewstate/retainingstate.aspx ViewState for dynamic controls is still maintained by the ASP.NET framework. Just make sure you add them during init or preinit, because viewstate is loaded for every control between the init and load stages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reading a text file using BufferedReader and Scanner I need to read the first n lines of a text file as lines (each line may or may not contain whitespace). The remainder of the text file contains an unknown number N of tokens that are whitespace-delimited (delimiters are a mixture of space, tab, and newline characters, all to be treated identically as delimiters). I know how to read lines using BufferedReader. I know how to read tokens using Scanner. But how do I combine these two different modes of reading for a single text file, in the above described manner? A: You could use a Scanner for both tasks. See the Scanner.nextLine method. If you really need to use both a BufferedReader and a Scanner you could simply do it like this: byte[] inputBytes = "line 1\nline 2\nline 3\ntok 1 tok 2".getBytes(); Reader r = new InputStreamReader(new ByteArrayInputStream(inputBytes)); BufferedReader br = new BufferedReader(r); Scanner s = new Scanner(br); System.out.println("First line: " + br.readLine()); System.out.println("Second line: " + br.readLine()); System.out.println("Third line: " + br.readLine()); System.out.println("Remaining tokens:"); while (s.hasNext()) System.out.println(s.next()); Output: First line: line 1 // from BufferedReader Second line: line 2 // from BufferedReader Third line: line 3 // from BufferedReader Remaining tokens: tok // from Scanner 1 // from Scanner tok // from Scanner 2 // from Scanner
{ "language": "en", "url": "https://stackoverflow.com/questions/7635917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP test for corrupt (but apparently fine) images I have a simple image upload script that uses SimpleImage.php (http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/) to resize and save 2 copies of an uploaded image. There isn't a massive amount of validation, just checking that it exists and that the file extension is fine, and also an exif_imagetype(); call. This has worked with no problems so far until I tried to upload a seemingly normal jpeg which turned out to be invisibly (and untestably?) corrupt. There was something not right about it, but I know very little about image corruption - it looked fine and opened no problem on anything, but when I tried to save a scaled copy in my script I got a white page. The problem is definitely that specific image, I've tested exhastively with other images both from my local stock and from stock image sites, and only that one image breaks it. I resized a copy using Photoshop (the predicted file size thingy gave me some wierd numbers - 45meg for top quality jpeg) and that uploaded with no issues. So my question is, how do I test for this? The image in question is here: http://chinawin.co.uk/broken.jpg //beware, 700k notes: I've tested with similar resolutions, image sizes and names, everything else worked apart from this image. UPDATE: Through trial and error I've narrowed down where the script breaks to the line where I load the image into a var for SimpleImage. Strangely this is the second line that does so (the first being to create the large copy, this one to create a thumbnail). Commenting it out means the rest works ok... perhaps some refactoring will avoid this problem. 2nd Update: Here's a snippet of code and some context from the line that fails: //check if our image is OK if ($image && $imageThumb) { //check if image is a jpeg if (exif_imagetype($_FILES[$k]['tmp_name']) == IMAGETYPE_JPEG) { list($width, $height, $type, $attr) = getimagesize($_FILES[$k]['tmp_name']); //echo 1; $image = new SimpleImage(); //echo 2; $image->load($_FILES[$k]['tmp_name']); //echo 3; $imageThumb = new SimpleImage(); //echo 4; //this next line topples my script, but only for that one image - why?: $imageThumb->load($_FILES[$k]['tmp_name']); //echo '5<br/><br/>-------<br/>'; //do stuff, save & update db, etc } } Final edit: Turns out my script was running out of memory, and with good reason - 4900x3900 image with 240 ppi turns out to be around 48 meg when loaded into memory, twice - so I was using probably > 90meg of ram, per image. Hats off to @Pekka for spotting this. Refactoring the script to only have the image loaded once, and then this variable used instead of it's sibling, fixed my script. Still having (different) issues with upoading larger (2.5meg) images but this is for another question. A: This is most likely a memory issue: Your JPG is very large (more than 4000 x 4000 pixels) and, uncompressed, will indeed eat up around 48 Megabytes of RAM. Activate error reporting to make sure. If it's the reason, see e.g. here on what to do: Uploading images with PHP and hitting the script memory limit
{ "language": "en", "url": "https://stackoverflow.com/questions/7635919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Persisting interfaces using JDO/Datanucleus I have the following class: @PersistenceCapable(identityType = IdentityType.APPLICATION, detachable = "true") public class TclRequest implements Comparable<TclRequest> { @PrimaryKey private String id; @Persistent(types = { DNSTestData.class, POP3TestData.class, PPPoETestData.class, RADIUSTestData.class }, defaultFetchGroup = "true") @Columns({ @Column(name = "dnstestdata_fk"), @Column(name = "pop3testdata_fk"), @Column(name = "pppoetestdata_fk"), @Column(name = "radiustestdata_fk") }) private TestData testData; public String getId() { return id; } public TestData getTestData() { return testData; } public void setId(String id) { this.id = id; } public void setTestData(TestData testData) { this.testData = testData; } } The TestData interface looks like this: @PersistenceCapable(detachable = "true") public interface TestData { @PrimaryKey public String getId(); public void setId(String id); } Which is implemented by many classed including this one: @PersistenceCapable(detachable = "true") public class RADIUSTestData implements TestData { @PrimaryKey private String id; private String password; private String username; public RADIUSTestData() { } public RADIUSTestData(String password, String username) { super(); this.password = password; this.username = username; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } } When I try to persiste the TclRequest class, after constructing it of course and using the RADIUSTestData: //'o' is the constructed TclRequest object. PersistenceManager pm = null; Transaction t = null; try { pm = getPM(); t = pm.currentTransaction(); t.begin(); pm.makePersistent(o); t.commit(); } catch (Exception e) { e.printStackTrace(); if (t != null && t.isActive()) { t.rollback(); } } finally { closePM(pm); } The interface field isn't persisted. And the column is not created in the table ! I enabled the debug mode and found 2 catchy things: 1) -Class com.skycomm.cth.beans.ixload.radius.TestData specified to use "application identity" but no "objectid-class" was specified. Reverting to javax.jdo.identity.StringIdentity 2) -Performing reachability on PC field "com.skycomm.cth.beans.TclRequest.testData" -Could not find StateManager for PC object "" at field "com.skycomm.cth.beans.TclRequest.testData" - ignoring for reachability What could this mean ? Thanks in advance. A: I have figured out how to do it. It's not very much scalable but it works for now. These are the annotations for the interface member variable. Note that the order of declared types, columns and class names in the extension value is important to be maintaned: @Persistent(types = { RADIUSTestData.class, POP3TestData.class, PPPoETestData.class, DNSTestData.class }, defaultFetchGroup = "true") @Columns({ @Column(name = "radiustestdata_fk"), @Column(name = "pop3testdata_fk"), @Column(name = "pppoetestdata_fk"), @Column(name = "dnstestdata_fk") }) @Extension(vendorName = "datanucleus", key = "implementation-classes", value = "com.skycomm.cth.tcl.beans.radius.RADIUSTestData, com.skycomm.cth.tcl.beans.pop3.POP3TestData, com.skycomm.cth.tcl.beans.pppoe.PPPoETestData, com.skycomm.cth.tcl.beans.dns.DNSTestData") A sample class implementing one of the interfaces (Just it's "header"): @PersistenceCapable(detachable = "true") public class RADIUSTestData implements TestData { So it's pretty normal here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to copy or match only selected elements from an XML input with namespace and then remove the namespace at the same time Given below is my XML input. How do I copy or match selected elements that I want to reflect in my XML output using XSL. The general idea of the logic should be to specify only the elements I am interested instead of specifying the elements that I don't like to be included in the output. The elements that I want to reflect in my output XML are always present in the XML Inpput. The rest of the elements vary depending on what the system has generated and so I cannot just specify what to remove. I was able to this without the namespace from the input by doing the copy-of, but when the namespace is present the code is not working. I found a way to remove the namespace but when combined with the copy-of, didn't work as well. I am quite confused as to how XSL behaves. Please bear with my inquiry, I'm very new to XML and XSL and I was assigned to this task because no one from our team had the experience working with XML. Thank you in advance. XML Input: <Transaction xmlns="http://www.test.com/rdc.xsd"> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> <ItemDesc>Keychain</ItemDesc> </Item> <Item id="2"> <ItemID>A002</ItemID> <ItemDesc>Wallet</ItemDesc> </Item> </Items> <IDONTLIKETHIS_1> <STOREXXX>XXX</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_1> <IDONTLIKETHIS_2> <STOREXXX>XXX</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_2> </Transaction> </Transaction> Desired Output: <Transaction> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> <ItemDesc>Keychain</ItemDesc> </Item> <Item id="2"> <ItemID>A002</ItemID> <ItemDesc>Wallet</ItemDesc> </Item> </Items> </Transaction> </Transaction> I've tried the code below but the problem with it is that I'm missing the second Transaction element and the xmlns attribute is present in the root element: <xsl:template match="*"> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:template> <xsl:template match="node()[not(self::*)]"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="x:Transaction/x:StoreName"/> <xsl:copy-of select="x:Transaction/x:TransNo"/> <xsl:copy-of select="x:Transaction/x:RegisterNo"/> <xsl:copy-of select="x:Transaction/x:Items"/> </xsl:copy> </xsl:template> A: This transformation uses a list of all names of elements that we want to copy after processing: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://invia.fujitsu.com/RetailDATACenter/rdc.xsd"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:param name="pNames" select= "'|Transaction|StoreName|TransNo|RegisterNo|Items|Item|ItemID|ItemDesc'"/> <xsl:template match="*" > <xsl:if test= "contains($pNames, concat('|',local-name(), '|') )"> <xsl:element name="{name()}"> <xsl:copy-of select="@*"/> <xsl:apply-templates select="node()"/> </xsl:element> </xsl:if> </xsl:template> <xsl:template match="node()[not(self::*)]"> <xsl:copy-of select="."/> </xsl:template> </xsl:stylesheet> when applied to the provided XML document: <Transaction xmlns="http://www.test.com/rdc.xsd"> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> <ItemDesc>Keychain</ItemDesc> </Item> <Item id="2"> <ItemID>A002</ItemID> <ItemDesc>Wallet</ItemDesc> </Item> </Items> <IDONTLIKETHIS_1> <STOREXXX>XXX</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_1> <IDONTLIKETHIS_2> <STOREXXX>XXX</STOREXXX> <TRANSXXX>YYY</TRANSXXX> </IDONTLIKETHIS_2> </Transaction> </Transaction> the wanted, correct result is produced: <Transaction> <Transaction> <StoreName id="aa">STORE A</StoreName> <TransNo>TXN0001</TransNo> <RegisterNo>REG001</RegisterNo> <Items> <Item id="1"> <ItemID>A001</ItemID> </Item> <Item id="2"> <ItemID>A002</ItemID> </Item> </Items> </Transaction> </Transaction> Do note: One advantage of this solution over other possible solution is that the string containing the pipe-delimited list of element names can be provide as an externally-specified parameter to the transformation, making it very powerful and flexible and eliminating the need to alter the code any time we include new elements (or exclude some) from our white-list. A: Would this work? <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> <xsl:variable name="allowed"> <names> <name>Transaction</name> <name>StoreName</name> <name>TransNo</name> <name>RegisterNo</name> <name>Items</name> <name>Item</name> <name>ItemID</name> <name>ItemDesc</name> <name>id</name> </names> </xsl:variable> <xsl:template match="text()"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="@*"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="comment()"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="processing-instruction()"> <xsl:copy-of select="."/> </xsl:template> <xsl:template match="*"> <xsl:if test="local-name(.) = $allowed//name"> <xsl:element name="{local-name(.)}"> <xsl:apply-templates select="@*"/> <xsl:apply-templates select="node()"/> </xsl:element> </xsl:if> </xsl:template> </xsl:stylesheet> A: This seems to do what you need, but please read up on namespaces as I'm not sure that what you plan to do is all that sensible. Hope this helps, Ken <xsl:stylesheet version="1.0" xmlns:abc="http://www.test.com/rdc.xsd" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:template match="abc:Transaction|abc:StoreName|abc:TransNo|abc:RegisterNo|abc:Items|abc:Item|abc:ItemID|abc:ItemDesc"> <xsl:element name="{local-name()}"> <xsl:copy-of select="@*"/> <xsl:apply-templates/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:copy/> </xsl:template> <xsl:template match="*"/> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7635922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jqueryUI datepicker and allowing non-dates? How would I use the jqueryUI "datepicker" if I want my input field to allow non-dates (or invalid dates)? I have a server-side script which can handle a normal date as input, or an asterisk to mean "latest date available" (amongst a few other special codes). It would be nice to have a popup datepicker in my HTML form, but only when needed. How can I use the jqueryUI datepicker to choose a specific date (for example, by clicking on a datepicker icon), while also allowing the user to enter one of our special codes as a "fake date"? Thanks! A: You can use the constrainInput option to allow all characters to be entered into the input: $("#someElem").datepicker({ constrainInput: false }); See this working example. The first input will allow any characters to be typed. The second input will only allow the defaults allowed by the datepicker widget (which I think is just numbers and the / character). A: Seems to my recollection that when I've used jQueryUI datepicker the datepicker fills in the value into a text field, but the user can still just close out the picker and type into the text field directly. Give it a try?
{ "language": "en", "url": "https://stackoverflow.com/questions/7635923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to use property injection in unity and asp.net mvc3? I would like to use property injection in an MVC3 application. I have configured Unity 2 as a DI container and everything works just fine by constructor injection but I can't figure out how to use property injection. I marked properties with the [Dependency] attribute but it doesn't work. public class UnityDependencyResolver : IDependencyResolver { IUnityContainer _container; public UnityDependencyResolver(IUnityContainer container) { _container = container; } public object GetService(Type serviceType) { try { return _container.Resolve(serviceType); } catch (Exception) { return null; } } public IEnumerable<object> GetServices(Type serviceType) { try { return _container.ResolveAll(serviceType); } catch (Exception) { return new List<object>(); } } } In Global.asax I have the following: var container = new UnityContainer(); var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); Any help is appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I write an ADL-enabled trailing return type, or noexcept specification? Imagine I'm writing some container template or something. And the time comes to specialize std::swap for it. As a good citizen, I'll enable ADL by doing something like this: template <typename T> void swap(my_template<T>& x, my_template<T>& y) { using std::swap; swap(x.something_that_is_a_T, y.something_that_is_a_T); } This is very neat and all. Until I want to add an exception specification. My swap is noexcept as long as the swap for T is noexcept. So, I'd be writing something like: template <typename T> void swap(my_template<T>& x, my_template<T>& y) noexcept(noexcept(swap(std::declval<T>(), std::declval<T>()))) Problem is, the swap in there needs to be the ADL-discovered swap or std::swap. How do I handle this? A: Rather than declaring but not defining a function template, which seems likely to cause confusion, I would write my own type trait (which is what should probably be in the standard library, anyway). Following the lead of the standard library, I would define something like the following: #include <type_traits> #include <utility> namespace adl { using std::swap; template<typename T, typename U> struct is_nothrow_swappable : std::integral_constant< bool, noexcept(swap(std::declval<T &>(), std::declval<U &>())) > { }; } // namespace adl We have to define our own namespace to import std::swap into (to avoid giving it to everyone), but of course, if it were in the standard library that wouldn't be necessary because they can already make unqualified calls to swap. A: I think I would move it into a separate namespace namespace tricks { using std::swap; template <typename T, typename U> void swap(T &t, U &u) noexcept(noexcept(swap(t, u))); } template <typename T> void swap(my_template<T>& x, my_template<T>& y) noexcept(noexcept(tricks::swap(std::declval<T>(), std::declval<T>()))) { using std::swap; swap(x.something_that_is_a_T, y.something_that_is_a_T); } Alternatively you can move the whole code up into tricks and delegate to there. A: There is a similar problem for return types: // Want to be compatible with both boost::tuple and std::tuple template<typename Tuple> auto first(Tuple&& tuple) -> /* ??? */ { // Introduce name into scope using std::get; // but ADL can still pick boost::get for boost::tuple return get<0>(std::forward<Tuple>(tuple)); } Using decltype( get<0>(std::forward<Tuple>(tuple)) ) isn't correct as get isn't in scope. Possible workarounds are: * *Introducing a dummy template (get in my example, swap in your case) in the enclosing scope; this includes putting the using std::swap declaration in the enclosing namespace, with the drawback of polluting the namespace. *Use of a type trait: typename std::tuple_element<0, typename std::remove_reference<Tuple>::type>::type (actually this one is problematic but for reasons that don't belong here) in my example, and a potential is_nothrow_swappable<T>::value in your case. Specializations then allow the template to be extended for other types if need be. A: C++17 has solved this particular use case with std::is_nothrow_swappable: http://en.cppreference.com/w/cpp/types/is_swappable
{ "language": "en", "url": "https://stackoverflow.com/questions/7635939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "46" }
Q: Objective-C – Message a view controller from application delegate I want to download some data in the application delegate in - application:didFinishLaunchingWithOptions: After I have downloaded some data I want to set this data to an NSArray property in a view controller. If I have a synthesized property of NSArray (nonatomic, retain) called data I would like to do [viewController setData:downloadedData]; How would I call the active viewController instance from the application delegate? My application structure is a Tab Bar Controller as root controller. A: You'll want to use NSNotificationCenter which will essentially broadcast a message to all objects that have subscribed to that particular message. In your view controller subscribe to the notification: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(downloadedData:) notificationName:@"DownloadedData" object:data]; - downloadedData:(NSNotification *)notification { self.data = notification.object; } And in your app delegate send the notification to the subscribers: [[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadedData" object:data]; A: Add delegateComplete property in your app delegate class: //define ivar id delegateComplete; //define property @property (nonatomic, retain) id delegateComplete; //synthesize @synthesize delegateComplete; In init method or viewDidLoad of your viewController do following: MainClass *appDelegate = (MainClass *)[[UIApplication sharedApplication] delegate]; appDelegate.delegateComplete = self; replace MainClass with your app class. After downloading is complete, do following in your app delegate: [delegateComplete loadingCompletedWithData:data]; Dont forget to add this method in your viewController: - (void)loadingCompletedWithData:(NSData *)data What happens is that your view controller registers to your app delegate. When loading completes, if your view controller has registered, call loadingCompletedWithData. Proper way of doing this would be through a protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I use HierarchicalDataTemplate to display XML Elements and Attributes? I'd like to display arbitrary XML in a TreeView, with expanding and collapsing nodes, showing both the element name and the set of attributes and their values. I think I can do this with HierarchicalDataTemplate . I've seen the hints to use HierarchicalDataTemplate to display arbitrary XML elements, and text nodes, like this: <Window.Resources> <HierarchicalDataTemplate x:Key="NodeTemplate"> <TextBlock x:Name="tbName" Text="?" /> <HierarchicalDataTemplate.ItemsSource> <Binding XPath="child::node()" /> </HierarchicalDataTemplate.ItemsSource> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding="{Binding Path=NodeType}" Value="Text"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Value}"/> </DataTrigger> <DataTrigger Binding="{Binding Path=NodeType}" Value="Element"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Name}"/> </DataTrigger> </HierarchicalDataTemplate.Triggers> </HierarchicalDataTemplate> <XmlDataProvider x:Key="xmlDataProvider"> </XmlDataProvider> </Window.Resources> .... <TreeView Name="treeView1" ItemsSource="{Binding Source={StaticResource xmlDataProvider}, XPath=*}" ItemTemplate= "{StaticResource NodeTemplate}"/> Which works great. It displays the element names and text for each element. But my XML uses attributes to carry information. The schema is complex and I don't have a formal definition of it, so for now I am treating it as arbitrary XML. The simplest document looks like this: <c4soap name="GetVersionInfo" seq="" result="1"> <versions> <version name="Director" version="2.1.0.126418" buildtype="" builddate="Jun 1 2011" buildtime="14:52:43" /> <version name="MediaManager" version="2.1.0.126418" buildtype="" builddate="Jun 1 2011" buildtime="14:36:17" /> </versions> </c4soap> Using the above HierarchicalDataTemplate definition, I get this for a display: Not quite what I want. For each node I want to display both the element name and the set of attributes and their values. I tried this: <Window.Resources> <HierarchicalDataTemplate x:Key="NodeTemplate"> <WrapPanel Focusable="False"> <TextBlock x:Name="tbName" Text="?" /> <TextBlock x:Name="tbAttrs" Text="?" /> </WrapPanel> <HierarchicalDataTemplate.ItemsSource> <Binding XPath="child::node()" /> </HierarchicalDataTemplate.ItemsSource> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding="{Binding Path=NodeType}" Value="Text"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Value}"/> </DataTrigger> <DataTrigger Binding="{Binding Path=NodeType}" Value="Element"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Name}"/> <Setter TargetName="tbAttrs" Property="Text" Value="{Binding Path=Attributes}"/> </DataTrigger> </HierarchicalDataTemplate.Triggers> </HierarchicalDataTemplate> <XmlDataProvider x:Key="xmlDataProvider"> </XmlDataProvider> </Window.Resources> ... which gets me kinda close, but the Value="{Binding Path=Attributes}" results in a display of "(Collection)" in the TreeView. How can I simply display all the actual attribute names and values, in addition to the element name? A: I added an ItemsControl into the template, like this : <Window.Resources> <SolidColorBrush x:Key="xmlValueBrush" Color="Blue" /> <SolidColorBrush x:Key="xmAttributeBrush" Color="Red" /> <SolidColorBrush x:Key="xmlTagBrush" Color="DarkMagenta" /> <SolidColorBrush x:Key="xmlMarkBrush" Color="Blue" /> <DataTemplate x:Key="attributeTemplate"> <StackPanel Orientation="Horizontal" Margin="3,0,0,0" HorizontalAlignment="Center"> <TextBlock Text="{Binding Path=Name}" Foreground="{StaticResource xmAttributeBrush}"/> <TextBlock Text="=&quot;" Foreground="{StaticResource xmlMarkBrush}"/> <TextBlock Text="{Binding Path=Value}" Foreground="{StaticResource xmlValueBrush}"/> <TextBlock Text="&quot;" Foreground="{StaticResource xmlMarkBrush}"/> </StackPanel> </DataTemplate> <HierarchicalDataTemplate x:Key="nodeTemplate"> <StackPanel Orientation="Horizontal" Focusable="False"> <TextBlock x:Name="tbName" Text="?" /> <ItemsControl ItemTemplate="{StaticResource attributeTemplate}" ItemsSource="{Binding Path=Attributes}" HorizontalAlignment="Center"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> </StackPanel> <HierarchicalDataTemplate.ItemsSource> <Binding XPath="child::node()" /> </HierarchicalDataTemplate.ItemsSource> <HierarchicalDataTemplate.Triggers> <DataTrigger Binding="{Binding Path=NodeType}" Value="Text"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Value}"/> </DataTrigger> <DataTrigger Binding="{Binding Path=NodeType}" Value="Element"> <Setter TargetName="tbName" Property="Text" Value="{Binding Path=Name}"/> </DataTrigger> </HierarchicalDataTemplate.Triggers> </HierarchicalDataTemplate> <XmlDataProvider x:Key="xmlDataProvider"> </XmlDataProvider> </Window.Resources> Now it displays element names and the set of attributes and their values, like this: A: you also can use a template selector for the different node types and use the XPath node()|@* to loop thru all types of nodes: <TreeView x:Name="TreeView" ItemsSource="{Binding}" ItemTemplateSelector="{DynamicResource ResourceKey=NodeTemplateSelector}"> <TreeView.Resources> <HierarchicalDataTemplate x:Key="TextTemplate"> <Grid> <uixml:TextInputControl DataContext="{Binding}" /> </Grid> </HierarchicalDataTemplate> <HierarchicalDataTemplate x:Key="AttributeTemplate"> <Grid> <uixml:AttributeInputControl DataContext="{Binding}" /> </Grid> </HierarchicalDataTemplate> <HierarchicalDataTemplate x:Key="NodeTemplate" > <TextBlock Text="{Binding Path=Name}" /> <HierarchicalDataTemplate.ItemsSource> <Binding XPath="child::node()|@*" /> </HierarchicalDataTemplate.ItemsSource> </HierarchicalDataTemplate> <ui:XmlTemplateSelector x:Key="NodeTemplateSelector" NodeTemplate="{StaticResource NodeTemplate}" TextTemplate="{StaticResource TextTemplate}" AttributeTemplate="{StaticResource AttributeTemplate}" /> </TreeView.Resources> </TreeView> and : public class XmlTemplateSelector:DataTemplateSelector{ public DataTemplate NodeTemplate { get; set; } public DataTemplate TextTemplate { get; set; } public DataTemplate AttributeTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { XmlNode node = (XmlNode)item; switch (node.NodeType) { case XmlNodeType.Attribute: return AttributeTemplate; case XmlNodeType.Element: return NodeTemplate; case XmlNodeType.Text: return TextTemplate; } throw new NotImplementedException(String.Format("not implemented for type {0}", node.NodeType)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: gcc optimisation effect on structure size Say I have a large struct, which includes other struct, etc. Would gcc -os or any other gcc optimisation switch change the way it's stored in memory? I.e. would it pack the structure so as to squeeze out some extra space? thanks, A: No, in order change the native platform alignment for a structure in gcc you would have to explicitly use the __attribute__((packed)) or __attribute__((align X)) compiler directives, or other gcc command-line switches that specifically direct the compiler to change the native-platform alignment for data-structures. Also, packing a structure with mixed data-types so that all the data-members may not be aligned on a proper word-boundary in memory actually will be slower for accessing a data-member at runtime, not faster. This is because the compiler will have to unpack the structure back to the native alignment for the platform before accessing the data-member. A: No, this should not happen - so long as you have the same alignment and packing options for all your code modules then they should work correctly together even if compiled with different optimisation levels, A: In fact, I can see how aligning structs (by padding them) could lead to shorter code (no cross-boundary word addressing -> fewer load/stores) -Os optimizes for binary size (i.e. most commonly referred to as code size) not memory compression
{ "language": "en", "url": "https://stackoverflow.com/questions/7635951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript - How to remove all extra spacing between words How can I remove all extra space between words in a string literal? "some value" Should become "some value" Also, " This should become something else too . " Becomes "This should become something else too ." Do not worry about moving the .. Just as above is fine. I know I can use $.trim(str) to achieve the trailing/ending space removal. But, I'm not sure how to do the 1 space between words trick. A: var str = " This should become something else too . " $.trim(str).replace(/\s(?=\s)/g,'') This uses lookahead to replace multiple spaces with a single space. A: jsFiddle Example " This should become something else too . ".replace(/[\s\t]+/g,' '); A: var str = " This should become something else too . "; str = str.replace(/ +(?= )/g,''); Here's a working fiddle. A: Another (perhaps easier to understand) regexp replacement that will do the trick: var input = /* whatever */; input = input.replace(/ +/g, ' '); The regexp matches one or more spaces, so the .replace() call replaces every single or repeated space with a single space. A: var string = " This should become something else too . "; string = string.replace(/\s+/g, " "); This code replaces a consecutive set of whitespace characters (\s+) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s by a space if you only want to replace spaces. If you also want to remove the whitespace at the beginning and end, include: string = string.replace(/^\s+|\s+$/g, ""); This line removes all white-space characters at the beginning (^) and end ($). The g at the end of the RegExp means: global, ie match and replace all occurences. A: In case we want to avoid the replace function with regex, We can achieve same result by str.split(' ').filter(s => s).join(' ') // var str = " This should become something else too . "; // result is "This should become something else too ." First, split the original string with space, then we will have empty string and words in an array. Second, filter to remain only words, then join all words with a whitespace. A: var str = 'some value'; str.replace(/\s\s+/g, ' ');
{ "language": "en", "url": "https://stackoverflow.com/questions/7635952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: open picture in new tab, same as if do right click - View Image in firefox (WatiN) I need to open image in new tab exactly as it's being done by clicking right button on it and then selecting View Image in firefox. Copying pic url and using browser.Goto doesn't give me the result i need due to some tricky javascript. Could anyone give me some suggestions? Thanks A: Old question, some answer for reference only. Get the src attribute for the image you are looking for and then open a new instance of IE with that address (you will probably need to append the base website address plus whatever there is in the src attribute for the image you are looking for. Some code for that: Image btnLogin = Window.Image(Find.ByName("TheImageNameOrAnyOtherAttribute")); string imageAddress = btnLogin.GetAttributeValue("src"); var newBrowser = new IE(); newBrowser.GoTo("http://www.somesite.com/"+imageAddress);
{ "language": "en", "url": "https://stackoverflow.com/questions/7635955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I check condition while mapping in SSIS? i want to create one ssis package which takes values from flat file and insert it into database table depending upon there companyname. for example: I have table fields: Date SecurityId SecurityType EntryPrice Price CompanyName 2011-08-31 5033048 Bond 1.05 NULL ABC Corp now i want to insert Price into this table but i need to match with CompanyName and in that also in file CompanyName is like ABC so how can i checked that and insert only particular data... like this i have 20 records in my file with different company names. I DID LIKE THIS in lookup i did and now my problem is i need to check company name from flat file and insert that company price into table but in flat file company name is given like 'AK STL' ans in table it is like 'AK STEEL CORPORATION' so for this i have used column transformation but what expression i write to find match ...same with other company names only 1ft 2-3 charachters are there in flat file please help A: Basically, you are looking to "Upsert" your data into the database. Here is a simple look up upsert example. With as few of records in your dataset as you have said, this method will suffice. With larger datasets, you probably want to look into using temp tables and using sql logic similar to this: --Insert Portion INSERT INTO FinalTable ( Colums ) SELECT T.TempColumns FROM TempTable T WHERE ( SELECT 'Bam' FROM FinalTable F WHERE F.Key(s) = T.Key(s) ) IS NULL --Update Portion UPDATE FinalTable SET NonKeyColumn(s) = T.TempNonKeyColumn(s) FROM TempTable T WHERE FinalTable.Key(s) = T.Key(s) AND CHECKSUM(FinalTable.NonKeyColumn(s)) <> CHECKSUM(T.NonKeyColumn(s))
{ "language": "en", "url": "https://stackoverflow.com/questions/7635958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JEditorPane and source of HTML element I have (still) problems with HTMLEditorKit and HTMLDocument in Java. I can only set the inner HTML of an element, but I cannot get it. Is there some way, how to get a uderlying HTML code of an element? My problem is, that the HTML support is quite poor and bad written. The API does not allow basic and expected functions. I need change the colspan or rowspan attribute of <td>. The Java developers have closed the straightforward way: the attribute set of element is immutable. The workaround could be to take the code of element (e.g. <td colspan="2">Hi <u>world</u></td>) and replace it with new content (e.g. <td colspan="3">Hi <u>world</u></td>). This way seems to be closed too. (Bonus question: What's the HTMLEditorKit good for?) A: You can get the selected Element html. Use write() method of the kit passing there offsets of the Element. But it will be included with surrounding tags "<html>" "<body>" etc. A: Thanks for hint, Stanislav. That's my solution: /** * The method gets inner HTML of given element. If the element is named <code>p-implied</code> * or <code>content</code>, it returns null. * @param e element * @param d document containing given element * @return the inner HTML of a HTML tag or null, if e is not a valid HTML tag * @throws IOException * @throws BadLocationException */ public String getInnerHtmlOfTag(Element e, Document d) throws IOException, BadLocationException { if (e.getName().equals("p-implied") || e.getName().equals("content")) return null; CharArrayWriter caw = new CharArrayWriter(); int i; final String startTag = "<" + e.getName(); final String endTag = "</" + e.getName() + ">"; final int startTagLength = startTag.length(); final int endTagLength = endTag.length(); write(caw, d, e.getStartOffset(), e.getEndOffset() - e.getStartOffset()); //we have the element but wrapped as full standalone HTML code beginning with HTML start tag //thus we need unpack our element StringBuffer str = new StringBuffer(caw.toString()); while (str.length() >= startTagLength) { if (str.charAt(0) != '<') str.deleteCharAt(0); else if (!str.substring(0, startTagLength).equals(startTag)) str.delete(0, startTagLength); else break; } //we've found the beginning of the tag for (i = 0; i < str.length(); i++) { //skip it... if (str.charAt(i) == '>') break; //we've found end position of our start tag } str.delete(0, i + 1); //...and eat it //skip the content for (i = 0; i < str.length(); i++) { if (str.charAt(i) == '<' && i + endTagLength < str.length() && str.substring(i, i + endTagLength).equals(endTag)) break; //we've found the end position of inner HTML of our tag } str.delete(i, str.length()); //now just remove all from i position to the end return str.toString().trim(); } This method can be easilly modified to get outter HTML (so the code containing the entire tag).
{ "language": "en", "url": "https://stackoverflow.com/questions/7635964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delphi menu choice My question is how to catch which menu item was pressed in some form? For an example : I have a form with a button. When I pressed the button the menu of the application will be on focus and the child form wait to choose a menu item. After I choose one the child form show a message with the name of the menu item which I pressed. Can anyone tell me how to do this? Thanks in advance! A: Something like this is a direct answer to your question: procedure TMyForm.MenuItemClick(Sender: TObject); begin ShowMessage((Sender as TMenuItem).Caption); end; This event handler should be connected to each menu item that you wish to behave this way. It seems that you want some centralised logging or monitoring of the execution of menu items. If you use actions and associate these with your menu items then you can get an application wide notification that an action has been executed. Drop a TApplicationEvents object onto your main form and handle its OnActionExecute event. Like this: procedure TMyForm.ApplicationEvents1ActionExecute(Action: TBasicAction; var Handled: Boolean); begin ShowMessage((Action as TAction).Caption); end; This will fire whenever any event in your app is executed. A: * *1/ By default you set all the TMenuItem OnClick event handler to Nil. *2/ When you click the form button you assign an event to each TMenuItem, this event will be only called once, and will record the 'trigger'. *3/ When the event is called you reset all the TMenuitem.OnClick to Nil *4/ To make this easyer, you store all your MenuItems in a TList. example: global variables (private declaration in TMyForm): MyTriggerItem: TMenuItem; // used as pointer MyMenuItemList: TList; // used to store all TMenuItem which are 'listened to' your TButton handler: Procedure TMyForm.ButtonClick(Sender: TObject); Var i: Integer; Begin For i:= 0 To Pred(MyMenuItemList.Count) Do TMenuItem(MyMenuItemList[i]).OnCLick := CommonMenuItemClick; End; your TMenuItem event handler: Procedure TMyForm.CommonMenuItemClick(Sender: TObject); Var i: Integer; Begin MyTriggerItem := TMenuItem(Sender); For i:= 0 To Pred(MyMenuItemList.Count) Do TMenuItem(MyMenuItemList[i]).OnCLick := Nil; End;
{ "language": "en", "url": "https://stackoverflow.com/questions/7635965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List to Dictionary conversion using Linq Can somebody suggest me what Linq operator should I use to write an elegant code to convert List to Dictionary of list? Eg. I have a list of person (List<Person>) and I wanted to convert that to dictionary of list (like Dictionary<string, List<Person>> using the person's last name as a key. I needed that for quickly lookup the list of persons by the last name A: To get a Dictionary<string, List<Person>> from List<Person>: var dictionary = list .GroupBy(p => p.LastName) .ToDictionary(g => g.Key, g => g.ToList()); A: This isn't what you asked for, but you can use Philip response for that :-) var lookup = myList.ToLookup(p => p.Surname); This will create an ILookup<string, Person> that is something very similar to what you wanted (you won't have a Dictionary<string, List<Person>> but something more similar to a Dictionary<string, IEnumerable<Person>> and and the ILookup is readonly) A: you can also use as follows. foreach(var item in MyList) { if(!myDictionary.Keys.Contains(item)) myDictionary.Add(item,item.value); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7635969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rails 3, Facebook, Koala: NoMethodError: undefined method `closed?' for nil:NilClass seems I get this error from Koala when I'm trying to connect with the graph api: NoMethodError: undefined method `closed?' for nil:NilClass It is exactly the same problem I had before with Omniauth which can be read here: https://github.com/intridea/omniauth/issues/260 http://stackoverflow.com/questions/3977303/omniauth-facebook-certificate-verify-failed basically is that Faraday is not setting the ca_path variable for OpenSSL. One solution is: OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE in Omniauth the solution was putting an option like this: provider :facebook, FACEBOOK_KEY, FACEBOOK_SECRET, {:client_options => {:ssl => {:ca_path => "/etc/ssl/certs"}}} I was wondering if anybody else has have the problem and how was it solved. I wouldn't like to use the first option and the second one is not possible afaik in koala. I'm using Koala 1.2.0 and Faraday 0.7.4 thanks! A: Seems it is possible to set default options for ssl in Koala. github.com/arsduo/koala/wiki/HTTP-Services I just missed it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7635973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the proper way to store an array into a database table? I have an array of 50+ elements that dictates how many hours were worked for a given week. What is the proper way to store this information into a database table? My initial idea was to use a delimiter, but the text is too large (280 characters) to fit. Additionally, there seems something "wrong" with creating a table column for each element. Ideas? Array using delimiter (comma): 37.5,37.5,37.5,37.5,37.5,37.5,37.5,37.5,37.5,37.5, ... A: The "proper" way is to store the array's contents as multiple rows in a whole other table, each with a foreign key referencing the record they belong to back in the first table. There may be other things that work for you, though. [EDIT]: From the details you added I'm guessing your array elements consist of a number of hours worked each week and you have 50+ of them because a year has 52-ish weeks. So what I think you're looking for, is I guess that your current (main) table is called something like "employees," is that each row there should have some unique identifier for each employee record. So your new table might be called "work_weeks" and consist of something like employee_id (which matches the employee id in the current table), week_number, and hours_worked. A: Seems like a 1 to many relationship. For this example, tableA is the 1 and tableBlammo is the many. tableA => column blammoId tableBlammo => column blammoId, column data One row in tableA joins to multiple rows in tableBlammo via the blammoId column. Each row in tableBlammo has one element of the array in the data column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: character module blues: bad memory address on close and read I'm making a simple fifo style character module. I'm struggling to get it to behave. Here's what's happening: I'm getting close failed in file object destructor: IOError: [Errno 14] Bad address When i try to close a file object that I'm using to talk to my character device. I also get a bad address when I try to read from it. I'm pretty new to kernel programming so I'm not too sure what these symptoms imply. Here is some relevant code. Any assistance would be greatly appreciated: int pop(char *source, char* dest, int count) { // take count values from source, store in dest memcpy(dest,source,count); memset(source,0x00,count); return 0; } ssize_t ent_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) { int retval; char *temp; int copy_count; printk(KERN_ALERT "entropy_feed: module reading...\n"); if (level>=count) { copy_count=count; } else { copy_count=level; } printk(KERN_ALERT "entropy_feed: allocating temp memory buffer"); temp = kcalloc(copy_count,1,GFP_KERNEL); if (down_interruptible(&sem)) { retval= -ERESTARTSYS; goto u_out; } printk(KERN_ALERT "entropy_feed: semaphore locked"); printk(KERN_ALERT "entropy_feed: popping"); pop(buffer+level-copy_count, temp, copy_count); printk(KERN_ALERT "entropy_feed: popped"); level-=copy_count; if (copy_to_user(buf,temp,copy_count)) { retval= -EFAULT; goto out; } out: up(&sem); printk(KERN_ALERT "entropy_feed: semaphore unlocked"); u_out: kfree(temp); printk(KERN_ALERT "entropy_feed: exiting read function") return retval; } ssize_t ent_write(struct file *filp, const char __user *buf, size_t count,loff_t *f_pos) { int retval; char *temp; int copy_count; printk(KERN_ALERT "entropy_feed module writing...\n"); copy_count=level-max_lvl; if (count<copy_count) copy_count=count; if (down_interruptible(&sem)) { retval= -ERESTARTSYS; goto u_out; } printk(KERN_ALERT "entropy_feed: semaphore locked"); temp = kcalloc(count,1,GFP_KERNEL); if (copy_from_user(temp,buf,count)) { retval= -EFAULT; goto out; } printk(KERN_ALERT "entropy_feed: popping"); pop(temp, buffer+level, copy_count); printk(KERN_ALERT "entropy_feed: popped"); level+=copy_count; out: up(&sem); printk(KERN_ALERT "entropy_feed: semaphore unlocked"); u_out: kfree(temp); printk(KERN_ALERT "entropy_feed: exiting write function"); return retval; } struct file_operations ent_fops = { .owner = THIS_MODULE, .read = ent_read, .write = ent_write, }; A: Error number 14 is EFAULT. Looking at your ent_read() function, I don't see anywhere that you set retval to the number of bytes written if the function succeeds, so you are just returning whatever uninitialized value is in retval in the non-failure case. Try adding retval = copy_count; right before the out: line, so that you get the correct return value in the successful read case. As far as the error from close, does your actual file_operations structure have a flush method? If so what are you returning from that? Otherwise I can't see why close() would return EFAULT for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to pass session parameter from jquery to ASHX handler Below is my Jquery code and I would like to pass Session paramater e.g. Session["ID"]. Jquery calls ASHX page All below parameters are working fine and the session parameter has a value, but how can I pass session paramater from Jquery? So below code "paramater Sessionparameter" should be replaced with Session["ID"] or something like that. How can I do that? please advice? $('input[name$=btnTab1Save]').click( function (e) { // debugger; // AJAX call to the handler $.post( 'Consulting.ashx', // data to the handler in the form of QueryString { tab: 'tab1', // id is the second column within the row Ilac_id: prevRow.find('td:eq(0)').text(), ID: SESSION_PARAMATER, begindate: $('input[name$=begindate]').val(), weigth: $('input[name$=weigth]').val(), continue: true, freq: $('input[name$=freq]').val(), reason: $('input[name*=radListreason]:checked').val(), freq2: $('input[name$=radListfreq2]:checked').val(), freetext: $('input[name$=freetext]').val() }, // callback function // data is the JSON object function (data) { if (data.Success) { // close the tab } }, "json" ); }); I can read my parameters like Convert.Toint(context.Request.Form["ID"])); data.weigth = Convert.ToInt32(context.Request.Form["weigth"]); I tried : '<%= Session["ID"] .ToString() %>', but it's not working.... A: If the information is in the session, the ASHX can access directly the session content. You need to implement IReadOnlySessionState and you will be fine. <% @ webhandler language="C#" class="MyClass" %> using System; using System.Web; using System.Web.SessionState; public class MyClass: IHttpHandler, IReadOnlySessionState { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext ctx) { ctx.Response.Write(ctx.Session["ID"]); } } A: The way to do it, if it is not sensitive data, would be to write the value of Session["ID"] to a javascript variable and then use the variable to post the data to the ASHX handler. Something like this: var sessionVariable = '<%=HttpContext.Current.Session["ID"].ToString()%>'; And then: ID: sessionVariable, // etc ... A: Is it a requirement to pass the session variable to the ASHX, or would it be preferable for the ASHX to be able to access session variables? The latter is more secure and less work. You just need to add an inheritance to the IReadOnlySessionState interface if all it will do is read it. There are other interfaces you can inherit from if you wish to actually change it, but this should get you on the right track. Here is a link. Edit: Corrected the link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7635982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript Regex (x,y) Match multiple I am newbie to Javascript. What regex will be used to match the following expression type. Please note that there could be spaces between digits. (3,2), ( 2,3),(5, 4) I am trying as (\d+,\d) but this is not working for multiple pairs of (x,y). A: See the RE below: \s* means: "any whitespace". The parentheses have a special meaning, and have to be escaped. The first RE just matches all pairs of numbers, while the second RE also group the numbers, so that they can be referred when using the RegExp.exec function. /\(\s*\d+\s*,\s*\d+\s*\)/g /\(\s*(\d+)\s*,\s*(\d+)\s*\)/g Example, get all (x,y) pairs within a string, and store the pair in an array: var source = "(1,2), (3,4) (5,6) (7,8)"; //Comma between pairs is optional var RE = /\(\s*(\d+)\s*,\s*(\d+)\s*\)/g, pair; var pairList = []; while((pair = RE.exec(source)) !== null){ pairList.push([pair[1], pair[2]]); } //pairList is an array which consists all x,y pairs A: this should match (x,y),(v,w) like patterns. 0 to n (x,y), expresions plus 1 (x,y) expresion (including whitespaces) /(\(\s*\d+\s*,\s*\d+\s*\),\s*)*\(\s*\d+\s*,\s*\d+\s*\)/ A: Try this code: patt = RegExp('\(\s*\d*\s*,\s*\d*\s*\),{0,1}', 'g') patt.test("(3,2), ( 2,3),(5, 4)") => true A: You can try this /(\(\d+\s*,\s*\d+\)*)/g.exec('(2,3), (3,4)') or using the string at the start '(2,3), (3,4)'.match(/(\(\d+\s*,\s*\d+\)*)/g)
{ "language": "en", "url": "https://stackoverflow.com/questions/7635988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting data off the Clipboard inside a BackgroundWorker I have a background worker and in the DoWork method I have the following: var clipboardData = Application.Current.Dispatcher.Invoke(new Action(() => { Clipboard.GetData(DataFormats.Serializable); })); Why does this always return null even though I know there is data on the clipboard in the correct format? A: Try putting the call into an STA thread: object data = null; Thread t = new Thread(() => { data = Clipboard.GetData(DataFormats.Serializable); }); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); // 'data' should be set here. Within a method with an "OnFinished" action: void GetClipboardData(Action<Object> OnFinished) { Thread t = new Thread(() => { object data = Clipboard.GetData(DataFormats.Serializable); OnFinished(data); }); t.SetApartmentState(ApartmentState.STA); t.Start(); } You'd use it like this: GetClipboardData((data) => { // 'data' is set to the clipboard data here. }); If you want to show and hide a window, try this: myWindow.Show(); GetClipboardData((data) => { // Do something with 'data'. myWindow.Close(); }); With ShowDialog(): Thread d = new Thread(() => { myWindow.ShowDialog(); }); d.SetApartmentState(ApartmentState.STA); d.Start(); GetClipboardData((data) => { // 'data' is set to the clipboard data here. myWindow.Close(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7635994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Vaadin LoginForm layout - HTML I'm facing problem trying to set horizontal layout to LoginForm of Vaadin. The only solution for which I have an idea is overriding getLoginHTML() class so that it return the proper code. I've added style="float:left" which worked for me in normal html. The changed part of code looks like this: (...) + "<div class='v-app v-app-loginpage' style=\"background:transparent;\">" + "<iframe name='logintarget' style='width:0;height:0;" + "border:0;margin:0;padding:0'></iframe>" + "<form id='loginf' target='logintarget' onkeypress=\"submitOnEnter(event)\" method=\"post\">" + "<div style=\"float: left;\">" + getUsernameCaption() + "</div><div style=\"float: left;\">" + "<input class='v-textfield' style=\"float: left;\" type='text' name='username'></div>" + "<div style=\"float: left;\">" + getPasswordCaption() + "</div>" + "<div style=\"float: left;\"><input class='v-textfield' style='display:inline; float:left;' type='password' name='password'></div>" + (...) And that behaves in a weird way - UserField and PasswordLabel are in the same line - all others are in a separate lines. So it looks like that: UsernameLabel UserField PasswordLabel PasswordField Button And as I said I would like it to be algined horizontally... any ideas? A: The are any reason, why you should use LoginForm. Because if answer is no, you can use Vaadin simple Form, it allow you make your form layout more flexible. For example public class FormBean{ private String username, password; //getters and setters } HorizontalLayout newLayout = new HorizontalLayout(); Form form = new Form(newLayout){ @Override protected void attachField(Object propertyId, Field field) { String fieldName = (String) propertyId; if(fieldName.equals("username")){ Label usernameLabel = new Label("username: "); newLayout.addComponent(usernameLabel); newLayout.addComponent(field); } } }; form.setItemDataSource(new FormBean()); form.setFormFieldFactory(new FormFieldFactory() { @Override public Field createField(Item item, Object propertyId, Component uiContext) { String fieldName = (String) propertyId; if(fieldName.equals("username")){ TextField field = new TextField(); field.setImmediate(true); //Here your can add some validations on "fly", for example is username allow only latin characters field.addListener(new TextChangeListener() { @Override public void textChange(TextChangeEvent event) { String currentText = event.getText(); //Here go validation } }); } return null; } }); Inside formFieldFactory you can set if field required, set some validator and etc. If you want to set some sort of validation I recommended use Vaadin add-on BeanValidationForm, it allow using annotations inside POJO object with used to form creation set some rules, for example @NotNull, @Max, @Min and etc. @NotNull(message = "Username required") private String username = ""; @NotNull(message = "Password required") private String userpass = "";
{ "language": "en", "url": "https://stackoverflow.com/questions/7635997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL statement - dynamically merging columns from different tables into a single result set I am not sure this is possible with SQL (say we are executing on DB2) - infact I would say it is not, but thought I would ask some folk who are more experienced in SQL than I am to comment. I have described the problem and what I would like to happen below. Please let me know if you see a way to do this, if not I guess I am down the path of retrieving the data in batches or something like that. Thanks a lot. MAIN TABLE | REF_TABLE | RECORD_NO | GROUPID | | TABLE1 | 1 | BLUE | | TABLE1 | 2 | BLUE | | TABLE2 | 3 | GREEN | | TABLE3 | 4 | BLUE | | TABLE2 | 5 | GREEN | | TABLE4 | 6 | BLUE | TABLE1 | RECORD_NO | NAME | VALUE | | 1 | NAMEX | RANDOM1 | | 2 | NAMEY | RANDOM2 | TABLE2 | RECORD_NO | NAME | VALUE | | 3 | NAMEB | RANDOM10 | | 5 | NAMEC | RANDOM9 | TABLE3 | RECORD_NO | NAME | VALUE | | 4 | NAMET | RANDOM77 | TABLE4 | RECORD_NO | NAME | VALUE | | 6 | NAMET | RANDOM77 | | 7 | NAMEZ | RANDOM99 | So I have some criteria for querying MAIN TABLE e.g. SELECT REF_TABLE, RECORD_NUMBER WHERE GROUPID = 'BLUE' But I also want to include the appropiate values from the other tables which are referenced via REF_TABLE. So the result would be: | REF_TABLE | RECORD_NUMBER | NAME | VALUE | | TABLE1 | 1 | NAMEX | RANDOM1 | | TABLE1 | 2 | NAMEY | RANDOM2 | | TABLE3 | 4 | NAMET | RANDOM77 | | TABLE4 | 6 | NAMET | RANDOM77 | In this case TABLE1, TABLE3 and TABLE4 have their name and value columns merged into a single result set. The table is of course retrieved from the ref_table column of main table. The list of ref tables in finite, so I could hardcode the table names in SQL statements in the query (to avoid dynamically setting the table name) e.g. IF TABLE1 SELECT FROM SCHEMA.TABLE1 (maybe CASE). Restructuring the tables is not an option and the number of returned results may be 10000s. Preferable I would want this all as a single query. Thanks. A: using case is certainly a possibility and should work. Another option is to create view REF_TABLE as select 'TABLE1' as TABLE_NAME, RECORD_NO, NAME, VALUE from TABLE1 UNION select 'TABLE2' as TABLE_NAME, RECORD_NO, NAME, VALUE from TABLE2 ... And then, select RECORD_NO, GROUPID, NAME, VALUE from MAIN_TABLE join REF_TABLE on MAIN_TABLE.REF_TABLE = REF_TABLE.TABLE_NAME and MAIN_TABLE.RECORD_NO = REF_TABLE.RECORD_NO etc EDIT: Not sure why you want to avoid the view. Given your schema it might be useful elsewhere too, and give you significant performance benefit if you can materialize your views (look it up if you don't know what they are) The query using case would be something as follows. I am not very clear on sql server case syntax so you will have work on that. select m.RECORD_NO, m.GROUP_ID, case when REF_TABLE = 'TABLE1' then t1.NAME, t1.VALUE else when REF_TABLE = 'TABLE2' then t2.NAME, t2.VALUE ... end case, from MAIN_TABLE M left outer join TABLE1 T1 on M.RECORD_NO = T1.RECORD_NO left outer join TABLE2 T2 on M.RECORD_NO = T2.RECORD_NO .... A: One can also take the UNIONs from Hemal Panya's answer out of the view and into your query... SELECT record_no, groupid, name, value FROM main_table INNER JOIN ref_table1 on main_table.record_no = ref_table1.record_no WHERE main_table.ref_table = 'TABLE1' UNION ALL SELECT record_no, groupid, name, value FROM main_table INNER JOIN ref_table2 on main_table.record_no = ref_table2.record_no WHERE main_table.ref_table = 'TABLE2' UNION ALL etc, etc... This is probably much faster than tryign to use CASE... SELECT main_table.record_no, main_table.groupid, CASE main_table.ref_table WHEN 'Table1' THEN Table1.name WHEN 'Table2' THEN Table2.name etc, etc END, CASE main_table.ref_table WHEN 'Table1' THEN Table1.value WHEN 'Table2' THEN Table2.value etc, etc END FROM main_table LEFT JOIN Table1 ON main_table.record_no = Table1.record_no AND main_table.ref_table = 'Table1' LEFT JOIN Table2 ON main_table.record_no = Table2.record_no AND main_table.ref_table = 'Table2' etc, etc I would, however, recommend against any of these options. It feels as though your schema is designed against the natural behaviour of SQL. You may either need a new structure, or be better suited to a different environment. Without knowing more details, however, it's impossible to advise on a natural relational structure that would meet your needs without needing this kind of 'conditional join'. On that basis, I'd be intrigued to know why it is that you are hesitent to use a view to unify your disperate data. It appears, in a vacuum, to be th emost sensible option...
{ "language": "en", "url": "https://stackoverflow.com/questions/7635998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I delete several items from an object, which is copy of another object, without affecting the one of which is derived? help me please to use the function "RemoveAll" or maybe there should be another implementation. I have an object (services) which contains a list with items. I make another object (anotherService ) which is equal with the first. I should remove from second object (anotherService) items which have mainService == false. I use the "RemoveAll" function, but after this action is made, from the object (services) items which are mainService = false are also removed. I need to have the first object completed how it was before removing. var services = DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now); var anotherService = services; anotherService.RemoveAll(p => { if (p.Model.mainService == false) { return true; } return false; }); Thank you all. A: The line: var anotherService = services; simply defines a new variable and assigns the existing value (almost certainly a class reference) to that variable; no new object is created. Any member-access on a reference is going to go to the same actual object, no matter which variable you use (there is only one object). To do what you need, you would need to create a shallow or deep clone (depending on what exactly you want to happen). A shallow clone is pretty easy to do by manually adding a Clone() method or similar (maybe ICloneable) which copies the properties (noting that in the case of lists, a new list with the same data is usually created). A deep clone is trickier - a common cheat there is to serialize and deserialize the item. A: The Serialization approach can be found here in this answer : For reference I have posted it here. public static T DeepClone<T>(T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } } A: Your problem is that you are changing the same object, just through a different reference. you need to make sure that you removes items from a different object, which contains copies of the same information. There are a few ways you could do this. The simplest is to just create 2 objects: var services = DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now); var anotherService = DictionaryObject.GetDictionaryValidatedByDate<ServiceInfo>(DictionaryType.REF_SERVICE, DateTime.Now);; anotherService.RemoveAll(p => { if (p.Model.mainService == false || p.Model.mainService == true) { return true; } return false; }); or you could copy/clone your object something like: var anotherService = services.Copy(); //or maybe use a copy constructor here instead: // var anotherService = new ServiceInfo(sevices); anotherService.RemoveAll(p => { if (p.Model.mainService == false || p.Model.mainService == true) { return true; } return false; }); When you implement the Copy() method or the constructor which takes the object to copy you need to make sure that you create copies of dictionaries and do not just use references to the same dictionary. if your object being returned is just an IDictionary<K,V> (its not clear from the code provided) you may be able to do this: var anotherService = new Dictionary<KeyType,ValueType>(services) anotherService.RemoveAll(p => { if (p.Model.mainService == false || p.Model.mainService == true) { return true; } return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7636000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python split string in moving window I have a string with digits like so - digit = "7316717" Now I want to split the string in such a way that the output is a moving window of 3 digits at a time. So I get - ["731", "316", "167", "671", "717"] How would the approach be? Straightforward way is to put in for-loop and iterate. But I feel some inbuilt python string function can do this in less code. Know of any such approach? A: There is a very good recipe pairwise in itertools docs. Modernizing it a bit for n elements in the group, I made this code: from itertools import tee, izip def window(iterable, n): els = tee(iterable, n) for i, el in enumerate(els): for _ in xrange(i): next(el, None) return izip(*els) print(["".join(i) for i in window("2316515618", 3)]) Python 2.7 A: The itertools examples provides the window function that does just that: from itertools import islice def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result Example usage: >>> ["".join(x) for x in window("7316717", 3)] ['731', '316', '167', '671', '717'] A: >>> s = "7316717" >>> [s[i:i+3] for i in range(len(s)-2)] ['731', '316', '167', '671', '717'] A: digit = "7316717" digit_sets = [digit[i:i+3] for i in range(len(digit)-2)] A: Following Shawn's, the newest example of sliding window uses collections.deque: def sliding_window(iterable, n): # sliding_window('ABCDEFG', 4) -> ABCD BCDE CDEF DEFG it = iter(iterable) window = collections.deque(islice(it, n), maxlen=n) if len(window) == n: yield tuple(window) for x in it: window.append(x) yield tuple(window)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Array diff with multilevel array I have this this multilevel array : $productpacks . Example $productpacks[0][0] is 4355 . Now, I have another array that is simple : $codescart[] . Example $codescart[0] is 4355 . I am trying to differ those two like this (it does not seem to work) : foreach($productpacks as $pack) { $diff = array_diff($pack, $codescart); if (empty($diff)) { // $cart contains this pack } } Does that work for anybody ? or were is the problem if any ... A: Why not just use in_array()? foreach($productpacks as $pack) { if (in_array($pack, $codescart)) { // $cart contains this pack } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Richfaces 4 rich:inputNumberSpinner: not getting "set" in backing bean I have done JSF work before, but am new to RichFaces. To test my set up and environment, etc. I have tried to make just a simple little app where the user enters two numbers, clicks a button, and the app returns the sum and product of the numbers. Here's the code summary: web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>eSPAR</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> <context-param> <param-name>javax.faces.DEFAULT_SUFFIX</param-name> <param-value>.xhtml</param-value> </context-param> <!-- Plugging the skin into the project --> <context-param> <param-name>org.richfaces.SKIN</param-name> <param-value>deepMarine</param-value> </context-param> <!-- Making the RichFaces skin spread to standard HTML controls --> <context-param> <param-name>org.richfaces.CONTROL_SKINNING</param-name> <param-value>enable</param-value> </context-param> </web-app> Next: faces-config.xml <?xml version="1.0" encoding="UTF-8"?> <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> <application></application> </faces-config> In other words, basically empty except for the version declarations. Next comes the view page: addmult.xhtml <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <f:view xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:head> </h:head> <h:body> <rich:panel header="Sample Add and Multiply App"> <h:form id="addmultForm"> <p>Enter one number here: <rich:inputNumberSpinner id="num1" minValue="0" value="# {calcBean.number1}" /></p> <p>Enter another number here: <rich:inputNumberSpinner id="num2" minValue="0" value="#{calcBean.number2}" /></p> <a4j:commandButton value="Go" action="#{calcBean.go}" immediate="true"> <f:ajax event="click" render="results" /> </a4j:commandButton> <br /><br /> <h:panelGroup id="results"> <h:panelGroup rendered="#{calcBean.calcDone}"> <p>The sum of your two numbers is: #{calcBean.sum}</p> <p>The product of your two numbers is: #{calcBean.product}</p> </h:panelGroup> </h:panelGroup> </h:form> </rich:panel> </h:body> </f:view> Now finally the bean: CalcBean.java import javax.faces.bean.ManagedBean; @ManagedBean public class CalcBean { private Integer number1 = 3; private Integer number2 = 7; private int sum; private int product; private boolean calcDone = false; public Integer getNumber1() { System.out.println("I am number1: " + number1); return number1; } public void setNumber1(Integer number1) { System.out.println("Change in number1"); this.number1 = number1; } public Integer getNumber2() { return number2; } public void setNumber2(Integer number2) { this.number2 = number2; } public int getSum() { return sum; } public int getProduct() { return product; } public boolean isCalcDone() { System.out.println("Returning calcDone: " + calcDone); return calcDone; } public String go() { System.out.println("Going!"); sum = number1 + number2; product = number1 * number2; calcDone = true; return null; } } My WEB_INF lib contains: commons-beanutils-1.8.3, commons-collections-3.2.1, commons-digester-2.1, commons-logging-1.1.1, cssparser-0.9.5, guava-r08, jhighlight-1.0, jsf-api (mojarra 2.0 version), jsf-facelets-1.1.15, jsf-impl (again mojarra 2.0), richfaces-components-api-4.0.0-FINAL, richfaces-components-ui-4.0.0-FINAL, richfaces-core-api-4.0.0-FINAL, richfaces-core-impl-4.0.0-FINAL, sac-1.3, standard. Whatever values I initiate the Integers number1 and number2, those are the values initially in the inputs when the page loads. The lower text is initially hidden. When the "Go" button is clicked, the lower panel appears, but no matter what values the user has entered, the sum is always 10 and the product always 21 (as shown). The sysout in the setter never displays. The one in the getter displays once when the page loads. When "Go" is clicked, the sysout "Going!" shows once, then "Returning calcDone: true" shows six times. What I have tried: Changing the scope of the bean. Wrapping the expressions in the results panel in <h:outputText>. Adding the FaceletViewHandler in web.xml (actually causes more problems). Removing the facelet jar file from the lib. Do I need a value change listener on the inputs? What else should I try? A: <a4j:commandButton value="Go" action="#{calcBean.go}" immediate="true"> <f:ajax event="click" render="results" /> </a4j:commandButton> Remove immediate="true". It will cause the inputs which do not have immediate="true" to be completely skipped in processing. Also remove <f:ajax> as <a4j:commandButton> already uses ajax. To get a better understanding what immediate does and what you need it for, I suggest you to get yourself through this article : Debug JSF lifecycle (yes, it's JSF 1.2 targeted, but general concept applies on JSF 2.x as well) Here's a summary of relevance: Okay, when should I use the immediate attribute? If it isn't entirely clear yet, here's a summary, complete with real world use examples when they may be beneficial: * *If set in UIInput(s) only, the process validations phase will be taken place in apply request values phase instead. Use this to prioritize validation for the UIInput component(s) in question. When validation/conversion fails for any of them, the non-immediate components won't be validated/converted. *If set in UICommand only, the apply request values phase until with update model values phases will be skipped for any of the UIInput component(s). Use this to skip the entire processing of the form. E.g. "Cancel" or "Back" button. *If set in both UIInput and UICommand components, the apply request values phase until with update model values phases will be skipped for any of the UIInput component(s) which does not have this attribute set. Use this to skip the processing of the entire form expect for certain fields (with immediate). E.g. "Password forgotten" button in a login form with a required but non-immediate password field. So, you ultimately want this: <a4j:commandButton value="Go" action="#{calcBean.go}" render="results" /> Unrelated to the concrete problem: there are more pretty serious problems in your configuration. I have the impression that you're reading JSF 1.x and RichFaces 3.x targeted tutorials/documentation instead of JSX 2.x and RichFaces 4.x targeted ones. The first <context-param> is mandatory for JSF 1.x Facelets only and the remnant is all specific to RichFaces 3.x. Remove them all. You also have an offending JSF 1.x jsf-facelets.jar file which should be removed as well as JSF 2.x already bundles a JSF 2.x Facelets implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Start application from browser Possible Duplicate: how do I create my own URL protocol? (e.g. so://…) I was wondering if it is possible to start an application using a browser url. Just like origin(origin://), itunes(itms://), Trackmania(tmtp://) ... I supose a registere setting needs to be changed for this. But where can I find this, and how do I get the parameters using a C# program. Thank you, Jerodev edit: I have been able to add an own protocol handler using the registery. The handler works with all browsers except for google chrome. Does anyone know how to enable this? A: To start application from web browser is not easy, because most desktop applications require full trust and also full access to your system, and by default web browser doesn't permit you to do so. The best way to really run your app from web browser is by using Silverlight Out of browser or using Adobe's AIR. But if you are just wanting to deploy your app from web browser, you can use Microsoft ClickOnce. It's quite easy and straightforward, and .NET 3.5's ClickOnce supports Firefox and Chrome, not just IE. To use ClickOnce, see this on MSDN Library: http://msdn.microsoft.com/en-us/library/t71a733d(v=VS.90).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7636009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ant builds running through maven issue So I'm building a project with maven, and in this maven pom we have a reference to an ant build script. The maven pom triggers this ant build to build a project (an install of alfresco with mysql database and tomcat server packed up with it). The issue seems to be when you try to set up a database for alfresco to use through the ant build. This is the part of the ant build. <target name="createDatabase"> <exec spawn="false" executable="${mysql.home}/bin/mysql" failonerror="true"> <arg value="-u" /> <arg value="root" /> <arg value="-e" /> <arg value="source ${alfresco.home}\mysql\db_setup.sql" /> </exec> </target> I'm getting 'unknown command '\U' sent back to me as an error on this. Of course you can install the DB manually but I want it as part of this ant script. SOmeone I work with runs this successfully on XP, but I'm getting that error on win7. Any ideas?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I create getter and setter for vector in C++? I declared vector<test*> test1; as a private, and I'd like to create getter and setter for this. I tried, void setV(vector<test*> test1) { test1 = test1; } vector<test*> getV() { return test1; } It works, but it works very strange. Is there another way to do it? Thanks A: Look at the assignment statement in setV: test1 = test1; The private variable test1 is shadowed by the function parameter of the same name, and you're assigning that parameter to itself. You should define setV like this: void setV(vector<test*> const &newTest1) { test1 = newTest1; } That way you're really assigning the parameter to the private variable, and using a const reference for the parameter avoids an unnecessary temporary copy. Also, you should define getV as const, and returning a const reference: vector<test*> const &getV() const { return test1; } That way it can be called on a const instance of your class, and it avoids making an unnecessary copy for the return value. (You can also define another getV, without the consts, if you want the caller to be able to modify the vector of a non-const instance of your class.) A: In coupling with the earlier response, you'll also want to turn your getter into a pass-by-reference (as a pass-by-copy can be slower): const vector<test *> &getV(){return test1;} //This will provide a read-only reference to your vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure a Git Work-flow like this? "Only one user can push to the central server(bare repo)" I will work with one designer that does not know anything of Git. I need to setup an Work-flow where I need to give permission to the code that the designer uploads to the central server. I'm a newbie in Git. How can I setup a Work-flow like this(Designer must to submit the code for approval)? It is also possible to receive notifications of pending code for approval? Best Regards, A: Make a second repository, where the designer can commit his changes at will. You can then pull the changes, merge it into your workspace and review it. When everything is fine, push it to your "main" repository. Or maybe you can create a commit hook, so the designer can only commit to a single branch (designers-name/develop or such). Now its the same as above: Fetch the changes, review, merge into the branch you want to keep control over and push back. Maybe you don't need a hook here, because everybody should be able to follow a rule like "never push into the branches X and Y yourself" ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Application failed codesign verification When I upload my app to the App store I am facing the issue below: Application failed codesign verification. The signature was invalid, or it was not signed with an Apple submission certificate I did all of the changes below: * *cleaning project, *cleaning all, *deleting build directory, *deleting certificates + profiles *and reinstall distribution provisional profile and distribuction certificate but still I am facing the same problem. What am I missing? A: First, check that your certificate is correct/valid. To do this, log in to the iOS Provisioning Portal with your Apple developer account and create a new distribution certificate. Make sure that you specify that you want to store you app on the iOS App Store. Create a certificate for the App Store by clicking the App Store radio button - don't choose "Ad Hoc". After that, download and install the newly created provisioning certificate. Check that you've done the following: * *Set your code-signing identity in the XCode project to use the new provisioning certificate. *Used the certificate for Distribution profile, not just Developer. *Used the "Clean all targets" function in XCode. *Deleted any build folders from your application's directory tree in the Finder. After that, build and run your application. For a fuller explanation, see Apple's documentation about this. A: For the iOS error "Application failed codesign verification", see Apple's complete list of potential causes at the following URL "How do I resolve the error: Application failed codesign verification?" A: I had the same issue and tried all the solutions listed and then some. But it turned out that it was something so simple, I could kick myself! Set your Archive Build Configuration to Release. You can do this by going into PRODUCT -> EDIT SCHEME -> ARCHIVE -> BUILD CONFIGURATION -> SET TO RELEASE. Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7636019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I correctly update a progress bar for an operation of unknown duration within an Eclipse wizard? I have implemented a wizard for my Eclipse plug-in, showing several pages. One of these pages needs some lengthy initialization, that means it consists of a SWT table, which needs to be populated by information coming from an external source. This source needs to be activated first (one single method call that returns after a couple of seconds - I can not know in advance how long it will take exactly), before it can be used as input for for the table viewer. This initialization is currently done by the table model provider when it needs to access the external source for the first time. Therefore, when I enter the wizard page, I would like to show a dummy progress bar that just counts up for a while. My approach was the following, but unfortunately does not work at all: private void initViewer() { IRunnableWithProgress runnable = new IRunnableWithProgress() { // needed to embed long running operation into the wizard page @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { SubMonitor progress = SubMonitor.convert(monitor); Thread thread = new Thread() { @Override public void run() { Display.getDefault().syncExec(new Runnable() { public void run() { viewer.setInput(ResourcesPlugin.getWorkspace().getRoot()); // this will make the table provider initialize the external source. } }); } }; thread.start(); while(thread.isAlive()) { progress.setWorkRemaining(10000); progress.worked(1); } progress.done(); } }; try { getContainer().run(false, false, runnable); } catch(Exception e) { throw new Exception("Could not access data store", e); } } This method gets then invoked when the wizard page's setVisible()-method is called and should, after a couple of seconds, set the viewer's input. This, however, never happens, because the inner-most run()-method never gets executed. Any hints on how to deal with long-running (where an exact estimate is not available) initializations in Eclipse wizards would be very appreciated! A: I have given below a simple example on how to use IRunnableWithProgress along with a ProgressMonitorDialog to perform a task of unknown quantity. To start with, have an implementation to IRunnableWithProgress from where the actual task is performed. This implementation could be an inner class. public class MyRunnableWithProgress implements IRunnableWithProgress { private String _fileName; public MyRunnableWithProgress(String fileName) { _fileName = fileName; } @Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int totalUnitsOfWork = IProgressMonitor.UNKNOWN; monitor.beginTask("Performing read. Please wait...", totalUnitsOfWork); performRead(_fileName, monitor); // This only performs the tasks monitor.done(); } } Now, a generic implementation to ProgressMonitorDialog can be created as below which could be used for other places where a progress monitor dialog is required. public class MyProgressMonitorDialog extends ProgressMonitorDialog { private boolean cancellable; public MyProgressMonitorDialog(Shell parent, boolean cancellable) { super(parent); this.cancellable = cancellable; } @Override public Composite createDialogArea(Composite parent) { Composite container = (Composite) super.createDialogArea(parent); setCancelable(cancellable); return container; } } Having got the required implementation, the task can be invoked as below to get it processed with a progress dialog. boolean cancellable = false; IRunnableWithProgress myRunnable = new MyRunnableWithProgress(receivedFileName); ProgressMonitorDialog progressMonitorDialog = new MyProgressMonitorDialog(getShell(), cancellable); try { progressMonitorDialog.run(true, true, myRunnable); } catch (InvocationTargetException e) { // Catch in your best way throw new RuntimeException(e); } catch (InterruptedException e) { //Catch in your best way Thread.currentThread().interrupt(); } Hope this helps! A: I assume the reason why it's "not working" for you is that the preparation of input is done in UI thread meaning that the progress bar cannot be updated. A better approach is to prepare input in advance and only set input to viewer after that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to update PDF metadata with CAM::PDF How can I add/overwrite the title and author metadata of a PDF using CAM::PDF? A: I'm the author of CAM::PDF. The library doesn't support this sort of edit, but you can do it by digging into the internals like this: #!perl -w use strict; use CAM::PDF; my $infile = shift || die 'syntax...'; my $outfile = shift || die 'syntax...'; my $pdf = CAM::PDF->new($infile) || die; my $info = $pdf->getValue($pdf->{trailer}->{Info}); if ($info) { #use Data::Dumper; print Dumper($info); my $title = $info->{Title}; if ($title) { $title->{value} = 'Foo'; # for a proper implementation, we should mark the holder of $info as dirty... # But cleanoutput ignores dirty flags anyway and writes the whole doc $pdf->cleanoutput($outfile); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I change the project directory in App Engine Launcher? I have a project (a version of which has already been deployed) in the App Engine Launcher, and I would like to change the project directory, as I have since moved the project files to a new directory. But, when I click to edit the project, the option to browse to a different directory is disabled. I am using App Engine SDK 1.5.4 on Windows XP. Thanks in advance for your help. It looks like this is a known issue (here), but the poster says s/he is running Ubuntu, not Windows. A: You can always delete (Ctrl+Del) and add the application again its not a lot of trouble.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2010 crashes at startup, even in safe mode I have Visual Studio 2010 Premium in a virtual machine (VM) and all was working fine until today, when I uninstalled Office 2010 Trial, installed Office 2010 Professional, and created a snapshot of my VM. Now when I open Visual Studio, the interface appears for one or two seconds and disappears. The problem comes when I open a solution (.sln) file (it crashes after loading the solution) or when I just open Visual Studio 2010 (even in Safe Mode). How do I fix this? Here is the log: <?xml-stylesheet type="text/xsl" href="ActivityLog.xsl"?> <activity> <entry> <record>1</record> <time>2011/10/03 13:41:20.894</time> <type>Information</type> <source>VisualStudio</source> <description>Microsoft Visual Studio 2010 version: 10.0.30319.1</description> </entry> <entry> <record>2</record> <time>2011/10/03 13:41:21.234</time> <type>Information</type> <source>VisualStudio</source> <description>Running in User Groups: Administrators Users</description> </entry> <entry> <record>3</record> <time>2011/10/03 13:41:21.304</time> <type>Information</type> <source>VisualStudio</source> <description>Available Drive Space: C:\ drive has 11464269824 bytes</description> </entry> <entry> <record>4</record> <time>2011/10/03 13:41:21.334</time> <type>Information</type> <source>VisualStudio</source> <description>Internet Explorer Version: 8.0.6001.19120</description> </entry> <entry> <record>5</record> <time>2011/10/03 13:41:21.725</time> <type>Information</type> <source>VisualStudio</source> <description>.NET Framework Version: 4.0.31106.0</description> </entry> <entry> <record>6</record> <time>2011/10/03 13:41:21.735</time> <type>Information</type> <source>VisualStudio</source> <description>MSXML Version: 6.20.1103.0</description> </entry> <entry> <record>7</record> <time>2011/10/03 13:41:21.915</time> <type>Information</type> <source>VisualStudio</source> <description>Creating PkgDefCacheNonVolatile</description> </entry> <entry> <record>8</record> <time>2011/10/03 13:41:22.086</time> <type>Information</type> <source>VisualStudio</source> <description>Double-checking master pkgdef file</description> </entry> <entry> <record>9</record> <time>2011/10/03 13:41:22.146</time> <type>Information</type> <source>VisualStudio</source> <description>PkgDefManagement initialized</description> </entry> <entry> <record>12</record> <time>2011/10/03 13:41:22.296</time> <type>Information</type> <source>VisualStudio</source> <description>PkgDefSearchPath</description> <path>C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\Extensions;C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\CommonExtensions;C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\devenv.admin.pkgdef</path> </entry> <entry> <record>15</record> <time>2011/10/03 13:41:22.456</time> <type>Information</type> <source>VisualStudio</source> <description>Searching for PkgDefs from search path</description> <path>C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\Extensions;C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\CommonExtensions;C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\devenv.admin.pkgdef</path> </entry> <entry> <record>16</record> <time>2011/10/03 13:41:22.486</time> <type>Information</type> <source>VisualStudio</source> <description>User extensions enabled by setting</description> <path>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\ExtensionManager\EnableAdminExtensions</path> </entry> <entry> <record>17</record> <time>2011/10/03 13:41:22.536</time> <type>Information</type> <source>VisualStudio</source> <description>Missing folder or file during PkgDef scan</description> <hr>80030002</hr> <path>C:\Program Files\Microsoft Visual Studio 10.0\\Common7\IDE\devenv.admin.pkgdef</path> </entry> <entry> <record>18</record> <time>2011/10/03 13:41:22.556</time> <type>Information</type> <source>VisualStudio</source> <description>Discovered 14 PkgDef files</description> </entry> <entry> <record>20</record> <time>2011/10/03 13:41:22.596</time> <type>Information</type> <source>VisualStudio</source> <description>Current pkgdef cache timestamp is valid</description> </entry> <entry> <record>21</record> <time>2011/10/03 13:41:22.616</time> <type>Information</type> <source>VisualStudio</source> <description>Checking age of HKEY_LOCAL_MACHINE vs PkgDef cache</description> <path>Software\Microsoft\VisualStudio\10.0</path> </entry> <entry> <record>22</record> <time>2011/10/03 13:41:22.837</time> <type>Information</type> <source>VisualStudio</source> <description>Newest node in merge source</description> <path>UITestExtensionPackages</path> </entry> <entry> <record>23</record> <time>2011/10/03 13:41:22.847</time> <type>Information</type> <source>VisualStudio</source> <description>PkgDef configuration cache is OK</description> </entry> <entry> <record>24</record> <time>2011/10/03 13:41:22.857</time> <type>Information</type> <source>VisualStudio</source> <description>PkgDefManagement startup complete</description> </entry> <entry> <record>25</record> <time>2011/10/03 13:41:22.857</time> <type>Information</type> <source>VisualStudio</source> <description>AppId setting up registry detouring</description> </entry> <entry> <record>26</record> <time>2011/10/03 13:41:22.867</time> <type>Information</type> <source>VisualStudio</source> <description>Adding detour rule 1: from HKLM</description> <path>Software\Microsoft\VisualStudio\10.0</path> </entry> <entry> <record>31</record> <time>2011/10/03 13:41:23.227</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{5E56B3DB-7964-4588-8D49-D3523AB7BDB9}</guid> </entry> <entry> <record>32</record> <time>2011/10/03 13:41:23.698</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Environment Package Window Management]</description> <guid>{5E56B3DB-7964-4588-8D49-D3523AB7BDB9}</guid> </entry> <entry> <record>33</record> <time>2011/10/03 13:41:23.718</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Environment Package Window Management]</description> <guid>{5E56B3DB-7964-4588-8D49-D3523AB7BDB9}</guid> </entry> <entry> <record>34</record> <time>2011/10/03 13:41:23.888</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{F384B236-B4A9-401B-BC58-3106E3ACA3EC}</guid> </entry> <entry> <record>35</record> <time>2011/10/03 13:41:23.908</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Shell Common UI Package]</description> <guid>{F384B236-B4A9-401B-BC58-3106E3ACA3EC}</guid> </entry> <entry> <record>36</record> <time>2011/10/03 13:41:23.918</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Shell Common UI Package]</description> <guid>{F384B236-B4A9-401B-BC58-3106E3ACA3EC}</guid> </entry> <entry> <record>37</record> <time>2011/10/03 13:41:24.349</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function VBDispatch::GetTypeLib</description> </entry> <entry> <record>38</record> <time>2011/10/03 13:41:24.359</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function LoadDTETypeLib</description> </entry> <entry> <record>39</record> <time>2011/10/03 13:41:24.369</time> <type>Information</type> <source>VisualStudio</source> <description>Leaving function LoadDTETypeLib</description> </entry> <entry> <record>40</record> <time>2011/10/03 13:41:24.369</time> <type>Information</type> <source>VisualStudio</source> <description>Leaving function VBDispatch::GetTypeLib</description> <guid>{80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2}</guid> </entry> <entry> <record>41</record> <time>2011/10/03 13:41:24.379</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function VBDispatch::GetTypeLib</description> </entry> <entry> <record>42</record> <time>2011/10/03 13:41:24.379</time> <type>Information</type> <source>VisualStudio</source> <description>Leaving function VBDispatch::GetTypeLib</description> <guid>{18BEB7F2-CA98-11D1-B6E7-00A0C90F2744}</guid> </entry> <entry> <record>43</record> <time>2011/10/03 13:41:24.399</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function VBDispatch::GetTypeLib</description> </entry> <entry> <record>44</record> <time>2011/10/03 13:41:24.399</time> <type>Information</type> <source>VisualStudio</source> <description>Leaving function VBDispatch::GetTypeLib</description> <guid>{80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2}</guid> </entry> <entry> <record>45</record> <time>2011/10/03 13:41:24.409</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function VBDispatch::GetTypeLib</description> </entry> <entry> <record>46</record> <time>2011/10/03 13:41:24.419</time> <type>Information</type> <source>VisualStudio</source> <description>Leaving function VBDispatch::GetTypeLib</description> <guid>{80CC9F66-E7D8-4DDD-85B6-D9E6CD0E93E2}</guid> </entry> <entry> <record>47</record> <time>2011/10/03 13:41:24.419</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{53544C4D-E3F8-4AA0-8195-8A8D16019423}</guid> </entry> <entry> <record>48</record> <time>2011/10/03 13:41:24.419</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Studio Source Control Integration Package]</description> <guid>{53544C4D-E3F8-4AA0-8195-8A8D16019423}</guid> </entry> <entry> <record>49</record> <time>2011/10/03 13:41:24.429</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{D79B7E0A-F994-4D4D-8FAE-CAE147279E21}</guid> </entry> <entry> <record>50</record> <time>2011/10/03 13:41:24.429</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [team foundation server provider stub package]</description> <guid>{D79B7E0A-F994-4D4D-8FAE-CAE147279E21}</guid> </entry> <entry> <record>51</record> <time>2011/10/03 13:41:24.429</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [team foundation server provider stub package]</description> <guid>{D79B7E0A-F994-4D4D-8FAE-CAE147279E21}</guid> </entry> <entry> <record>52</record> <time>2011/10/03 13:41:24.429</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Studio Source Control Integration Package]</description> <guid>{53544C4D-E3F8-4AA0-8195-8A8D16019423}</guid> </entry> <entry> <record>53</record> <time>2011/10/03 13:41:24.479</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{A9405AE6-9AC6-4F0E-A03F-7AFE45F6FCB7}</guid> </entry> <entry> <record>54</record> <time>2011/10/03 13:41:24.489</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Microsoft.VisualStudio.TestTools.TestCaseManagement.QualityToolsPackage, Microsoft.VisualStudio.QualityTools.TestCaseManagement, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description> <guid>{A9405AE6-9AC6-4F0E-A03F-7AFE45F6FCB7}</guid> </entry> <entry> <record>55</record> <time>2011/10/03 13:41:24.679</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Microsoft.VisualStudio.TestTools.TestCaseManagement.QualityToolsPackage, Microsoft.VisualStudio.QualityTools.TestCaseManagement, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description> <guid>{A9405AE6-9AC6-4F0E-A03F-7AFE45F6FCB7}</guid> </entry> <entry> <record>56</record> <time>2011/10/03 13:41:24.809</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{52CBD135-1F97-2580-011F-C7CD052E44DE}</guid> </entry> <entry> <record>57</record> <time>2011/10/03 13:41:24.819</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Microsoft.VisualStudio.TestTools.Tips.TuipPackage.TuipPackage, Microsoft.VisualStudio.QualityTools.Tips.TuipPackage, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description> <guid>{52CBD135-1F97-2580-011F-C7CD052E44DE}</guid> </entry> <entry> <record>58</record> <time>2011/10/03 13:41:24.870</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}</guid> </entry> <entry> <record>59</record> <time>2011/10/03 13:41:24.940</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual C# Project System]</description> <guid>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}</guid> </entry> <entry> <record>60</record> <time>2011/10/03 13:41:24.950</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{6E87CFAD-6C05-4ADF-9CD7-3B7943875B7C}</guid> </entry> <entry> <record>61</record> <time>2011/10/03 13:41:25.300</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Studio Common IDE Package]</description> <guid>{6E87CFAD-6C05-4ADF-9CD7-3B7943875B7C}</guid> </entry> <entry> <record>62</record> <time>2011/10/03 13:41:25.320</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Studio Common IDE Package]</description> <guid>{6E87CFAD-6C05-4ADF-9CD7-3B7943875B7C}</guid> </entry> <entry> <record>63</record> <time>2011/10/03 13:41:25.330</time> <type>Information</type> <source>VisualStudio</source> <description>Loading UI library</description> <guid>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}</guid> <path>c:\Program Files\Microsoft Visual Studio 10.0\VC#\VCSPackages\*\csprojui.dll</path> </entry> <entry> <record>64</record> <time>2011/10/03 13:41:25.340</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual C# Project System]</description> <guid>{FAE04EC1-301F-11D3-BF4B-00C04F79EFBC}</guid> </entry> <entry> <record>65</record> <time>2011/10/03 13:41:25.340</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{164B10B9-B200-11D0-8C61-00A0C91E29D5}</guid> </entry> <entry> <record>66</record> <time>2011/10/03 13:41:25.350</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Basic Project System]</description> <guid>{164B10B9-B200-11D0-8C61-00A0C91E29D5}</guid> </entry> <entry> <record>67</record> <time>2011/10/03 13:41:25.350</time> <type>Information</type> <source>VisualStudio</source> <description>Loading UI library</description> <guid>{164B10B9-B200-11D0-8C61-00A0C91E29D5}</guid> <path>c:\Program Files\Microsoft Visual Studio 10.0\VB\Bin\*\msvbprjui.dll</path> </entry> <entry> <record>68</record> <time>2011/10/03 13:41:25.360</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Basic Project System]</description> <guid>{164B10B9-B200-11D0-8C61-00A0C91E29D5}</guid> </entry> <entry> <record>69</record> <time>2011/10/03 13:41:25.360</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Microsoft.VisualStudio.TestTools.Tips.TuipPackage.TuipPackage, Microsoft.VisualStudio.QualityTools.Tips.TuipPackage, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]</description> <guid>{52CBD135-1F97-2580-011F-C7CD052E44DE}</guid> </entry> <entry> <record>70</record> <time>2011/10/03 13:41:25.390</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{6077292C-6751-4483-8425-9026BC0187B6}</guid> </entry> <entry> <record>71</record> <time>2011/10/03 13:41:25.390</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Unknown]</description> <guid>{6077292C-6751-4483-8425-9026BC0187B6}</guid> </entry> <entry> <record>72</record> <time>2011/10/03 13:41:25.410</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Unknown]</description> <guid>{6077292C-6751-4483-8425-9026BC0187B6}</guid> </entry> <entry> <record>73</record> <time>2011/10/03 13:41:25.591</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{7494682B-37A0-11D2-A273-00C04F8EF4FF}</guid> </entry> <entry> <record>74</record> <time>2011/10/03 13:41:25.591</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Windows Forms Designer Package]</description> <guid>{7494682B-37A0-11D2-A273-00C04F8EF4FF}</guid> </entry> <entry> <record>75</record> <time>2011/10/03 13:41:25.601</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Windows Forms Designer Package]</description> <guid>{7494682B-37A0-11D2-A273-00C04F8EF4FF}</guid> </entry> <entry> <record>76</record> <time>2011/10/03 13:41:25.701</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{DA9FB551-C724-11D0-AE1F-00A0C90FFFC3}</guid> </entry> <entry> <record>77</record> <time>2011/10/03 13:41:25.711</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Studio Environment Package]</description> <guid>{DA9FB551-C724-11D0-AE1F-00A0C90FFFC3}</guid> </entry> <entry> <record>78</record> <time>2011/10/03 13:41:25.711</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Studio Environment Package]</description> <guid>{DA9FB551-C724-11D0-AE1F-00A0C90FFFC3}</guid> </entry> <entry> <record>79</record> <time>2011/10/03 13:41:26.652</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{2DC9DAA9-7F2D-11D2-9BFC-00C04F9901D1}</guid> </entry> <entry> <record>80</record> <time>2011/10/03 13:41:26.652</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Studio Logging Package]</description> <guid>{2DC9DAA9-7F2D-11D2-9BFC-00C04F9901D1}</guid> </entry> <entry> <record>81</record> <time>2011/10/03 13:41:26.662</time> <type>Information</type> <source>VisualStudio</source> <description>Loading UI library</description> <guid>{2DC9DAA9-7F2D-11D2-9BFC-00C04F9901D1}</guid> <path>c:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE*\VsLogUI.dll</path> </entry> <entry> <record>82</record> <time>2011/10/03 13:41:26.672</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Studio Logging Package]</description> <guid>{2DC9DAA9-7F2D-11D2-9BFC-00C04F9901D1}</guid> </entry> <entry> <record>83</record> <time>2011/10/03 13:41:26.672</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{715F10EB-9E99-11D2-BFC2-00C04F990235}</guid> </entry> <entry> <record>84</record> <time>2011/10/03 13:41:26.682</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Visual Studio Environment Menu Package]</description> <guid>{715F10EB-9E99-11D2-BFC2-00C04F990235}</guid> </entry> <entry> <record>85</record> <time>2011/10/03 13:41:26.682</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Visual Studio Environment Menu Package]</description> <guid>{715F10EB-9E99-11D2-BFC2-00C04F990235}</guid> </entry> <entry> <record>86</record> <time>2011/10/03 13:41:26.682</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{0E13FC54-9231-410B-8B74-95689CD32627}</guid> </entry> <entry> <record>87</record> <time>2011/10/03 13:41:26.692</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [Start Page]</description> <guid>{0E13FC54-9231-410B-8B74-95689CD32627}</guid> </entry> <entry> <record>88</record> <time>2011/10/03 13:41:26.692</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [Start Page]</description> <guid>{0E13FC54-9231-410B-8B74-95689CD32627}</guid> </entry> <entry> <record>89</record> <time>2011/10/03 13:41:26.712</time> <type>Information</type> <source>VisualStudio</source> <description>Entering function CVsPackageInfo::HrInstantiatePackage</description> <guid>{8FF5C2A8-5EBA-4717-8EE1-46B6427D8FF3}</guid> </entry> <entry> <record>90</record> <time>2011/10/03 13:41:26.722</time> <type>Information</type> <source>VisualStudio</source> <description>Begin package load [MRU Data Source]</description> <guid>{8FF5C2A8-5EBA-4717-8EE1-46B6427D8FF3}</guid> </entry> <entry> <record>91</record> <time>2011/10/03 13:41:26.722</time> <type>Information</type> <source>VisualStudio</source> <description>End package load [MRU Data Source]</description> <guid>{8FF5C2A8-5EBA-4717-8EE1-46B6427D8FF3}</guid> </entry> <entry> <record>92</record> <time>2011/10/03 13:41:26.832</time> <type>Information</type> <source>VisualStudio</source> <description>ProductID: </description> </entry> <entry> <record>93</record> <time>2011/10/03 13:41:26.912</time> <type>Information</type> <source>VisualStudio</source> <description>Microsoft Data Access Version: 2.81.1132.0</description> </entry> <entry> <record>94</record> <time>2011/10/03 13:41:27.343</time> <type>Information</type> <source>VisualStudio</source> <description>Application Name: Microsoft Visual Studio</description> </entry> <entry> <record>95</record> <time>2011/10/03 13:41:27.343</time> <type>Information</type> <source>VisualStudio</source> <description>SKU Edition: Premium</description> </entry> <entry> <record>96</record> <time>2011/10/03 13:41:27.844</time> <type>Information</type> <source>VisualStudio</source> <description>Shutting down pkgdef registry</description> </entry> <entry> <record>97</record> <time>2011/10/03 13:41:27.874</time> <type>Information</type> <source>VisualStudio</source> <description>Released pkgdef cache usage tracker</description> </entry> <entry> <record>98</record> <time>2011/10/03 13:41:27.914</time> <type>Information</type> <source>VisualStudio</source> <description>PkgDef registry shutdown complete</description> </entry> </activity> A: If Roman's suggestion does not pan out, I would reset the entire VS installation. You can do this as follows from the VS command prompt: devenv.exe /resetsettings devenv.exe /setup This should put VS back to it original installed state. A: I had the same problem caused by changing one of my project's property pages during compilation. The following steps solved this issue: * *Open Visual Studio 2008. *Open some project you have or create new empty project. *Modify the debugger command to point to the visual studio 2010 devenv.exe. *Launch the debugger and the Visual Studio 2010 will run. *Press File -> Exit from the Visual Studio 2010 menu, and that's it. A: A few suggestions as for working around the problem without knowing the specific cause of the crash: * *Disable Visual Studio Add-Ins *Delete solution/project temporary files (such as .SDF, intermediate files, etc.) Re-open the solution file in a restarted Visual Studio to give it another try. A: I fixed mine: logged in as another user (administrator) launched visual studio 10 ultimate. It worked. Came BACK as my normal user - all was well. * *I did a remote desktop connection to the same machine as a different user *I did a /resetsettings before attempting the other user
{ "language": "en", "url": "https://stackoverflow.com/questions/7636044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Radio buttons using wxpython I'm Building a gui using wxpython.. i have buttons and radiobuttons in it, and i wanna to do such tasks based on what the current values of the widgets in the gui .. the insert button has a multiple if statement one of these if statement is to check whether a radiobutton is selected. i dont want to bind an event to the radio button so i have checked about it in the insert button using this is the defined radion button self.rb1 = wx.RadioButton(self.panel, -1, 'Is this a required pre_action to the next step?', (5, 220)) and this is the check condition if self.rb1.GetValue(): # do something here and also : if self.rb1.GetValue() == 'True': # do some tasks in both way (which is already the same) the is nothing happend when i choose the radio button rb1 ! so what is the problwm of this ? A: I don't know what that doesn't work for you. It works for me just fine. See sample code below: import wx class MyForm(wx.Frame): #---------------------------------------------------------------------- def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial") panel = wx.Panel(self, wx.ID_ANY) self.radio = wx.RadioButton(panel, label="Test", style = wx.RB_GROUP) self.radio2 = wx.RadioButton(panel, label="Test2") btn = wx.Button(panel, label="Check Radio") btn.Bind(wx.EVT_BUTTON, self.onBtn) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.radio, 0, wx.ALL, 5) sizer.Add(self.radio2, 0, wx.ALL, 5) sizer.Add(btn, 0, wx.ALL, 5) panel.SetSizer(sizer) #---------------------------------------------------------------------- def onBtn(self, event): """""" print "First radioBtn = ", self.radio.GetValue() print "Second radioBtn = ", self.radio2.GetValue() # Run the program if __name__ == "__main__": app = wx.PySimpleApp() frame = MyForm().Show() app.MainLoop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7636045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: import statement to create a session object in android In android, I want to create a session object. I saw a statment in one of the post as follow; public static Session mySessionObject = new Session(); where can i get the import statment? I simple want to have a client base login that manages session. Thank you, A: Session session = new Session(); Properties props = new Properties(); session = Session.getDefaultInstance(props, this); then you can add MimeMessage message = new MimeMessage(session); A: The android framework doesn't have any Session class. Ask the author of that code, what he used there. If you don't have special needs, you can write your own Session class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why is read-only sqlce is very slow on windows phone 7? i am developing an app on windows phone 7 (wp7) using sdk 7.1. i am using the natively supported sqlce database. the database only stores 1 table with 5 "string" columns. however, there are nearly 90,000 records. the table is indexed (specified using the Index attribute). this reference database is always accessed from the installation folder (not from iso store, because it is read-only). i am using linq, per the recommendations on MSDN, to query for data. my linq queries are very simple. var items = from e in myDataContext.MyItems where e.col1 == 'literal' select e; in some cases, i have to implement paging, so i do something like the following. var items = (from e in myDataContext.MyItems where e.col1 == 'literal' select e).Skip(offset).Take(maxResults); the problem is that performance is very slow. i haven't tracked down where the bottleneck is, but i suspect it's with sqlce and/or linq. anyone have any suggestion for me on how to troubleshoot this problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can i have a single NSMutableArray in my multiple views application? I have a navigational based application which has multiple views. Is it possible to use one single NSMutableArray for the whole applicaiton? Can i add objects to that NSMutableArray in one view and then remove object from the same NSMutableArray from some other view? I tried myappAppDelegate *appDelegate = (myappAppDelegate *)[[UIApplication sharedApplication] delegate]; but it gives me null when i try to access appDelegate's array. If anyone can give me any idea or helping link or tutrorial. Thanks in advance. A: For your type of issue I would use a singleton. http://en.wikipedia.org/wiki/Singleton_pattern The appdelegate is a singleton too but you can reduce a bit the number of coded lines if you use your own singleton. A: If you are having multiple views in your application, and in that case you want to have a variable accessible to every view, you should always create a Model/Data(singleton) class and define the variable in it. Something like this : //DataClass.h @interface DataClass : NSObject { NSMutableArray *arrGlobal; } @property(nonatomic,retain)NSMutableArray *arrGlobal; +(DataClass*)getInstance; @end //DataClass.m @implementation DataClass @synthesize arrGlobal; static DataClass *instance =nil; +(DataClass *)getInstance { @synchronized(self) { if(instance==nil) { instance= [DataClass new]; } } return instance; } Now in your view controller you need to call this method as : DataClass *obj=[DataClass getInstance]; obj.arrGlobal = arrLocal; This variable will be accessible to every view controller. You just have to create an instance of Data class. A: The AppDelegate approach should work, and you should probably figure out why it's not working, even if you go with a singleton. The statement to get your appDelegate pointer appears to be correct, so I'm guessing that the pointer to the array is either not getting set (and retained) in your myappDelegate class, or you did not create the AppDelegate instance correctly in the first place. A: On the Singleton approach add this instance.arrGlobal = [[NSMutableArray alloc] init]; this way: @synchronized(self) { if(instance==nil) { instance= [DataClass new]; instance.arrGlobal = [[NSMutableArray alloc] init]; } } return instance; This way you can initilize the array and use it properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extracting events from Google Calendar Today I created code: // Create a CalenderService and authenticate CalendarService myService = new CalendarService("exampleCo-exampleApp-1"); myService.setUserCredentials("j...@gmail.com", "mypassword"); // Send the request and print the response URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full"); CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class); System.out.println("Your calendars:"); System.out.println(); for (int i = 0; i < resultFeed.getEntries().size(); i++) { CalendarEntry entry = resultFeed.getEntries().get(i); System.out.println("\t" + entry.getTitle().getPlainText()); } This code gives out the list of all calendars. At me - a box calendar, a calendar of birthdays of friends and a calendar of holidays. I need to receive all events occurring today - i.e. both my notes, and birthdays of friends, and holidays. How I am able to do it? This code returns event for specified data range, but it is work for private calendar only; i tried to replace "private" for "allcalendars", but it doesn't work: URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); CalendarQuery myQuery = new CalendarQuery(feedUrl); myQuery.setMinimumStartTime(DateTime.parseDateTime("2006-03-16T00:00:00")); myQuery.setMaximumStartTime(DateTime.parseDateTime("2006-03-24T23:59:59")); CalendarService myService = new CalendarService("exampleCo-exampleApp-1"); myService.setUserCredentials("jo@gmail.com", "mypassword"); // Send the request and receive the response: CalendarEventFeed resultFeed = myService.query(myQuery, Feed.class); A: Your problem is in the your feed url. The one you are using is getting the events on the default calendar. To get the other calendars you should replace default in the url by the calendar's id, for example: feedUrl = new URL("https://www.google.com/calendar/feeds/xxxxxxxxxxxxxxxxx@group.calendar.google.com/private/full");
{ "language": "en", "url": "https://stackoverflow.com/questions/7636058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: _InterlockedCompareExchange64 compiler intrinsic on Windows XP? Based on the Microsoft documentation InterlockedCompareExchange64 is not available as a Windows API call until Windows Vista. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683562(v=vs.85).aspx. However, it seems like the _InterlockedCompareExchange64 compiler intrinsic might be available on Windows XP as long as you are using a Pentium or above processor: http://msdn.microsoft.com/en-us/library/ttk2z1ws(VS.80).aspx . Is this correct? Is there any gotcha there? A: The documentation is quite consistent. API function is available since Vista or Server 2003, but if you prefer an intrinsic (that is no extrernal API required) MS compiler will implement the function through specific CPU instruction (see Remarks): Because _InterlockedCompareExchange64 uses the cmpxchg8b instruction, it is not available on pre-Pentium processors, such as the 486. It is noted that this instruction might be an issue with very old CPUs. This means that if you run your app on 486 processor, it will just crash as soon as it stumbles on this code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Flash stage dimensions when exporting for iPhone AND iPad In the Flash CS 5.5 AIR settings for iOS, in the General tab of a panel, there's a menu that lets you specify the target device: * *iPhone; *iPad; *(both) iPhone and iPad; What happens if I specify the third? That is: I can't understand if I can use the default stage dimensions (iPhone dimensions) or I must eventually create a stage (and assets) for iPad (and it will work for iPhone too). Can't find any documentation. A: I guess the best way to find out is to actually try it out! Many apps that work on both iPad and iPhone use the default stage dimensions and just resize the whole thing 2x when on an iPad. Although I haven't tried it with an AIR app, I would say the same behavior should be expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c# save directory between sessions Not really done this before so I wanted a few pointers. In my app, users are able to pick a folder that the application looks in when it is started to pick up some input files. What is the best way to save this information between sessions. the old fashion way I would have done in the past would be to have a config.ini file and read and write to that the path. However I am sure there are better ways now. I don't want to have to write to the registary as I want a app that can be installed and uninstalled simple by copying a folder or deleating the folder. Is there any way to save configuration settings that the uesr can update and remian constant between sessions? Cheers Aaron A: AFAIK, the way is done now, is by writing these values to the Application.Settings file; however, that's not too different than writing to any XML file and reading it on startup. Either alternative is almost equally simple. A: As Icarus said, you need a .settings file. You can specify that settings be Scoped to the User. A: You can also look into using IsolatedStorage ( http://msdn.microsoft.com/en-us/library/x7dzh4ws.aspx ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: regular expression no characters I have this regular expression ([A-Z], )* which should match something like test, (with a space after the comma) How to I change the regex expression so that if there are any characters after the space then it doesn't match. For example if I had: test, test I'm looking to do something similar to ([A-Z], ~[A-Z])* Cheers A: Use the following regular expression: ^[A-Za-z]*, $ Explanation: * *^ matches the start of the string. *[A-Za-z]* matches 0 or more letters (case-insensitive) -- replace * with + to require 1 or more letters. *, matches a comma followed by a space. *$ matches the end of the string, so if there's anything after the comma and space then the match will fail. As has been mentioned, you should specify which language you're using when you ask a Regex question, since there are many different varieties that have their own idiosyncrasies. A: ^([A-Z]+, )?$ The difference between mine and Donut is that he will match , and fail for the empty string, mine will match the empty string and fail for ,. (and that his is more case-insensitive than mine. With mine you'll have to add case-insensitivity to the options of your regex function, but it's like your example) A: I am not sure which regex engine/language you are using, but there is often something like a negative character groups [^a-z] meaning "everything other than a character".
{ "language": "en", "url": "https://stackoverflow.com/questions/7636074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Something like an operation filter in WCF REST? I am looking for something like the AuthorizeAttribute in MVC, something I can use like this: [WebGet(UriTemplate = "data/{spageNumber}")] [WebCache(CacheProfileName = "SampleProfile")] [WcfAuthorize] public IEnumerable<SampleItem> GetCollection(String spageNumber) { Int32 itemsPerPage = 10; Int32 pageNumber = Int32.Parse(spageNumber); return Enumerable.Range(pageNumber * itemsPerPage, itemsPerPage) .Select(i => SampleItem.Create(i)); } That WcfAuthorizeAttribute, will try to authenticate the user with FormsAuthentication, and set the context's IPrincipal, or return a HTTP 401 Unauthorized. I have tried with a IOperationBehavior, but I gets executed in the first method, whichever it be, not in the method I have set the attribute. How can this be achieved in WCF REST? Regards. PS: I have seen the RequestInterceptor example in the Starter Kit, but what I want is put it in some methods only, and the example looks like a filter you execute in all the operations. A: You can use AOP to achieve this. I have used PostSharp as an AOP tool to achieve this functionality. You can also find a sample on their website. The OnMethodEntry gets executed before a method (that is decorated with this attribute) is executed and you can perform your validation there. I did a quick sample to test this and it worked. [Serializable] [ProvideAspectRole(StandardRoles.Security)] public class WcfAuthorizeAttribute : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { //extract forms authentication token here from the request and perform validation. } } And you could decorate your WCF methods like below. [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Service1 { [WcfAuthorize] [WebGet(UriTemplate = "")] public List<SampleItem> GetCollection() { return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Predict consequences of installing LESS, CSS3PIE on a high-load project I faced situation of global site redesign (not appearance, but code architecture and underlying technologies). Website has about 135 000 visitors everyday. And it's crucial to make right decision now. I had no experience of using LESS and CSS3PIE on such big projects before. Maybe some of you can predict some trouble which I can run into using technologies mentioned above. I would like to know advantages and drawbacks. Isn't it better to use old tested and reliable methods like sprites for round corner buttons with shadows and gradients? I look at http://zappos.com. They just degrade gracefully in IE and don't use CSS3PIE. A: Nobody answered me, so I try to answer myself. Since there are server-side LESS-compilers for all major platforms (Ruby, .NET, PHP) I decided to use LESS but compile server-side instead of using LESS.js which is not good because it prevents client's browser from caching CSS. As concerning CSS3PIE I don't see any significant drawbacks of using it, a little more load lies on client using IE but it's not so bad. The only issue I can foresee now is background and decoration disappearing on popups. I have already encountered this problem and posted a question here but no one ever answered. A: I would avoid using CSS3Pie for production sites. In my experience, the higher the number of CSS3Pie-rendered elements on the page, the worse IE8/9 will perform. Specifically, when I was using IE9 with an IE8 document mode, and with at least 2 elements rendered using CSS3Pie (using border-radius and linear-gradient), I observed a noticeable lag when scrolling the browser window. That is, I would try and scroll down the page, and the scroll bar would take a couple of seconds to "catch up" with the mouse pointer. As soon as I switched CSS3Pie off, no lag when scrolling was observed. The same applies for IE8 in my experience.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Using Facebook php in codeigniter adds PHPSESSID to URLs? I started using facebook php sdk with codeigniter but since then the urls on my website all have a 'PHPSESSID' added to the end. I created a config file containing the app id and secret and used the following code to load the library. $this->load->library('facebook'); Does anybody know of a workaround to this problem?? A: The Facebook script uses PHP native sessions. You can change this in your php.ini file: # set session.use_cookies = 1 # to session.use_cookies = 0 http://www.webune.com/forums/disable-phpsessid-phpini.html A: Instead of changing php.ini setting I went ahead and replaced the $_SESSION usages in facebook.php with Codeigniter sessions $this->session->set_userdata(). Works for me till now. Not very foolproof I guess. A: Just figured it out: php.ini session.use_trans_sid = 0 This will hide (make intransparent / invisible) all the PHPSESSID from your URLs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert sql timestamp to yyyy-mm-ddThh:mm:ss.sssZ I need to convert a SQL Server timestamp format (stored on Timestamp java data type) into this format yyyy-mm-ddThh:mm:ss.sssZ (it's the date format parsed by Alfresco) How can I do it? thanks for your time! Andrea A: Try this SimpleDateFormat: SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" ); String yourformattedDate = sdf.format(yourDate); A: You could try and get the time (in ms) from your TimeStamp instance, create a Date instance and use the DateFormatter class to format it anyway you want. That is, assuming DateFormatter supports the format you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to obtain language independent values from Android Geocoder I am working on an application where i need to know the users location: country, state/province, and city/town. Then I want users to interact in some way based on their location: country, state/province, or city/town. However the geocoder gives me these locations in the language that the phone is set to. For that reason I can't accurately compare strings with other users that are in the same country, state/province, or city/town, if their language is set differently. 1 solution for countries is using the country codes. But states/provinces, or cities/towns are still a problem. Any suggestions? A: Use the constructor that accepts a Locale argument rather than the default (which uses the system locale). See http://developer.android.com/reference/android/location/Geocoder.html If all clients use the same locale argument, then all should receive the same response for the same requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JBoss 7 application, start/stop from ui? I am running an application on a Jboss 6 server and using mbeans to start/stop my app without redeploying/restarting server. I was testing on JBoss 7 and saw that there were no mbean support. How do I create that functionality now? I've yet to find anything on this. A: There is MBean support. In what area do you experience problems: when deploying MBeans or accessing them, ...? A: In the meantime (2015), there is a portation of the AS5 jmx-console, which can be deployed to AS7 and WildFly. See https://github.com/wildfly-extras/jmx-console
{ "language": "en", "url": "https://stackoverflow.com/questions/7636099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What SQL Server database and table does Sharepoint 2010 use to hold "Issue Tracking List" data? Trying to track down this table, I've spot checked some 160 tables and have not been able to find the table that stores data for this list. I have these databases created by Sharepoint 2010: Application_Registry _Service Managed Metadata Service My_Portal_WSS_Content MySites_WSS_Content PerformancePoint Service Application Search_Service_Application_CrawlStore Search_Service_Application_DB Search_Service_Application_PropertyStoreDB Secure_Store_Service_DB SharePoint_AdminContent SharePoint_Config StateService User Profile Service Application_ProfileDB User Profile Service Application_SocialDB User Profile Service Application_SyncDB WebAnalyticsServiceApplication_ReportingDB WebAnalyticsServiceApplication_StagingDB WSS_Logging WSS_Search Thanks! A: SharePoint uses a single table to store all the items from all the lists - dbo.AllUserData. If you need to access is directly, it is possible but cumbersome and not recommended. Without knowing the exact configuration I can only guess that the list you're looking for is stored in the My_Portal_WSS_Content database. Inspecting The SharePoint Content Database
{ "language": "en", "url": "https://stackoverflow.com/questions/7636101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery animation on window load on an infinite loop? I need a hand making this code below working. I've had it working so that when the user hovers over the image it animates up, then down when losing focus, but now I want it to run on window load on an infinite loop. $(document).ready(function(){ $(window).load(function(){ $('.navImage').animate({top:'-=13'}, 700) }, function(){ $('.navImage').animate({top:'+=13'}, 700); }); }); At the moment it's only animating 13pixels up, not down, and obviously the animation doesn't currently loop. Do I need to use some sort of callback? Any help would be great, thanks. [EDIT] Removed the height:toggle, didn't mean to include that. A: Try this: function moveUp() { $('.navImage').animate({top:'-=13', height:'toggle'}, 700, moveDown); } function moveDown() { $('.navImage').animate({top:'+=13'}, 700, moveUp); } $(document).ready(function(){ $(window).load(moveUp); }); === UPDATE 1 === function move(jElem, bUp) { jElem.animate( {top: (bUp ? '-' : '+') + '=13'}, 700, function() { move(jElem, !bUp); } ); } $(document).ready(function() { $(window).load(function() { $('.navImage').each(function() { move($(this), true); }); }); }); Also see my jsfiddle. === UPDATE 2 === Now they start with random delay: function move(jElem, bUp) { jElem.animate( {top: (bUp ? '-' : '+') + '=13'}, 700, function() { move(jElem, !bUp); } ); } $(document).ready(function() { $('.navImage').each(function(iIndex, jElem) { // get random delay var iTime = Math.floor(Math.random() * 700); setTimeout( function() { move($(jElem), true); }, iTime ); }); }); Also see my jsfiddle 2. === Update 3 === And in this jsfiddle additional with random speed: jsfiddle 3. A: function anim_up() { $('.navImage').animate({top:'-=13', height:'toggle'}, 700, anim_down) }; function anim_down() { $('.navImage').animate({top:'+=13'}, 700, anim_up); }; window.onload = anim_up; As a sidenote, you should replace that navImage class with an ID instead, if there's only one of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: html, displaying a link as normal text I was wondering if you could display a link as normal text. <a id="" href="" target="_parent"><img src="" width="121" height="20" alt=""> <div style="position:absolute;left:163px;top:1px;font-size: 12px; display: block"> <font color="white">Log in</font></a> I'm trying to overlap an image that is also a button, with the text "Log in", it works as it is with the code above, but I was wondering if I can change the "log in" which displays as blue and underlined to appear as normal text. A: In css: a { color: inherit; text-decoration: inherit; } These values can also be stuck in your anchor tag's style attribute. Should result in your anchor tags looking the same as the text color and decoration of the parent(s). A: If you don't want the link to be underlined, set " text-decoration:none" A: Short answer: yes. Longer answer: Yes, here is a fiddle, but you probably don't want to hide links from your user. stslavik makes a good point with "text-decoration: inherit". Here is another fiddle. On my browser the "blam" and "stslavic" both show with strike-through, but I'd go with the "inherit" versus the "none"; just seems better to me. A: use this code in your html file <style> a { text-decoration: none; color: #000; /* or whatever colour your text is */ } </style> A: If you have a look at Cascading Style Sheets (CSS) you can change the colour and the text style of the link. In your example, you could use <a id="" href="" target="_parent" style="color: white; text-decoration: none;"><img src="" width="121" height="20" alt=""> <div style="position:absolute; sleft:163px;top:1px;font-size: 12px; display: block"> <font color="white">Log in</font> </div> </a> However I would learn how to use external stylesheets and link them to your HTML through the <link> tag in the <head> of your html. You can then style up individual tags through the tag name, an id or a css class. So an updated example would be: <link rel="stylesheet" href="link-to-your-css-file" /> in your css file have a.imgLink{ color: white; text-decoration: none; } div.imgLink{ position: absolute; left: 163px; top: 1px; font-size: 12px; display: block; } Then your html would be <a class="imgLink" id="" href="" target="_parent"> <img src="" width="121" height="20" alt=""> <div class="imgLink"> Log In </div> </a> Not only does it make your HTML "dry" but it gives you greater control over the styles of your html by only changing the css file. A: (P.S not advertising this and no spam. Click on 'Hate AI' to reach my project) You can do this => <h1><a style="text-decoration: none; color: inherit;" href="https://obnoxiousnerd.github.io/hate-ai">Hate AI</a></h1> <p>A personal assistant that hates you but still helps you.</p> The logic here was adding a style to the a tag which contains the following:- text-decoration: none; color: inherit; text-decoration for removing the underline under the text. color: inherit for removing the usual purple color of links. A: Sure - just adjust the CSS for 'a' elements on the page. A: Just a simple snippit to show some size/coloring possibilities, to make your link fit thematically when the rest of your text a bit better. <a href="https://www.website.com/">Wow, Look at this website! It's called Website! It's a shame that this link looks horrible, though!</a> <h2><a style="color: #A52A2A;; text-decoration: none;" href="https://www.website.com/">Oh, boy! You can now click here to visit Website's website without the link looking bad!</a></h2> <h2><a style="color: #A52A2A;; text-decoration: none;" href="https://www.bing.com/">Uh oh, the Website website is broken! Visit the pinnacle of innovation, Bing, instead!</a></h2>
{ "language": "en", "url": "https://stackoverflow.com/questions/7636105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Installing memcached for a django project From the django docs: After installing Memcached itself, you'll need to install a memcached binding. There are several python memcached bindings available; the two most common are python-memcached and pylibmc. The pylibmc docs have their own requirements: -libmemcached 0.32 or later (last test with 0.51) -zlib (required for compression support) -libsasl2 (required for authentication support) So it seems to me that I need to do the following: -install memcached -install libmemcached -install zlib -install libsas12 -install pylibmc How/where can I do this? I've been used to just pip installing whatever I need but I can't even tell which of these are python packages. Are these bundled together anywhere? A: Just do pip install python-memcached and you should be good. As for installing memcached itself, it depends on the platform you are on. * *Windows - http://pureform.wordpress.com/2008/01/10/installing-memcache-on-windows-for-php/ *OS X - brew install memcached *Debian/Ubuntu - sudo apt-get install memcached On OS X/Linux, just run memcached in the command line. A: Detailed explanation here http://ilian.i-n-i.org/caching-websites-with-django-and-memcached/ The link above includes explanations for how to install Memcached on Ubuntu, how to configure it as cache engine in your Django project and how to use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: ssh gateway in python - colors available? I am using python bindings for libssh2 to connect to SSH2 server programmatically. The received output should be forwarded to a remote server and displayed there. The code below works correctly, but it displays the result in monochrome. How can I display the colors or at least get the VT100 terminal control escape sequences, so I can replace them with HTML tags? import socket import libssh2 import os sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 22)) session = libssh2.Session() session.startup(sock) session.userauth_password("test", "test") channel = session.channel() channel.execute('ls -al /') stdout = [] stderr = [] while not channel.eof: data = channel.read(1024) if data: stdout.append(data) data = channel.read(1024, libssh2.STDERR) if data: stderr.append(data) print (''.join(stdout)) print (''.join(stderr)) I can use another ssh library if needed, I just liked the simplicity and documentation of libssh2 bindings... I am open for other suggestions. A: You can look into the paramiko python library. A good blog post going over details, with links to various python info is here. I'm not sure how paramiko would handle the control codes, but in theory, it will at least allow you to see them in its return data. If you check the section of the docs dealing with invoking a shell, it allows you to set the terminal emulation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change font size in form combo box in MS Excel I need to change the font size in an Excel combo box because the default font size is way too small. Is there a way to do this? This is the code I use for my macro: Option Explicit Sub DropDown4_Change() Dim comboValue As String Dim Key1ColumnIndex As Integer Dim Key2ColumnIndex As Integer Dim Index As Integer Dim comboName As String Dim comboName2 As String Dim comboID As Integer 'You can get the name by doing something like this in the immediate window: "? Sheet1.Shapes(1).OLEFormat.Object.Name" For Index = 1 To ActiveSheet.Shapes.Count comboName = ActiveSheet.Shapes(Index).OLEFormat.Object.Name If InStr(comboName, "Drop") > 0 Then 'MsgBox InStr(comboName, "Drop") comboName2 = comboName comboID = Index End If Next comboValue = ActiveSheet.Shapes(comboID).ControlFormat.List(ActiveSheet.Shapes(comboID).ControlFormat.ListIndex) Select Case comboValue Case "By Keyphrase" Key1ColumnIndex = 18 Key2ColumnIndex = 19 Case "By Region" Key1ColumnIndex = 19 Key2ColumnIndex = 18 Case "Default" Key1ColumnIndex = 1 Key2ColumnIndex = 1 End Select Range("DataValues").sort Key1:=Range("DataValues").Cells(1, Key1ColumnIndex), _ Order1:=xlAscending, Header:=xlNo, DataOption1:=xlSortNormal, _ Key2:=Range("DataValues").Cells(1, Key2ColumnIndex), order2:=xlAscending End Sub Thank you. A: It can't be done There's no formatting the font size of a forms dropdown - even programatically. If it's an absolute requirement, you'll have to switch this to an activeX control. A: As said by @Alain you simply can't in a clean way, or you have to use an activeX control. But here there's also a workaround. With programming, you can temporarily zoom the worksheet, to make the data validation font size appear larger. Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Address = "$A$2" Then ActiveWindow.Zoom = 120 Else ActiveWindow.Zoom = 100 End If End Sub Credits and more details: https://www.contextures.com/xldataval08.html#zoommacro
{ "language": "en", "url": "https://stackoverflow.com/questions/7636115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linux kernel: skbuff structure - routing information.. I have a doubt, pls clarify. Suppose I have a System connected like the below, A -> B -> C -> D I need to send a packet from A to D, so when a packet moves out of A, it should update the routing information somewhere in the packet or in the skbuff so that packet is routed correctly via B, so that it reaches the destination. Pls let me know where it is updated in the packet means which header or which parameter in the skbuff.. Thnx in advance.. A: From your view, you only need the target address D and the first gateway (or router) B. You don't make any modification in the packet, this is done in the router(s). C or any other routers on the way to D are transparent for you. A: Normally this happens by updating the source and destination mac address of the packet. This would be found in the ethernet header of the packet (assuming it's travelling over ethernet). In normal UDP or TCP routing, you can do this completely in userspace by modifying the routing tables. Are you implementing a custom internet protocol? Otherwise, it's unlikely that a custom kernel module / patch is the right place for this. A: When the packet is being sent from A to D in this network, A -> B -> C -> D, application on A has a socket to application on D. The IP at A needs to find the next hop through routing, which would be B in this case. This information can be cached in socket as well(as in some versions of Linux, in the socket->sock->dst_cache field). The IP datagram always has destination IP as IP of D. So, B forwards it to C based on routing table and similarly C to D. Does this answer your question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL query BOOLEAN MODE Case Sensitivity My search is case sensitive, but I want it to be case insensitive. In MySQL I have my database and table set to utf8_general_ci. The search is still case sensitive. I have been doing some research and it seems the reason behind this is BOOLEAN MODE in my query. Is there a way to make it case insensitive? so no matter how I type any word with any sensitivity it will always bring it up in the search result? SELECT s_cost_sheet.partnumber, s_cost_sheet.description, s_cost_sheet.price, s_cost_sheet.notes FROM s_cost_sheet WHERE MATCH ( partnumber, description, price, notes ) AGAINST('%".$search."%' IN BOOLEAN MODE) ORDER BY partnumber, description, price, notes ASC"; I have tested the search in phpMyAdmin and it works no matter how a type the word plate, it can be Plate, PLATE, plaTE. It all works fine, so it must be something within this that is causing the issue. A: If one of the columns is of type int or numeric then the search becomes case sensitive. Also there's no need to use % in the searched string A: TRY changing your table and column to utf8_general_ci and you don't have to use % wildcard with FULL TEXT Search RECOMMENDATIONS Also avoid using a lot of columns with ORDER BY clause if you need quicker results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jquery repeat animation This code seems to break the remainder of my code? function sam() { $("#animate").children("#box") .animate({ left: '+=1100'},8000, 'linear', function() { $("#animate").children("#box").css("left", "0"); sam(); }); } setInterval(sam()); Sorry about the short response but I kept getting blocked by a stupid quality message A: Try to change setInterval(sam()); to setInterval(function(){ sam() }, 1000); which will trigger sam() every second.Your usage of setInterval is wrong Also, delete sam() call in sam() function. So final code: function sam() { $("#animate").children("#box") .animate({ left: '+=1100'},8000, 'linear', function() { $("#animate").children("#box").css("left", "0"); }); } setInterval(function(){ sam() }, 1000); A: setInterval needs a second parameter for how often you are going to run the code sam(). but I dont know if you want that, it seems to do that anyway. function sam() { $("#animate").children("#box") .animate({ left: '+=1100'},8000, 'linear', function() { $("#animate").children("#box").css("left", "0"); sam(); }); } sam(); should be enought if you want to repeat the animation over and over again, or use setTimeout instead of setInterval. Set interval will relaunch the code, even if the first run isnt finished, your animation takes 8 seconds, if you say run sam() every 2 second for example you will get a very, very bad result because the codes takes more then 2 seconds to run and you also said that it should rerun itself. I would not use setInterval at all. Demo: http://jsfiddle.net/voigtan/tG7Gm/2/ A: You could use the finished-animation callback to start a new animation. Could you clarify if you want the animation to start when the first one is finished, or just have endless animations on top of each other? A: Remove the () from where you're passing sam as the callback. You want to pass the function, not the result of it. var sam = function() { // Changed this to show functions are variables $("#animate").children("#box") .animate({ left: '+=1100'},8000, 'linear', function() { // Not sure about += $("#animate").children("#box").css("left", "0"); sam; // Pass the variable, not the result of the function }); }; sam(); // Call the function the first time. However, I notice that #box is an id. So I've extrapolated what I think you want to do and come up with this demo: var sam = function() { // Changed this to show functions are variables $("#box").animate({left: $("#animate").width() + 'px'}, 1000, 'linear') .animate({left: '-' + $("#box").width() + 'px'}, 0, 'linear', sam); }; sam(); // Call the function the first time. #animate { position: relative; width: 200px; height: 200px; background-color: red; overflow: hidden; } #box { position: absolute; width: 50px; height: 50px; left: 0; top: 0; background-color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="animate"> <div id="box"></div> </div> Or JsFiddle if you prefer: http://jsfiddle.net/Gisleburt/tn8j7w8p/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7636133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unable to instantiate Action, com.hcl.hips.action.KaList, Possible Duplicate: Unable to instantiate Action, com.hcl.hips.action.KAListproduct, defined for 'KAListproduct' in namespace '/'com.hcl.hips.action.KAListproduct Unable to instantiate Action, com.hcl.hips.action.KaList, defined for 'KaList' in namespace '/'Error creating bean with name 'com.hcl.hips.action.KaList': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.hcl.hips.action.KaList]: Constructor threw exception; nested exception is java.lang.NullPointerException at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:306) at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:387) at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:186) at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:458) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at net.sf.j2ep.ProxyFilter.doFilter(ProxyFilter.java:91) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.hcl.hips.action.LoginFilter.doFilter(LoginFilter.java:110) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859) at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:574) at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1527) at java.lang.Thread.run(Thread.java:619) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.hcl.hips.action.KaList': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.hcl.hips.action.KaList]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:254) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:925) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowire(AbstractAutowireCapableBeanFactory.java:308) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:154) at com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:129) at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139) at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109) at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:287) ... 26 more Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.hcl.hips.action.KaList]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:115) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:248) ... 33 more Caused by: java.lang.NullPointerException at com.hcl.hips.action.KaList.(KaList.java:16) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:100) ... 35 more PLease help me in this Error.. Thanks in Advance.. A: your error is described in the stack trace Could not instantiate bean class [com.hcl.hips.action.KaList]: Constructor threw exception; nested exception is java.lang.NullPointerException You constructor is throwing exception when the container is trying to create it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Drag from NSOutlineView never accepted I'm trying to implement dragging from an NSOutlineView and although the drag starts OK it is never accepted by another app. The pertinent code is: - (BOOL) outlineView:(NSOutlineView*)pOutlineView writeItems:(NSArray*)pItems toPasteboard:(NSPasteboard*)pBoard { CItem* theItem = [pItems objectAtIndex:0]; BOOL canDrag = ([theItem subItems] == 0); if (canDrag) { [pBoard clearContents]; [pBoard writeObjects:[NSArray arrayWithObject:[theItem name]]]; } return canDrag; } [theItem name] returns an NSString*. At some point I'll want to add more to the pasteboard contents but until I can get it to work with a simple string there doesn't seem to be much point in getting into that. The drag looks fine but the receiver doesn't show any highlighting when being hovered over and the drag image 'flies back' when released. Any help gratefully received! Rev. Andy A: Turns out that draggingSourceOperationMaskForLocal: is never called for the delegate of NSOutlineView (or NSTableView possibly) so that drag operation is never allowed. Subclassing NSOutlineView just to override this method fixes everything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access list items from JavaScript I want to access model items by index from JavaScript into a Play Framework template: <script type="text/javascript" charset="utf-8"> window.onload = function() { var cl = ${colors.size()}; int i = 0; for (i=0;i<cl;i++) { labels = labels + "${colors.name.get(i).escapeJavaScript().raw()}"; } } </script> My problem is that this loop throws an exception: IndexOutOfBoundsException : Index: 12, Size: 4 Nota 0: model = Color. Nota 1: the size is 4. Nota 2: if I test with a fixed number instead of variable i it is ok, but this is not what I need. Cannot get why it does not work. A: You try to use Groovy inside a Javascript loop which is wrong. Remember your Groovy code (inside ${}) is evaluated by the Play templating on the server side and result of an HTML page returned to the client, and the Javascript is evaluated on client side (by the browser, not on your server). maybe you want to do something like : <script type="text/javascript" charset="utf-8"> window.onload = function() { labels = [#{list colors.name}"${_.escapeJavaScript().raw()}"#{if !_isLast},#{/if}#{/list}]; } which is still dangerous if you don't understand what it does, prefer using a simple AJAX request and the renderJSON method for dynamic loadings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing array post values jquery ajax to php I spend my all day in searching of this solutions but i didn't find any proper way to do this. i am beginner with jquery need code help. i have a dynamic table in a form which will send bed details to php. its diagram is like this. numbers below user choose from select dropdown box. Rooms | King Bed | Queen Bed | Child Bed -------------------------------------------------- Room Name | 1 | 0 | 0 Room Name2| 0 | 1 | 0 Room Name3| 0 | 0 | 2 its not a single form many of other inputs are before it and after it. so i dont think so we can use serialize() with jquery etc.. the thing which i really hate in jquery ajax is we can't pass $_POST['txt'] array of form to php. need you help with how can i pass each room detail to php. waiting for positive response. thank you A: There's no reason you can't post arrays through ajax. You just can't use a native object, pass a string instead. $.post('mypage.php', 'txt[]=a&txt[]=b&txt=c') More info at http://api.jquery.com/jQuery.post/ NOTE: You may need to escape the [ and ] which become %5B and %5D, respectively.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differentiate single Dialogs with DialogInterface.OnClickListener We have two AlertDialog objects AlertDialog dialog1, dialog2; both dialogs are created via AlertDialog.Builder. How can we recognize which dialog is source of event in DialogInterface.OnClickListener ? with single dialog we can do this: AlertDialogInstance.setOnClickListener(myListener); //myListener public void onClick(DialogInterface arg0, int arg1) { switch (arg1) { case AlertDialog.BUTTON_NEGATIVE: // do something break; case AlertDialog.BUTTON_POSITIVE: // do something break; case AlertDialog.BUTTON_NEUTRAL: // do something break; } } how to modify this switch logic to handle multiple dialogs? (Or if there is better system to handle dialogs, other than inline button callbacks, what is it?) A: I'll recommend you to put needed param in the custom listener. private class CustomOnClickListener implements OnClickListener { private int id; public CustomOnClickListener(int id) { this.id = id; } public void onClick(DialogInterface dialog, int which) { //check id and which } } Then, when you add onClickListeners to dialogs, you just provide an id to listener. A: private AlertDialog dialog1; private AlertDialog dialog1; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); dialog1 = new AlertDialog.Builder(this).setTitle("dialog1").create(); dialog1.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", this); dialog2 = new AlertDialog.Builder(this).setTitle("dialog2").create(); dialog2.setButton(AlertDialog.BUTTON_NEGATIVE, "NO", this); } @Override public void onClick(final DialogInterface dialog, final int which) { if (dialog == dialog1) { if (which == AlertDialog.BUTTON_POSITIVE) { // } else if (which == AlertDialog.BUTTON_NEGATIVE) { // } } else if (dialog == dialog2) { if (which == AlertDialog.BUTTON_POSITIVE) { // } else if (which == AlertDialog.BUTTON_NEGATIVE) { // } } } A: If your dialogs have differentiable content, you can obviously tell the dialog directly by its content: if(which==AlertDialog.BUTTON_NEGATIVE)return; AlertDialog theDialog = (AlertDialog)dialog; if(theDialog.findViewById(R.id.phoneinput)!=null) ...;//handle the phone if(theDialog.findViewById(R.id.emailinput)!=null) ...;//handle the email Of course the solution is NOT universal, but quite handy in some cases.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Ext.NET DateField - formatting reversing itself We have a weird situation where an Ext.NET datefield is 'switching' formats if we input values in a certain style. Specifically, if I input '01/12/09', when I blur the field, it will appear as '12/01/2009'. If I then focus the field and remove the '20' so the format reads '12/01/09' when I blur the field, it will 'switch' and show '01/12/09'. What's odd is that we only see this behaviour on our production environment. I've done all the obvious things like checking the locale/region settings on the production box but haven't yet found anything which circumvents the behaviour. Does anyone have any ideas on places to check next? This is based on Ext.js 3.3.1. Many thanks, Doug A: Here's a simple test I used in an attempt to recreate the problem, although was unable. <%@ Page Language="C#" UICulture="en-GB" %> <%@ Register assembly="Ext.Net" namespace="Ext.Net" tagprefix="ext" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Ext.NET Example</title> </head> <body> <form runat="server"> <ext:ResourceManager runat="server" /> <ext:DateField ID="DateField1" runat="server" /> </form> </body> </html> Which version of Ext.NET are you using 1.0, 1.1 or 1.2? Can you modify the sample above to demonstrate the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What will return this function? (Math.random()) What range of Numbers? Seriously, I got headache trying to figure it out -_- public function gerRandom(i:uint):uint { return Math.round(Math.random()*i); } Whole numbers from 0 to i including? I need these. A kind of a noob question, but whatever :D A: Will return whole number from 0 to i, both inclusive, but not with equal probability. You'll get 0 if Math.random()*i is the interval [0, 0.5), but you get 1 if it's in [0.5, 1.5]. Use Math.floor(Math.random() * (i + 1)) instead. A: An integer between 0 and i (both included) :) * *Math.random() return a value between 0 and 1 *Math.random*i return a number between 0 and i *Math.round(Math.random()*i) returns an integer between 0 and i. A: Math.random() will create a number from 0 to 1 (not including 1). So your code would create a value between 0 and i, with less chance to get 0 and i compared to the other values in the range (it will only round down to 0 on a 0.5 or less, and up to 'i' on a 'i'-0.5 or more). A better way is to use public function getRandom(from:uint, to:uint):uint { return Math.floor(Math.random()*(to-from+1))+from; } (iirc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do server-sent events actually work? So I understand the concept of server-sent events (EventSource): * *A client connects to an endpoint via EventSource *Client just listens to messages sent from the endpoint The thing I'm confused about is how it works on the server. I've had a look at different examples, but the one that comes to mind is Mozilla's: http://hacks.mozilla.org/2011/06/a-wall-powered-by-eventsource-and-server-sent-events/ Now this may be just a bad example, but it kinda makes sense how the server side would work, as I understand it: * *Something changes in a datastore, such as a database *A server-side script polls the datastore every Nth second *If the polling script notices a change, a server-sent event is fired to the clients Does that make sense? Is that really how it works from a barebones perspective? A: The HTML5 doctor site has a great write-up on server-sent events, but I'll try to provide a (reasonably) short summary here as well. Server-sent events are, at its core, a long running http connection, a special mime type (text/event-stream) and a user agent that provides the EventSource API. Together, these make the foundation of a unidirectional connection between a server and a client, where messages can be sent from server to client. On the server side, it's rather simple. All you really need to do is set the following http headers: Content-Type: text/event-stream Cache-Control: no-cache Connection: keep-alive Be sure to respond with the code 200 and not 204 or any other code, as this will cause compliant user agents to disconnect. Also, make sure to not end the connection on the server side. You are now free to start pushing messages down that connection. In nodejs (using express), this might look something like the following: app.get("/my-stream", function(req, res) { res.status(200) .set({ "content-type" : "text/event-stream" , "cache-control" : "no-cache" , "connection" : "keep-alive" }) res.write("data: Hello, world!\n\n") }) On the client, you just use the EventSource API, as you noted: var source = new EventSource("/my-stream") source.addEventListener("message", function(message) { console.log(message.data) }) And that's it, basically. Now, in practice, what actually happens here is that the connection is kept alive by the server and the client by means of a mutual contract. The server will keep the connection alive for as long as it sees fit. Should it want to, it may terminate the connection and respond with a 204 No Content next time the client tries to connect. This will cause the client to stop trying to reconnect. I'm not sure if there's a way to end the connection in a way that the client is told not to reconnect at all, thereby skipping the client trying to reconnect once. As mentioned client will keep the connection alive as well, and try to reconnect if it is dropped. The algorithm to reconnect is specified in the spec, and is fairly straight forward. One super important bit that I've so far barely touched on however is the mime type. The mime type defines the format of the message coming down the connecting. Note however that it doesn't dictate the format of the contents of the messages, just the structure of the messages themselves. The mime type is extremely straight forward. Messages are essentially key/value pairs of information. The key must be one of a predefined set: * *id - the id of the message *data - the actual data *event - the event type *retry - milleseconds the user agent should wait before retrying a failed connection Any other keys should be ignored. Messages are then delimited by the use of two newline characters: \n\n The following is a valid message: (last new line characters added for verbosity) data: Hello, world! \n The client will see this as: Hello, world!. As is this: data: Hello, data: world! \n The client will see this as: Hello,\nworld!. That pretty much sums up what server-sent events are: a long running non-cached http connection, a mime type and a simple javascript API. For more information, I strongly suggest reading the specification. It's small and describes things very well (although the requirements of the server side could possibly be summarized a bit better.) I highly suggest reading it for the expected behavior with certain http status codes, for instance. A: You also need to make sure to call res.flushHeaders(), otherwise Node.js won't send the HTTP headers until you call res.end(). See this tutorial for a complete example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Function overload resolution trouble Over the weekend, I had specific problem with function overload resolution that I can't seem to solve. The code below is a distillation of the problem: #include <iostream> using namespace std; template<typename T> void f(const T& t) { cout << "In template function." << endl; } class C { public: void f() { cout << "In class function." << endl; } void g() { int i=0; f(i); } void h() { int i=0; f<int>(i); } void i() { extern void f(int); int i=0; f(i); } }; int main() { cout << "Test" << endl; C c; c.i(); return 0; } 1) C::g won't compile because the compiler won't try the template. It just complains that there is no C::f to match. 2) C::h won't compile for no reason that is obvious to me. The message is "expected primary-expression before 'int'" 3) C::i will compile, but (after commenting out g and h) it won't link to anything. I think I understand this: the extern is forcing the linker to look into another compilation unit, but any template definition would be in this compilation unit. I would appreciate any clarification on the reasons for 1 and 2. Also, ultimately, can someone suggest a way to get this to work that doesn't involve creating another compilation unit? A: Likely it is finding C::f instead of global f. Use ::f<int>(i). A: Look here: http://ideone.com/zs9Ar Output: Test In template function. #include <iostream> using namespace std; template<typename T> void f(const T& t) { cout << "In template function." << endl; } class C { public: void f() { cout << "In class function." << endl; } void g() { using ::f; int i=0; f(i); } }; int main() { cout << "Test" << endl; C c; c.g(); return 0; } A: Functions with the same name will hide other functions of the same name when they have different scopes, even if they have different signatures. Instead of using a template for the first f, you could just do f(int) and the result would be the same for #1(the C::f() hides the ::f(int)). One solution is to add "::" before the name to force the global namespace. Another solution would be to change the names. A: Names in a smaller scope hide names in an outer scope. Use ::f to indicate global namespace. In i() you declare a function called f, but indeed there is no definition (it is not the same as the template), so you get a linker error. A: C++ is somewhat "greedy" when trying to find functions. As soon as it finds a matching function name in the current scope (in this case, class C) it stops and then tries to match the parameters. If the parameters don't match, it won't try additional scopes. I assume this was to keep compiler writers sane. That's why g doesn't compile. The same thing applies to h. It sees a non-template function f in the class scope and gets confused. It thinks you're trying to do a < comparison against the function C::f. In both cases you can use ::f to qualify the name to the global scope.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: jQuery 'this' legacy scoping I'm trying to back-port a slideshow I wrote in jQuery 1.6 to work in Drupal, which you may or may not know is "locked" to jQuery 1.3 at present (I know, it's retarded). I'm having a problem with scope though, as jQuery 1.3's $(this) model isn't as robust or helpful as it is in more modern releases. Here's the code that's breaking: var $controls = $('a.controls', $frame); $controls.click( function() { var $clicked = $(this); // ... } The a.controls expression results in a collection of two objects within $controls as expected. But when jQuery 1.3 encouters the $(this) assignment, it's throwing the following error: this[0].ownerDocument is null Does anyone know why it's doing this, and how I can fix or work around it? A: That’s probably not where the error is happening, the this context works the same for event callbacks in 1.3 as in the latest version. Example: http://jsfiddle.net/hPfZH/2/ * *Are you sure the $frame context is correct? *Are you using inline click events on the $controls that can add conflict? A: The only way I think this is going to get done is with a small hack of the jquery_update module. You need to replace the jquery.min.js (or jquery.js if you're not using the minimised version) file in sites/all/modules/jquery_update/replace with the latest jQuery version, then make the alterations to the jquery.module file (around line 59): function jquery_update_preprocess_page(&$variables) { // Only do this for pages that have JavaScript on them. if (!empty($variables['scripts'])) { // ADD THESE TWO LINES BEFORE THE REST OF THE CODE if (preg_match('/^\/admin[\/]*.*/', $_SERVER['REQUEST_URI'])) { return; } if (preg_match('/^\/batch[\/]*.*/', $_SERVER['REQUEST_URI'])) { return; } That will basically tell jquery_update to only replace the javascript on non-admin and non-batch pages, which should serve your purpose. There may be other paths you need to add to that check depending on your needs. I haven't tested this but in theory it will work, unfortunately I can't comment as to whether AHAH (Drupal's lame attempt at an AJAX framework) will work with the later version of jQuery on non-admin pages. Hope you get this sorted it's a very annoying problem :-) A: This may not answer the question but may help you with the problem. With drupal module jquery update you can choose the jquery version in drupal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to identify Delphi StringList object is created or not I have declared variable of TStringList in private section. In a button click event I want to access that TStringList object. sVariable:= TStringList.Create; sVariable.add('Test1'); Now whenever i click on that button each time its newly created and memory is allocated to that variable. Is there any property/function using which we can determine object is created for that variable or not and it will not give the access violation error also? A: Another way to approach it, expanding on David's answer, is through a property with a read method. TMyForm = class (TForm) private FStrList : TStringList; public property StrList : TStringList read GetStrList; destructor Destroy; override; end; implementation function TMyForm.GetStrList : TStringList; begin if not Assigned(FStrList) then FStrList := TStringList.Create; Result := FStrList; end; destructor TMyForm.Destroy; begin FStrList.Free; inherited; end; Edit: Added the Free call in an overridden destructor. A: if not Assigned(sVariable) then sVariable:= TStringList.Create; sVariable.add('Test1');
{ "language": "en", "url": "https://stackoverflow.com/questions/7636172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MATLAB does not prompt me when saving a file that is being debugged When saving a file that is being debugged, MATLAB would typically ask me if I wanted to proceed and warn me that saving the file to disk would exit the debug mode. Recently MATLAB stopped showing me this warning. At the moment, if I type Ctrl-S to save the current file, MATLAB exits debug mode automatically without asking. Is there an option that reverts this behavior? A: Works for me so the behaviour hasn't changed. I think that you selected the "Don't show this dialog again" option. Look under "General\Confirmation Dialogs" in the preferences. A: Turn it back on by: Preferences > General > Confirmation Dialogs > Prompt to exit debug mode when saving file
{ "language": "en", "url": "https://stackoverflow.com/questions/7636176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the best API to combine C++11 async/futures with Windows asynchronous IO? Especially the upcoming Windows 8 (with Metro) will require that any IO is programmed asynchronously. In C#/.Net there seems to be special await and such like constructs for that and the JavaScript API will have its own mechanism for that to work. What will be the C++11-integration for that? Is the a concise example (eg. reading an image from a file for display?) for modern (or upcoming) Windows? If it's using C++11 features I would expect that async or future is involved? A: The Tips and tricks for developing Metro style apps using C++ presentation covers this at 59:13. The raw interface uses callback objects. In practice, people are likely to use the simplified interface offered by PPL. A: Windows 8 async will probably be done through PPL. You can read more about that here. From my understanding, Windows 8 and PPL uses task-based scheduling and cooperative blocking. While std::async and std::future use thread based scheduling and preemptive blocking. Thus they are not compatible. A: This is what you want: http://code.msdn.microsoft.com/windowsapps/Windows-8-Asynchronous-08009a0d
{ "language": "en", "url": "https://stackoverflow.com/questions/7636177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Trouble popping a view within a tab bar and nab bar I have a UITabBarController, which is the second item in a UINavigationBarController. Within the UITabBarController are a couple of views, one of which is a UIViewController subclass called AccountViewController. Got that? Login View Controller -> UIViewController + UITabBarController - > Account View Tab -> Button I want to use a button - Logout - to pop back to the Login view. How would I do that? A: Assuming you are creating the UITabBarController within one of the UIViewControllers which are part of the string of view controllers within the UINavigationController where you have done something similar to this: UITabBarController *mytabs = [[UITabBarController alloc] init]; [self.view addSubview:mytabs.view]; mytabs.delegate = self; // This is key to getting back your UINavigationController You can call this from within one of the UIViewControllers that are added to your mytabs.viewControllers array like so: [[(UIViewController *)self.tabBarController.delegate navigationController] popViewControllerAnimated:YES]; You can also specify if you want it to go to a specific viewController index in the UINavigationController stack ( just in case your Login viewController isn't the next one down or the root view controller ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7636183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: typo3 - building a simple functionality I am building a fairly simple website based on typo3. I'm new to the CMS but I've read almost everything I could find about it - tutorials, wikis, documentation. I'm stuck with designing a functionality for the administrator to be able to create records with predefined attributes (category, date, info, image, ...) and those records to be listed in a table on the front end with a "View detailed" link on each row. Will I need to develop a complete extension for this? From where the administrator will enter these records? How can I iterate them on the front end? I apologize in advance if my question is too broad. A: The Kickstarter extension provides a full stop solution for your needs. There is a good set of, if slightly outdated, screencasts explaining how to use this extension to create your custom record types and associated front-end views.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: accelerometer sensor avaiblable in locked screen / screen off mode? it seems that there is a bug in froyo with respect to the onSensorChanged method when the phone goes to lock screen mode, i.e. there are no values coming from the accelerometer. I read about this issue in this topic Now, the topic does mention a workaround which involves keeping the screen on, although dimmed, but it seems to me that this would drain the battery. In my application I don't need the screen to be visible at all (brightness can be zero), but it should respond to touch. The application should also respond to shaking and movement. Would this still drain the battery fast? EDIT: Is there a difference between screen lock and screen off?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Validation problems when using jQuery and Ajax to post back form in partial view I am having some challenges with validation in my ASP.NET MVC3 project when using jQuery and AJAX to post back data from a partial view. Adding validation to the NoteText field within my partial view results in "$('#noteAdd').submit" event failing to trigger and my form posting directly to the controller. Removing the validation results in the expected behaviour. I was hoping somebody might be able to shed some light over what's happening here, why it's happening and my provide some advice on how to resolve the issue and I've included my partial, controller, JS and view below. My Partial [Bind(Include = "NoteId,NoteText,Date,SourceId,Username,TypeId,ItemId,Processed")] [MetadataType(typeof(NotePartial_Validation))] public class NotePartial { public int NoteId { get; set; } public string NoteText { get; set; } public DateTime? Date { get; set; } public int? Source { get; set; } public string Username { get; set; } public int ItemId { get; set; } public int TypeId { get; set; } public IEnumerable<NotePartial> ExistingNotes { get; set; } } public class NotePartial_Validation { [HiddenInput(DisplayValue = false)] public int NoteID { get; set; } [Required] public string NoteText { get; set; } [HiddenInput(DisplayValue = false)] public int ItemId { get; set; } [HiddenInput(DisplayValue = false)] public int TypeId { get; set; } } } My Controller public class NoteController : Controller { [HttpPost] public ActionResult Create(NotePartial model) { try { NoteMethods.CreateNote(model.NoteText, SessionManager.Current.ActiveUser.Username, model.ItemId, SessionManager.Current.ActiveUser.Company); return Json(new { s = "Success" }); } catch (NoPermissionException) { return Json(new { s = "No permission" }); } } } My View @model EF.NotePartial @{using (Html.BeginForm("Create", "Note", new { area = "" }, FormMethod.Post, new { id = "noteAdd" })) { @Html.TextAreaFor(m => m.NoteText, new { @class = "note-input" }) //note-input @Html.ValidationMessageFor(model => model.NoteText) <input type="submit" value="Send" /> }} <script type="text/javascript"> $(function () { $('#noteAdd').submit(function () { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), error: function (xhr, ajaxOptions, thrownError) { alert('An error occured when processing this request:\r\n\r\n' + thrownError); }, success: function (result) { alert(result.s); } }); // it is important to return false in order to // cancel the default submission of the form // and perform the AJAX call return false; }); }); A: put partial keyword on your class : public partial class NotePartial
{ "language": "en", "url": "https://stackoverflow.com/questions/7636193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use sass-rails helpers in Ruby? From the Github page it would seem that one can use the Sass helpers (asset_path, asset_url, image_path etc.) in Ruby but I can't figure out how. I need to set the default_url for a Paperclip attachment and want to use one of my assets from the asset pipeline for that. A: You can use the sass helpers in SCSS files, but you cannot use them elsewhere. In those cases you need to use the regular asset_path and image_tag helpers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Minimum and maximum length in a regular expression I'm using the following regular expression to validate emails: ^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ Now I want to modify this regular expression to validate the email length using {5,100}. How can I do that? A: ^(?=.{5,100}$)\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ I'm using the zero-width lookahead. It won't consume characters, so you can then recheck them with your expression. A: Be careful. This is a relatively weak expression and matches even user@server.com.net.org. Email regexes were already discussed in many other questions like this one. Checking for the length of a string can generally be done within the language/tool you're using. This might be even faster in some cases. As an example (in Perl): my $len = length $str; if ($len < 5 || $len > 100) { # Something is wrong }
{ "language": "en", "url": "https://stackoverflow.com/questions/7636207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why System.out.println() not working in Netbeans 6.8? I am facing one problem in Netbeans 6.8, the output window of Netbeans not showing the output from project which i used as system.out.println(). How to solve this issue with Netbeans 6.8? A: * *Ensure that you are running the right project, many a times we have multiple projects open and main project is some different project *Ensure that the code block you want to get executed is reached by the Java Virtual Machine, it may happen that the code part if not reached due to some earlier condition *Try posting example of your code here to get more specific answers A: that's because you have used lowercase 's' in the System.out.println()... ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash size on publishing post by Graph API I use Facebook Graph API to post on user's wall. I also attach Flash application ("source" parameter) to it. $data = array( 'name' => 'Test name', 'message' => 'Custom message', 'picture' => 'http://www.example.com/image.png', 'link' => 'http://www.example.com', 'description' => 'Description of the message', 'source' => 'http://www.example.com/flash.swf', 'access_token' => '... token_here ...', 'method' => 'post' ); $ret = file_get_contents('https://graph.facebook.com/me/feed?'.http_build_query($data)); The problem that i can't set flash size. For example if use REST API, then you can define attached flash size by "expanded_width" and "expanded_height" parameters. A few month ago when i tried to publish such post i saw that Facebook set flash size to 398x260, but today when i tried it again, i saw that Facebook set size to 398x224. 1) Does someone know if there is some way to define flash size in Graph API, like in REST API? 2) Is there some official documentation that provide default size of post attachment (source)?
{ "language": "en", "url": "https://stackoverflow.com/questions/7636218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: extra css is not loaded. any suggestions? I've added the following to my <head>: <link rel="stylesheet" type="text/css" media="all and (min-width: 481px) and (max-width: 1024px)" href="<?php bloginfo('template_directory'); ?>/css/tablet.css" />` For the main page which is header.php, it is working fine. But if I go to lets say: http://mysyte.com/products-page/checkout/ after inspecting with firebug I can see that the browser didnt even loaded this file even if I assigned a lot of properties for the page in this file (tablet.css). What can you suggest, where to look for the problem? Thanks! P.S. platform - wordpress and ecommerce wp plugin. A: Have you tried echoing the bloginfo function such as... <link rel="stylesheet" type="text/css" media="all and (min-width: 481px) and (max-width: 1024px)" href="<?php echo bloginfo('template_directory'); ?>/css/tablet.css" />`
{ "language": "en", "url": "https://stackoverflow.com/questions/7636221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Please assist me with this simple script I am new to JavaScript and would like to ask for some help with my simple script. What I am trying to do is to retrieve and display the values of all list item elements in the unordered list with the help of the (for) loop. I was able to get the script display all list items in the alert window one by one. But the problem is that I need values of all list elements displayed in a table row way. Like this: Monday Tuesday Wednesday ....... Here is what I have in my script: <script language="JavaScript"> <!-- function process() { a = document.getElementsByTagName('li') for (i = 0; i < a.length; i++) { alert(a[i].childNodes[0].nodeValue); } } //--> </script> And here is HTML code: <body> <ul> <li>Monday</li> <li>Tuesday</li> <li>Wednesday</li> </ul> <input type="button" value="Submit" onclick="process()" /> </body> If that's possible at all would anyone please also explain where I am wrong in my script? Why all 3 list item values can't be shown in the alert window at once? Thanks a lot! A: First, create a string variable: var all_at_once = "". Then, add the contents of the nodeValue. Finally, alert this variable: function process(){ var a = document.getElementsByTagName('li') var all_at_once = ""; for(i=0;i<a.length;i++){ all_at_once += a[i].childNodes[0].nodeValue + " "; } alert(all_at_once); } A: The alert shows repeatedly because that is what a for loop does... it loops! The loop will iterate over the array of elements returned by getElementsByTagName, executing the loop body once for each element in that array. If you wanted to display one alert, an option would be to build up a string containing the appropriate text, and alert it afterwards: var yourString = ""; for(i=0;i<a.length;i++){ yourString += a[i].childNodes[0].nodeValue; } alert(yourString); Some other notes on your code... you should almost always declare variables with the var keyword to prevent them leaking into the global scope. You should also always end lines with semi-colons: function process(){ var a = document.getElementsByTagName('li'), yourString = ""; for(i=0;i<a.length;i++){ yourString += a[i].childNodes[0].nodeValue; } alert(yourString); } A: <script language="JavaScript"> <!-- function process(){ var data = ''; a=document.getElementsByTagName('li') for(i=0;i<a.length;i++){ data = data + '\n' +(a[i].childNodes[0].nodeValue); } alert(data); } //--> </script> You need to call alert only once if you need 1 popup with all the text. A: function process() { var a = getElementsByTagName('li'), text = ''; for( i = 0; i < a.length; i++ ) { text += a[i].childNodes[0].nodeValue + '\n'; } alert( text ); } A: You can process the days in whatever manner you like by storing them in an array first, and then iterating: var days = new Array(); var a = document.getElementsByTagName('li') for(var i = 0; i < a.length; i++) { days.push(a[i].childNodes[0].nodeValue); } for (i=0; i < days.length; i++) { // process the day } See: http://jsfiddle.net/jkeyes/Cfg4k/ for a working example. A: These few adjustments to your function should produce the result you want. Good luck! What changed: 1) Set up an empty string var 2) Instead of alerting each value, just append them to the string var you created earlier 3) Finally, alert the newly created (concatenated) string! function process() { a = document.getElementsByTagName('li'); var days = new String(""); for (i = 0; i < a.length; i++) { days = days+(a[i].childNodes[0].nodeValue)+"\n"; } alert(days); } Now I see there have been tons of answers since opening this thread... but maybe all the different solutions will help you in different ways.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Writing Javascript to Response.OutputStream Currently, I have a controller action that outputs a PDF (as a Response.OutputStream.Write()) and this is working just as it should. However, I am interested in outputting another script section along with the PDF to "automatically print" (or simply perform a window.print();) on the PDF. Is this possible, or is there another method to solve this issue that I may not be aware of? Controller Action: public ActionResult PrintPDF(string ID) { //Population of Model //Output Result return PdfResult(model); } PDF Result: var buffer = byteArrayStream.toByteArray(); response.OutputStream.Write(buffer, 0, buffer.Length); //Is it possible to output something like the following: response.Output.Write("<script type='text/javascript'>window.print();</script>"); A: You will most likely not be able to mix PDF-data with JavaScript, so what you need to is embed the PDF-file using the <embed>-tag and then use javascript to print whatever is inside the <embed>-tag. Here's some information that someone else got working. Basicly this is the code that is outputted (from the previous source but edited a little bit): <html> <body> <embed id="pdfToPrint" src ="@ViewData.PDFUrl" width="550" height="550" name="whatever"> <script> var x = document.getElementById("pdfToPrint"); x.click(); x.setActive(); x.focus(); x.print(); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7636225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ class operator overloading It's possible to overload the not operator for a class: class TestA { public: bool Test; const bool operator!(){return !Test;} }; So that... TestA A; A.Test = false; if(!TestA){ //etc } ...can work. However, how does the following work? if(TestA) //Does this have to be overloaded too, or is it the not operator inverted? I will add, having read it, I am slightly confused by the typedef solution that is employed, and I don't fully understand what is occurring, as it seems somewhat obsfucated. Could someone break it down into an understandable format for me? A: You could write an operator bool(). This takes care of coercion to bool, making statements as your above one possible. A: You overload operator void* (like the standard library's iostreams) or use boost's trick of using an "unspecified_bool_type" typedef (safe bool). It does NOT automatically invert your operator!
{ "language": "en", "url": "https://stackoverflow.com/questions/7636226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C++ Interview: vtable for a class with a pure virtual function I was asked this interview question today!! (it was a really awkward telephonic interview..): What is the difference between the vtable for a class with virtual functions and a class with pure virtual functions? Now, I know the C++ standard doesn't specify anything about vtables, or even the existence of a v-table ..however theoretically speaking what would the answer be? I blurted out that the class with a pure virtual function could have a vtable and its vtable entry for the pure virtual function will point to the derived class implementation. Is this assumption correct? I did not get a positive answer from the interviewer. Will a hypothetical compiler create a vtable for a class with only pure virtual functions? What if the class contains pure virtual functions with definitions? (as shown in : http://www.gotw.ca/gotw/031.htm). A: In the case of non-pure virtual functions, each entry in the vtable will refer to the final-overrider or a thunk that adapts the this pointer if needed. In the case of a pure-virtual function, the entry in the vtable usually contains a pointer to a generic function that complains and aborts the program with some sensible message (pure virtual function called within this context or similar error message). Will a hypothetical compiler create a vtable for a class with only pure virtual functions? Yes, it will, the difference will be in the contents stored in the table, not in the shape of the table. In a simplistic approach, a NULL pointer for pure virtual functions, non-NULL for virtual functions. Realistically, a pointer to a generic function that will complain and abort() with usual compilers. What if the class contains pure virtual functions with definitions? This will not affect the vtable. The vtable is only used for dynamic dispatch, and a call will never be dynamically dispatched to the definition of a pure virtual function (i.e. you can only manually dispatch to the pure virtual function by disabling dynamic dispatch qualifying the name of the type: x.base::f() will call base::f even if it is pure-virtual, but x.f() will never be dispatched to base::f if it is pure virtual. A: An implementation can do pretty much anything in such cases, because if your code ends up calling a pure virtual function in a context where dynamic resolution is required, and it would resolve to a pure virtual function, the behavior is undefined. I've seen several different solutions: the compiler inserts the address of a function which terminates with an error message (the preferred solution from a quality of implementation point of view), the compiler inserts a null pointer, or the compiler inserts the address of the function from some derived class. I've also seen cases where the compiler will insert the address of the function if you provide an implementation. The only correct answer to the question is that you can't count on any particular behavior. A: I can tell you that "pure" abstract classes (classes with only pure virtual functions) are used by Microsoft (and MS VC++) for their COM interfaces. Perhaps he was speaking of it. The "internal" representation of a COM is a pointer to a vtable. Pure abstract classes in MS VC++ are implemented in the same way, so you can use them to represent COM objects. Clearly if you class has other virtual functions, you can't simply overwrite its vtable with the COM vtable :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7636230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Show a div with the layout like a dialog I need to format multiple containers (div) in a web page to look like a jquery-ui dialog. The divs should automatically change if I change the theme. So far I'm applying a jquery-ui tab to the div, but this don't have the same title bar and I need to add a lot of html for each div Thanks In Advance A: Just use the same css as jQuery UI and apply it to your divs. Examples: * *http://jsfiddle.net/Fyj7L/ *http://jsfiddle.net/Fyj7L/1/ *http://jsfiddle.net/Fyj7L/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7636231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic monitoring of log file I need to monitor a log file for a pattern. The log file continually gets written by an application. * *The application can add new log statements while my program is reading it. *The log gets rolled over when it’s >200 MB or at end of the day, so my program should handle change in filename dynamically. *If my program crashes for any reason, it has to resume from where it left off. I do not want to re-invent the wheel. I am looking for a Java API. I wrote a program to read file and put in a loop with 30 seconds sleep, but that does not meet all the criteria. A: You might consider looking at apache commons io classes, in particular Tailer/TailerListener classes. See http://www.devdaily.com/java/jwarehouse/commons-io-2.0/src/main/java/org/apache/commons/io/input/Tailer.java.shtml. A: These two API's can be helpful: 1 JxFileWatcher (Official Site) Read here what it is capable of 2 Jnotify JNotify is a java library that allow java application to listen to file system events, such as: * *File created *File modified *File renamed *File deleted A: If you are using Log4j, or can integrate it, it is possible to append log outputs to a convenient object, such as a StringBuffer, as it has been discussed in this related question: Custom logging to gather messages at runtime A: This looks similar: Implementation of Java Tail Essentially you use a BufferedReader. Tracking where you left off will be something you'll have to add, perhaps capture the last line read? That same question references JLogTailer which looks interesting and may do most of what you want already.
{ "language": "en", "url": "https://stackoverflow.com/questions/7636234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }