text
stringlengths
8
267k
meta
dict
Q: Access 2007 VBA - Rename report upon closing it? I have a report that is dynamically generated depending on the button pressed on my main form, in order to change the filter, the query used, etc. I have DoCmd.Rename working to rename the report to the current (dynamic) report title. However, it appears that I cannot rename the report back to a generic name upon closing the report. Using the Report_Close() event doesn't work; Access tells me the report is still open and therefore can't be closed. Using DoCmd.Close doesn't work either; I get Runtime error 2501 (The Close action was cancelled). How can I rename this report after it's closed? A: Are you saying that each time someone changes the settings and opens a report, you want to save that as a new report in Access? I wouldn't recommend this. If the dynamically changed stuff are just things like filter and query, why not always use the same report and set the RecordSource dynamically? EDIT: Okay, now I understand what you actually want to do. You can set the Caption property of the report at runtime in code: Private Sub Report_Open(Cancel As Integer) Me.Caption = "Incidents By Assignee" End Sub You can also pass the text for the caption from your main form to the report: Pass the text from the form in the OpenArgs parameter when opening the report: DoCmd.OpenReport "YourReport", acViewNormal, , , , "Incidents By Assignee" ...and in the report, just set the Caption to OpenArgs if it's not empty: Private Sub Report_Open(Cancel As Integer) If Nz(Me.OpenArgs) > "" Then Me.Caption = Me.OpenArgs End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7560445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Center Text in UITableView.tableHeaderView? I am adding a UILabel to the tableHeaderView but for some reason it is left aligned. self.messageLabel = [[UILabel alloc] initWithFrame:CGRectZero]; [self.messageLabel setText:@"Nothing to display!"]; [self.tableView setTableHeaderView:self.messageLabel]; [self.tableView.tableHeaderView setBackgroundColor:[UIColor blueColor]]; [self.tableView.tableHeaderView setFrame:CGRectMake(320/2, 480/2, 100, 20)]; [self.messageLabel setCenter:self.tableView.tableHeaderView.center]; A: [label setTextAlignment:UITextAlignmentCenter];
{ "language": "en", "url": "https://stackoverflow.com/questions/7560449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find the ajax status with jQuery 1.2.6 I'm using jQuery 1.2.6 (I know it's old, but I don't have a choice) I need to check the status of my ajax calls. I either want to use: statusCode, or I could even use error(jqXHR, textStatus, errorThrown), except that textStatus, errorThrown and statusCode, aren't in my jQuery version. Basically what I have to do, is know if the ajax call was aborted, or had an error for another reason. Any ideas how I can do this? A: you could get the status text from the error callback: $.ajax({ url: "/foo", dataType: "text", error: function(obj){ alert(obj.status + "\n" + obj.statusText); } }); http://jsfiddle.net/jnXQ4/ you can also get it from the complete callback if the request resulted in an error. Edit: the ajax request also returns the XMLHttpRequest which you can then bind events to, though I'm not sure how cross-browser it is. var request = $.ajax(options); request.onabort = function(){ alert('aborted'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Decimals to 2 places for money in Python 3 How do I get my decimals to stay at 2 places for representing money using the decimal module? I've setting the precision, and damn near everything else, and met with failure. A: When working with money you usually want to limit precision as late as possible so things like multiplication don't aggregate rounding errors. In python 2 and 3 you can .quantize() a Decimal to any precision you want: unit_price = decimal.Decimal('8.0107') quantity = decimal.Decimal('0.056') price = unit_price * quantity cents = decimal.Decimal('.01') money = price.quantize(cents, decimal.ROUND_HALF_UP) A: Falsehoods programmers believe about money: * *Monetary values can be stored or represented as a floating point. *All currencies have a decimal precision of 2. *All ISO 4217 defined currencies have a decimal precision. *All currencies are defined in ISO 4217. *Gold is not a currency. *My system will never have to handle obscure currencies with more than 2 decimal places. *Floating point values are OK if the monetary value of transactions is "small". *A system will always handle the same currency (therefore we do not persist the currency, only the monetary value). *Storing monetary values as signed long integers will make them easier to work with, just multiply them by 100 after all arithmetic is done. *Customers will never complain about my rounding methods. *When I convert my application from language X to language Y, I don't have to verify if the rounding behavior is the same. *On exchanging currency A for currency B, the exchange rate becomes irrelevant after the transaction. A: The accepted answer is mostly correct, except for the constant to use for the rounding operation. You should use ROUND_HALF_UP instead of ROUND_05UP for currency operations. According to the docs: decimal.ROUND_HALF_UP     Round to nearest with ties going away from zero. decimal.ROUND_05UP     Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero. Using ROUND_05UP would only round up (for positive numbers) if the number in the hundredths place was a 5 or 0, which isn't correct for currency math. Here are some examples: >>> from decimal import Decimal, ROUND_05UP, ROUND_HALF_UP >>> cents = Decimal('0.01') >>> Decimal('1.995').quantize(cents, ROUND_HALF_UP) Decimal('2.00') # Correct >>> Decimal('1.995').quantize(cents, ROUND_05UP) Decimal('1.99') # Incorrect >>> Decimal('1.001').quantize(cents, ROUND_HALF_UP) Decimal('1.00') # Correct >>> Decimal('1.001').quantize(cents, ROUND_05UP) Decimal('1.01') # Incorrect A: One way to solve this is to store money values in cents as integers, and only convert to decimal representation when printing values. This is called fixed point arithmetic. A: >>> decimal.getcontext().prec = 2 >>> d = decimal.Decimal('2.40') >>> d/17 Decimal('0.14') You just have to set the precision to 2 (the first line) and them everything will use no more than 2 decimal places Just for comparison: >>> 2.4 / 17 0.1411764705882353
{ "language": "en", "url": "https://stackoverflow.com/questions/7560455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Understanding xyplot in R I'm an R newbie and I'm trying to understand the xyplot function in lattice. I have a dataframe: df <- data.frame(Mean=as.vector(abc), Cycle=seq_len(nrow(abc)), Sample=rep(colnames(abc), each=nrow(abc))) and I can plot it using xyplot(Mean ~ Cycle, group=Sample, df, type="b", pch=20, auto.key=list(lines=TRUE, points=FALSE, columns=2), file="abc-quality") My question is, what are Mean and Cycle? Looking at ?xyplot I can see that this is some kind of function and I understand they are coming from the data frame df, but I can't see them with ls() and >Mean gives Error: object 'Mean' not found. I tried to replicate the plot by substituting df[1] and df[2] for Mean and Cycle respectively thinking that these would be equal but that doesn't seem to be the case. Could someone explain what data types these are (objects, variables, etc) and if there is a generic way to access them (like df[1] and df[2])? Thanks! EDIT: xyplot works fine, I'm just trying to understand what Mean and Cycle are in terms of how they relate to df (column labels?) and if there is a way to put them in the xyplot function without referencing them by name, like df[1] instead of Mean. A: These are simply references to columns of df. If you'd like access them by name without mentioning df every time, you could write with(df,{ ...your code goes here... }). The ...your code goes here... block can access the columns as simply Mean and Cycle. A more direct way to get to those columns is df$Mean and df$Cycle. You can also reference them by position as df[,1] and df[,2], but I struggle to see why you would want to do that. The reason your xyplot call works is it that implicitly does the equivalent of with(df), where df is your third argument to xyplot. Many R functions are like this, for example lm(y~x,obs) would also correctly pick up columns x and y from dataframe obs. A: You need to add , data=df to your call to xyplot(): xyplot(Mean ~ Cycle, data=df, # added data= argument group=Sample, type="b", pch=20, auto.key=list(lines=TRUE, points=FALSE, columns=2), file="abc-quality") Alternatively, you can with(df, ....) and place your existing call where I left the four dots.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Opening a new window and waiting for it to close I have a Mac OS X app written in objetive-c Cocoa. You can see most of the code in this previous question. Essentially you click a button on the main window (the app delegate) and it opens another window where the user can enter information. In the following code (that gets called when the user press the button in the app's main window) - (IBAction)OnLaunch:(id)sender { MyClass *controllerWindow = [[MyClass alloc] initWithWindowNibName:@"pop"]; [controllerWindow showWindow:self]; NSLog(@"this is a log line"); } The NSLog line gets printer immediately after I called showWindow. Is there any way to wait until controllerWindow is closed to continue with the NSlog? The reason for this is that the user set's a value on the new window I opened and I need to collect that value on the same OnLaunch so I need to wait. I know that modal windows are bad form in Mac, but I have no control over this feature. I've tried with [NSApp runModalForWindow:[controllerWindow window]]; and then setting the popup window to [[NSApplication sharedApplication] runModalForWindow:popupwin]; and it works but then the focus never gets passed to the main window anymore Thanks! A: If you want the window to be modal for your application, use a sheet: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Sheets/Tasks/UsingCustomSheets.html However, there is no way to suspend execution of a method while the sheet is displayed, this would be tantamount to blocking the current run loop. You would have to break you code into the begin and end methods as described in the linked documentation. Here are the steps you need to follow: * *In TestAppAppDelegate create an NSWindow outlet to hold your sheet and an action to dismiss the sheet *Create a nib with an NSWindow as the root object. I think you already have this in "pop". Set the Visible at Launch option to NO (this is very important) *Set the file's owner of this nib to TestAppAppDelegate and connect the window to your new outlet, and the close button to your new action *In your method to launch the sheet (OnLaunch), use the following code: (ignore this it's to make the code format properly!) if(!self.sheet) [NSBundle loadNibNamed:@"Sheet" owner:self]; [NSApp beginSheet:self.sheet modalForWindow:self.window modalDelegate:self didEndSelector:@selector(didEndSheet:returnCode:contextInfo:) contextInfo:nil]; * *Your close button action should be [NSApp endSheet:self.sheet]; *Your didEndSheet: method should be [self.sheet orderOut:self]; A: You can use UIVIew method animateWithDuration:delay:options:animations:completion: to accomplish this. You said you want the next line to execute once the window is closed, rather than after it is opened. In any case, you may end the OnLaunch method this way: - (IBAction)OnLaunch:(id)sender { MyClass *controllerWindow = [[MyClass alloc] initWithWindowNibName:@"pop"]; [controllerWindow animateWithDuration:someDelay:options: someUIAnimationOption animations:^{ [controllerWindow showWindow:self]; // now you can animate it in the showWindow method } completion:^{ [self windowDidFinishShowing]; // or [self windowDidFinishDisappearing] } } - (void) windowDidFinishShowing { NSLog(@"this is a log line"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Convert Apache .htaccess to Nginx I got the following .htaccess code for a Magento plugin, could someone help me convert it to valid Nginx rewrites? I'm having a really tough time getting this down. It's for a plugin that rewrites and caches Magento URL's. The original editor of the module couldn't help me. I'm sure there are lots of people using Nginx and wanting to use this plugins functionality! # static rewrite - home page RewriteCond %{HTTP_COOKIE} store=default RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} ^/magento/$ RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/ww/var/turbocache/default.html -f RewriteRule .* var/turbocache/default.html [L] # static rewrite - other pages RewriteCond %{HTTP_COOKIE} store=default RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} /magento/(.*)\.html$ [NC] RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/www/var/turbocache/magento/default/%1.html -f RewriteRule .* var/turbocache/magento/default/%1.html [L] # store view is choosen by request_path # static rewrite - home page RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} ^/magento/default(/|)$ RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/www/var/turbocache/default.html -f RewriteRule .* var/turbocache/default.html [L] # static rewrite - other pages RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} ^/magento/default/(.*)\.html$ [NC] RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/www/var/turbocache/magento/default/%1.html -f RewriteRule .* var/turbocache/magento/default/%1.html [L] #cookie RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} ^/magento/$ RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/www/var/turbocache/default.html -f RewriteRule .* var/turbocache/default.html [L] # rules for default storeview # static rewrite - home page RewriteCond %{HTTP_COOKIE} !artio_mturbo=.* RewriteCond %{REQUEST_URI} /magento/(.*)\.html$ [NC] RewriteCond %{QUERY_STRING} !.+ RewriteCond /var/www/var/turbocache/magento/default/%1.html -f RewriteRule .* var/turbocache/magento/default/%1.html [L] Thanks so far! A: if ($http_cookie ~ "store=default"){ set $rule_0 1$rule_0; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_0 2$rule_0; } if ($uri ~ "^/magento/$"){ set $rule_0 3$rule_0; } if ($args !~ ".+"){ set $rule_0 4$rule_0; } if (-f /var/ww/var/turbocache/default.html){ set $rule_0 5$rule_0; } if ($rule_0 = "54321"){ rewrite /.* /var/turbocache/default.html last; } if ($http_cookie ~ "store=default"){ set $rule_1 1$rule_1; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_1 2$rule_1; } if ($uri ~* "/magento/(.*).html$"){ set $rule_1 3$rule_1; } if ($args !~ ".+"){ set $rule_1 4$rule_1; } if (-f /var/www/var/turbocache/magento/default/%1.html){ set $rule_1 5$rule_1; set $bref_1 $1; } if ($rule_1 = "54321"){ rewrite /.* /var/turbocache/magento/default/$bref_1.html last; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_2 1$rule_2; } if ($uri ~ "^/magento/default(/|)$"){ set $rule_2 2$rule_2; } if ($args !~ ".+"){ set $rule_2 3$rule_2; } if (-f /var/www/var/turbocache/default.html){ set $rule_2 4$rule_2; } if ($rule_2 = "4321"){ rewrite /.* /var/turbocache/default.html last; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_3 1$rule_3; } if ($uri ~* "^/magento/default/(.*).html$"){ set $rule_3 2$rule_3; } if ($args !~ ".+"){ set $rule_3 3$rule_3; } if (-f /var/www/var/turbocache/magento/default/%1.html){ set $rule_3 4$rule_3; set $bref_1 $1; } if ($rule_3 = "4321"){ rewrite /.* /var/turbocache/magento/default/$bref_1.html last; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_4 1$rule_4; } if ($uri ~ "^/magento/$"){ set $rule_4 2$rule_4; } if ($args !~ ".+"){ set $rule_4 3$rule_4; } if (-f /var/www/var/turbocache/default.html){ set $rule_4 4$rule_4; } if ($rule_4 = "4321"){ rewrite /.* /var/turbocache/default.html last; } if ($http_cookie !~ "artio_mturbo=.*"){ set $rule_5 1$rule_5; } if ($uri ~* "/magento/(.*).html$"){ set $rule_5 2$rule_5; } if ($args !~ ".+"){ set $rule_5 3$rule_5; } if (-f /var/www/var/turbocache/magento/default/%1.html){ set $rule_5 4$rule_5; set $bref_1 $1; } if ($rule_5 = "4321"){ rewrite /.* /var/turbocache/magento/default/$bref_1.html last; } Hope it will work ,good luck。 A: Here is a converter that give you this from your htaccess. This may give you a solid first base. After that, if you have further question please feel free to write them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jquery colon conflict HTML allows to use as a valid identifier (ID) a colon. For example: <div id="item:0">...</div> The problem is I have a Jquery snippet like this: $("#" + id).clone(true, true); When some ID uses a colon this call makes JQuery crash. What can I do to make it work? (Note: changing colon symbol for other valid character is not an option) A: Escape the id with something like id = id.replace(':', '\\:'); before you try selecting it. A: You say changing the id is not possible - but could you change the id with javascript client side? Otherwise, you could assign a class to each element that has id with colon, and select them by their class. A: Can't you clone a div, not by id?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Help needed with farbtastic color picker. Simple example html included I've included a very simple html example that almost works. It is a very plain implementation of this great color picker. But it doesn't quite work as advertised. I only get a single blue box and I can pick blue shades. But not the gradient or the outer ring. Wait! I just realized that the outer ring is there, and I can change the colors with it. But its invisible! Weird.... Can anybody show me how to get the whole thing to work? http://bizzocall.com/farbPicker.html Thanks in advance! A: the images for it are not pointing to the correct uri. http://bizzocall.com/css/marker.png returns a 404; point your images to the correct file and you should be straight A: I have the farbtastic color picker working really well now. Just for those of you who want an example to take apart and look at, here's a link. The sytax of how the farbtastic function is called to send the color to numerous items on the page is the tricky part. But, its working here. Just look at the source... http://bizzocall.com/cp-BizzoActiveButton.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7560467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Behaviour of RTF in browsers I am receiving text from a backend and displaying it on my web page. The text could be in one of three formats: plain text, HTML, and RTF. I am sure the first two will render without any problems, or loss of formatting. Will RTF be interpreted and rendered properly by web browsers? A: No, RTF will not render at all. A: The actual browser itself will not render the RTF directly because a browser renders html. However, the browser will receive the RTF sent from the server and will launch whatever default RTF editor is in place on the end users system. By default on windows, this is typically wordPad. However if an end user has Microsoft Word in place or another RTF editor this could be the editor that gets launched. The end user will then be able to read the RTF in this editor. On my system pushing RTF to a client will launch Word and give me the option to either Open or Save the RTF file immediately. I hope this helps out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560468", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call function in main activity from service? I start a service from my main activity using startService(). The service checks for sockets on localhost. When it receives a socket, it reads data from it. I would like to hide the notification bar when it receives socket with specific data. I already coded a function hideNotificationBar() which is located in my main activity. The problem is I don't know how to call this function in main activity from service. Thanks for any help! A: Send a Broadcast from Service. Register your Activity to receive this broadcast and act upon it. This approach solves the problem of storing/acquiring the reference to Activity, which might become inactive during the lifetime of your Service. The downside is that you can only send simple types, Bundle or classes implementing Parcelable via a broadcast Intent. A: I suggest you have a look at MessengerService and MessengerServiceActivities from API Demos application. Basically, idea is to have Handler class inside both your activity and service that handles communication between the two. Use ServiceConnection in the activity to establish connection with the service.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Try-Catch Problem in c++ I am trying queue implementation in c++. During that I am having this problem. void Queue::view() { int i; try { if(Qstatus==EMPTY) { UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY"); throw ex; } } i=front; cout<<"Queue contains...\n"; while(i <= rear) { cout<<queue[i]<<" "; i++; } } This gives an error as : error: expected ‘catch’ before ‘i’ I think this problem is arises since I doesn't written catch block below try block. But If want to write the catch block in main(), ( like in this case ), how could I do that? Before, that Could I do that? If not Why? A: catch block must follow the try block. If you want the catch to be in main - that's where the try has to be too. You can throw everywhere, doesn't have to be inside a try block within the same function. It should be something like this: void Queue::view() { int i; if(Qstatus==EMPTY) { UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY"); throw ex; } i=front; cout<<"Queue contains...\n"; while(i <= rear) cout<<queue[i]<<" "; } /// ... int main() { Queue q; try{ q.view(); } catch(UnderFlowException ex) { /// handle } catch (...) { /// unexpected exceptions } // follow the success/handled errors } A: You simply need to remove the try block. A try block always goes with a catch. void Queue::view() { int i; if(Qstatus==EMPTY) { ex = UnderFlowException("\nQUEUE IS EMPTY"); throw ex; } i=front; cout<<"Queue contains...\n"; while(i <= rear) cout<<queue[i]<<" "; } You can then include a try/catch construct in your main. int main() { Queue queue; try { queue.View() } catch(UnderFlowException ex) { //handle ex } return 0; } A: All try blocks need at least one associated catch block. You should remove the try block if you have no intentions of handling any exceptions here. Exceptions can be (and usually should be!) thrown outside of a try block. A: Make your code catch and rethrow the exception, like this: try { if(Qstatus==EMPTY) { UnderFlowException ex = UnderFlowException("\nQUEUE IS EMPTY"); throw ex; } } catch( ... ) { throw; // rethrow whatever exception we just catched } Although you don't even need the try block in the first place. Looks like just throw ex; would work, since you don't intend to catch it but just throw it. A: try{ } catch(Exception ex){ } Catch must be immediately after try. These are the rules.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I log in and display information from two tables (MySQL)? I'm new to MySQL and PHP so Im not sure how to approach this problem I'm having. I have two tables right now. CREATE TABLE `users` ( `userid` int(25) NOT NULL AUTO_INCREMENT, `username` varchar(65) NOT NULL DEFAULT '', `password` varchar(32) NOT NULL DEFAULT '', `emailaddress` varchar(255) NOT NULL DEFAULT '', PRIMARY KEY (`userid`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; and CREATE TABLE `images` ( `userid` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, `image` blob, PRIMARY KEY (`userid`) ) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; so what I want to do is when a user signs in I want to be able to display an image that the user uploaded. do I have to do something to the tables to make theme reference from each other? help please! A: Do you want just?... select image from images left join users on users.userid=images.userid where username='whateverusername'; A: in the second table , the attribute userid should be a foreign key (i'd rather use Innodb to make sure that there is a foreign key constraint but it's up to u to use innodb or not) so your table should look like this CREATE TABLE images ( userid int(10) unsigned NOT NULL, name varchar(50) DEFAULT NULL, image blob, foreign key userid references users(userid) on delete cascade ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; once you do that, the table images will be linked to the table users which means that no record will be added to the table images unless the user id is already in the table users if you wanna grab all the informations about that users including the image , you can perform a join between the two tables. example with php $con = mysql_connect("localhost","mysql_user","mysql_pwd"); if (!$con) { die('Could not connect: ' . mysql_error()); } $user_id = 1; $results = array(); > $results =mysql_query("select t1.userid,t1.username,t2.name,t2.image from users as t1 left join images as t2 on t1.userid=t2.userid where userid = $user_id",$con); UPDATE: make sure that the type of userid in both tables match
{ "language": "en", "url": "https://stackoverflow.com/questions/7560472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Updating the centre point & zoom of MKMapView (iPhone) I have been trying to centre the map view on the users location. This should also update as and when a change in location is registered. The issue I'm having is upon loading the app I can't get hold of the current latitude and longitude to apply the centring & zooming. These are the key bits of code I have so far... - (void)viewDidLoad { self.locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; [self updateMapZoomLocation:locationManager.location]; [super viewDidLoad]; } The idea being that it should create an instance of the location manager, then start updating the location. Finally it should run the function I wrote to update the map view accordingly... - (void)updateMapZoomLocation:(CLLocation *)newLocation { MKCoordinateRegion region; region.center.latitude = newLocation.coordinate.latitude; region.center.longitude = newLocation.coordinate.longitude; region.span.latitudeDelta = 0.1; region.span.longitudeDelta = 0.1; [map setRegion:region animated:YES]; } However this doesn't seem to happen. The app builds and runs ok, but all that gets displayed is a black screen - it's as if the coordinates don't exist?! I also have a delegate method that deals with any updates by calling the function above... - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [self updateMapZoomLocation:newLocation]; } I have tried looking at several of the other similar questions that have been asked & answered previously however I still can't seem to find the solution I'm after. Any help on this would be really appreciated; I've spent hours and hours trawling the internet in search of help and solutions. ps. 'map' is the mapView. A: You want to use the MKMapViewDelegate callback so you only zoom in once the location is actually known: Here's some swift code to handle that: var alreadyZoomedIn = false func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) { if(!alreadyZoomedIn) { self.zoomInOnCurrentLocation() alreadyZoomedIn = true } } func zoomInOnCurrentLocation() { var userCoordinate = mapView?.userLocation.coordinate var longitudeDeltaDegrees : CLLocationDegrees = 0.03 var latitudeDeltaDegrees : CLLocationDegrees = 0.03 var userSpan = MKCoordinateSpanMake(latitudeDeltaDegrees, longitudeDeltaDegrees) var userRegion = MKCoordinateRegionMake(userCoordinate!, userSpan) mapView?.setRegion(userRegion, animated: true) } A: You shouldn't call updateMapZoomLocation during your viewDidLoad function because the location manager has not yet go a location. If/when it does it'll call the delegate function when it's ready. Until then your map won't know where to center. You could try zooming as far out as it goes, or remembering where it was last looking before the app was shutdown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Scaling image offsets between resolutions I have an app where, in landscape, I line up a bunch of lowercase alphabet ImageView pngs so that they are sitting on an imaginary line. The problem is that they are of different heights i.e. an 'h' is taller than an 'a'. Thus I've been setting the android:layout_marginTop attribute for each letter, in pixels, to line them up on the Galaxy Tab. This has worked. My problem is that when I go to run the app on a Milestone, the scaling of the offsets is a litttttle wonky. It looks like there's some sort of scaling happening, which is kind of working, but it's not perfect. Anyone have an idea how I could remedy this? A: I think that trying to hard code the offsets for each letter and each display resolution is going to be a real pain and will be even bigger pain to maintain. An easy solution would be to use photoshop (or gimp) to resize the png files so they all have the exact same dimensions and set the new region of the PNG to be transparent. A: I would first question why you're doing it this way...seems overly complicated. That said, you could try to just measure the maximum heigh for the ImageViews and use that. For example, x, h, and g all have the same x-height (the height of the lowercase letter x) but the h has an ascender, and the g has a descender (which go above and below the standard x-height respectively). You could create all the letters aligned on the baseline, give them all the same height (the x-height + the ascender height + the descender height) and then just align top, bottom, or center align them on the imaginary line, which should give you a proper alignment. Really, if you can share a little more information (a screenshot maybe?) there's probably a much more elegant solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how does google create the instant preview images? I was wondering how google is capturing all those websites that are featured in google's instant preview? I'm sure they are not using a thumbnail service (like www.thumbalizr.com, websnapr.com, snapcasa.com, thumbshots.com) but rather use their own software. BUT: given that google captures A LOT of websites, they must have a very sophisticated system. PLUS: this generates HUGE amounts of data (jpgs?). Does somebody have more insight into how google does this? A: Yes, it's something like that. Their webmaster pages hint that they render the page with the same engine Chrome uses, and the preview is based on the result. A: It's hard to say, but here's some info from a Google project manager discussing it: http://googleblog.blogspot.com/2010/11/beyond-instant-results-instant-previews.html It says in part: "we match your query with an index of the entire web, identify the relevant parts of each webpage, stitch them together and serve the resulting preview completely customized to your search—usually in under one-tenth of a second" That plus looking at the source of a preview page suggests that they're using their own index (the same webcache.googleusercontent.com that is used to serve the Cached pages) to serve JPEG Base64 image strings as screenshots.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dojo drop-down detaches when scrolling page containing FilteringSelect or ComboBox Since the ComboBox and FilteringSelect use a 'dijitPopup' whose DOM element gets inserted just before the closing body tag (presumably to help with ensuring it appears above everything else z-index-wise) this means that if the ComboBox is contained in an element that scrolls independent of the window itself and the user opens the dropdown and then scrolls the window (or whatever containing element) using the scroll wheel, that the menu part doesn't move with the control itself. Is there a straightforward way to ensure that the menu part of the view remains positioned correctly relative to the control itself rather than simply assuming that its starting position is ok? EDIT: appears to be a known issue (http://bugs.dojotoolkit.org/ticket/5777). I understand why they put the dijit popup just before the closing body tag for z-index stacking and overflow clipping issues, but it seems like it's maybe not the ideal way to do things given the bug in question here and things like: You can restrict the Dijit theme to only small portions of a page; you do this by applying the CSS class of the theme to a block-level element, such as a div. However, keep in mind that any popup-based widget (or widgets that use popups, such as dijit.form.ComboButton, dijit.form.DropDownButton, and dijit.form.Select) create and place the DOM structure for the popup as a direct child of the body element—which means that your theme will not be applied to the popup. ~ from http://dojotoolkit.org/documentation/tutorials/1.6/themes_buttons_textboxes/ A: Not sure if this is the very best solution, but here's what I came up with: Since the widget may be programmatically added/removed, and to avoid coupling a solution with some particular surrounding markup that we can't always count on in all cases, what I did was to hook the _showResultList and _hideResultList methods of ComboBox and when the popup opens, traverse up the DOM till we reach the <html> tag, adding onscroll listeners on each ancestor. The handler for the onscroll event is simply: var myPos = dojo.position(this.domNode, true); this._popupWidget.domNode.parentNode.style.top = '' + (myPos.y + myPos.h) + "px"; where this is the widget in question. I scope the handler to the widget using dojo.hitch. In the close method I remove the listeners. I have to clean up the code a bit before it's presentable, but when it's finalized I'll add it to this answer. Note: I only show updating the y position here. Part of the cleanup is to add x position updating in case someone scrolls horizontally. A: Though its old I just faced this same problem and it looks like a Dojo issue and the fix is available here https://bugs.dojotoolkit.org/changeset/30911/legacy
{ "language": "en", "url": "https://stackoverflow.com/questions/7560481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assembly Language: Read (w/o echo) and write I am writing a program that will read and write characters, converting lowercase characters to uppercase. This is my first assembly program, so I am attempting to first get the program to read in a character and write it out. This is what I have coded so far: .model small .8086 .data lower db 'a' .code start: mov ax,@data mov ds,ax mov ah,8 int 21h mov dl,al mov ah,2 int 21h exit: mov ax,4c00h int 21h end start Have I handled the read/write correctly? When I run this program and enter in a character, I only see one instance of it. Shouldn't it be two? One for the letter I typed, and then one for letter returned? For example, if I type d, I see: d but shouldn't I see: d d or dd A: DOS Int 08h reads a character from STDIN and does not echo it. If you want to echo the character, call int 01h.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django-- Retrieve specific object in templates I'm trying to have the URL have a variable (say userid='variable') and that variable would be passed as an argument to retrieve a specific object with 'variable' as its name in some specific application's database. How would I do this? A: Arie is right, the documentation for Django is excellent. Don't be intimidated, they make it very easy to learn. From the Writing your first Django app, part 3 (https://docs.djangoproject.com/en/dev/intro/tutorial03/), the example shows you how to capture variables from the URL. In urls.py: urlpatterns = patterns('', (r'^polls/$', 'polls.views.index'), (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail'), ) the line (r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail') says when the url is like mysite.com/polls/423, capture the \d+ (the 423) and send it to the detail view as variable named poll_id. If you change <poll_id> to <my_var>, the variable named my_var is passed to the view. In the view, the example has: def detail(request, poll_id): return HttpResponse("You're looking at poll %s." % poll_id) You in the body of this function, you could look up the poll Polls.objects.get(id=poll_id) and get all of the properties/methods of the Poll object. ALTERNATIVELY, if you are looking to add URL variables (query string), like /polls/details?poll_id=423, then your urls.py entry would be: (r'^polls/details$', 'polls.views.detail'), and your view: def detail(request): poll_id = request.GET['poll_id'] return HttpResponse("You're looking at poll %s." % poll_id) In the body, you could still get details of the Poll object with Poll.objects.get(id=poll_id), but in this case you are creating the variable poll_id from the GET variable instead of allowing Django to parse from the url and pass it to the view. I would suggest sticking with the first method. A: Did you actually read the tutorial for Django? To highlight just one sentence from Write your first view Now lets add a few more views. These views are slightly different, because they take an argument (which, remember, is passed in from whatever was captured by the regular expression in the URLconf)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Jasper Reports OutOfMemoryError on export I have written a web app for managing and running Jasper reports. Lately I've been working with some reports that generate extremely large (1500+ page) outputs, and attempting to resolve the resultant memory issues. I have discovered the JRFileVirtualizer, which has allowed me to run the report successfully with a very limited memory footprint. However, one of the features of my application is that it stores output files from previously run reports, and allows them to be exported to various formats (PDF, CSV, etc.). Therefore, I find myself in the situation of having a 500+MB .jrprint file and wanting to export it to, for example, CSV on demand. Here is some simplified example code: JRCsvExporter exporter = new JRCsvExporter(); exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, jrprintPath); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); exporter.exportReport(); Unfortunately, when I attempt this on the large file I mentioned, I get an OutOfMemoryError: Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded at java.io.ObjectInputStream$HandleTable.grow(ObjectInputStream.java:3421) at java.io.ObjectInputStream$HandleTable.assign(ObjectInputStream.java:3227) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1744) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) at java.util.ArrayList.readObject(ArrayList.java:593) at sun.reflect.GeneratedMethodAccessor184.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974) at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351) at net.sf.jasperreports.engine.base.JRVirtualPrintPage.readObject(JRVirtualPrintPage.java:423) ... From browsing some of the Jasper internals, it looks like no matter how I attempt to set up this export (I have also tried loading and setting the JASPER_PRINT parameter directly), there will ultimately be a call to JRLoader.loadObject(...) which will attempt to load my entire 500MB report into memory (see net.sf.jasperreports.engine.JRAbstractExporter.setInput()). My question is, is there a way around this that doesn't involve just throwing memory at the problem? 500MB is doable, but it doesn't leave my application very future-proof, and the JRVirtualizer solution for report execution leaves me hoping there will be something similar for export. I am willing to get my hands dirty and extend some of the Jasper internal classes, but the ideal solution would be one provided by Jasper itself, for obvious reasons. A: Since posting this question, I have also filed a feature request with JasperSoft. As a follow-up, I was pointed to the JRVirtualizationHelper.setThreadVirtualizer method. This method allows you to set a JRVirtualizer associated with the current thread, which will be used during JasperPrint deserialization. I have tested this in my project with satisfactory results. It seems the feature I was hoping existed does indeed exist, although its visibility in the API could potentially be improved. Code sample: JRVirtualizer virtualizer = new JRSwapFileVirtualizer(1000, new JRSwapFile(reportFilePath, 2048, 1024), true); JRVirtualizationHelper.setThreadVirtualizer(virtualizer); A: I think your problem is that a .jrprint is a serialized Java object that you must deserialize completely. You need to break it somehow into small files and then concatenate the outputs at export time. My proposal is a bit involved but I think it might work, at least for some cases: * *Fill your report using a JRVirtualizer. Use the methods that return a JasperPrint instance, to avoid dumping everything to a huge .jrprint. *Do an internal export using a JRXmlExporter. The trick would be to use the appropiate JRExportParameters to tell Jasper to export each page separately (you can use a ZipOutputStream as a container to avoid directories with lots of files). *When you want to do your real export, use a JASPER_PRINT_LIST. It is important that the list implementation is lazy and creates JasperPrint instances one by one using JRPrintXmlLoader, so you do not need to load the whole thing at once. Anyway, you should inspect Jasper source code to check if this approach is doable. A: Thank you for your question and your own answer. But I have a further question on your solution: You said you use the method JRVirtualizationHelper.setThreadVirtualizer to set the JRSwapFileVirtualizer instance associated with current thread. But since your requirement is to export some previously generated reports into PDF/CSV files, I think the GENERATE and EXPORT actions are run in two separated threads, because these two actions are probably generated by two separated user clicks. So, why can you set a single JRSwapFileVirtualizer instance for the two threads? You are using a single server JVM?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHP rename() Ignoring Permissions? Environment * *PHP -V output: PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch (cli) (built: May 2 2011 23:00:17) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies *cat /etc/issue output: Ubuntu 11.04 *Apache2 -V ouput: Server version: Apache/2.2.17 (Ubuntu) Server built: Sep 1 2011 09:31:14 *Browser About output: Firefox 6.0.2 PS -AUX Ouput root 2943 0.0 0.3 206420 12428 ? Ss Sep19 0:20 /usr/sbin/apache2 -k start www-data 18658 0.0 0.2 208552 11096 ? S Sep25 0:00 /usr/sbin/apache2 -k start www-data 18659 0.0 0.3 208976 12036 ? S Sep25 0:00 /usr/sbin/apache2 -k start www-data 18660 0.0 0.3 210532 12476 ? S Sep25 0:00 /usr/sbin/apache2 -k start www-data 18661 0.0 0.3 210276 11820 ? S Sep25 0:00 /usr/sbin/apache2 -k start www-data 18662 0.0 0.2 206948 10236 ? S Sep25 0:00 /usr/sbin/apache2 -k start www-data 20037 0.0 0.3 208976 12128 ? S 08:22 0:00 /usr/sbin/apache2 -k start www-data 20039 0.0 0.3 209132 11748 ? S 08:23 0:00 /usr/sbin/apache2 -k start www-data 20120 0.0 0.3 209004 12000 ? S 09:04 0:00 /usr/sbin/apache2 -k start File Permissions drwxr-xr-x 2 www-data www-data 4096 2011-09-26 15:24 . drwxr-xr-x 4 www-data www-data 4096 2011-08-26 11:31 .. -rw-r--r-- 1 root root 161976 2011-08-26 16:26 market.txt -rw-r--r-- 1 root root 0 2011-09-26 14:55 test1.txt -rw-r--r-- 1 root root 0 2011-09-26 14:55 test2.txt -rw-r--r-- 1 root root 0 2011-09-26 14:55 test3.txt -rw-r--r-- 1 root root 0 2011-09-26 14:55 test4.txt -rw-r--r-- 1 root root 0 2011-09-26 15:02 test5.txt Code rename($file, "$dest/$file"); Question When I run the above code on the files listed in the File Permissions section above, it properly moves the file from its current location to a new location and removes the original. How is this possible when apache2 is running as www-data and the files are owned by root and only have read access for non-root users? On the PHP documentation it says: Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem. Does rename() call either of those system functions during the process? If so, why? Not that it matters anyway as www-data should not be able to chown/chmod a file owned by root anyway. Can anyone explain to me how this is occuring? Additional Information * *I have tried this with the PHP script owned by root and by www-data and it works. I tried to provide as much pertinent info as possible but let me know if you need anything else. A: Moves don't "remove" originals, unless the move takes place across filesystem boundaries. Within a single filesystem, a move simply rewrites the relevant directory entries so it APPEARS that you've copied/deleted the file, but all you've done is a bit of housekeeping. Since www-data owns the directories in question, it can rewrite the directory entries representing those files all it wants, and never touch the actual files. A: When moving files you are not editing the files themselves, but rather the directory they are part of. In your case that directory is owned by www-data (the apache process)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inserting new tuples into a 1 to many relationship tables using c# DataSet I have a typed DataSet with two TableAdapters (1 to many relationship) that was created using visual studio 2010's Configuration Wizard. The child table's FK uses cascading. It is a small part of an application that keeps track of groups (parent table) and group members (child table). I can insert new tuples into the Groups table fine but the problem occurs when I am trying to insert new tuples into the Members table when the FK is based on a group that I just inserted into the group table. You can see the problem in the following code snippet GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName, this.type); this.groupsDataSet.Members.AddMembersRow(memberName, addedGroup); this.groupsTableAdapter.Update(this.GroupsDataSet.Groups); this.membersTableAdapter.Update(this.GroupsDataSet.Members); When I insert a new row into the Group table (parent) the PK id returned by addedGroup.id is -1 so it seems that Members table (child) insertion is trying to insert a new row with groupId = -1 which does not exist and is throwing the error. What is the correct way to add a new Group (parent) and then immediately add a new Member (child) that is associated with the newly added Group? A: I think the problem that you have is the ID won't be filled until you update. So you need to change the order of your statements to: GroupsDataSet.GroupsRow addedGroup = this.groupsDataSet.Groups.AddGroupsRow(groupName, this.type); this.groupsTableAdapter.Update(this.GroupsDataSet.Groups); this.groupsDataSet.Members.AddMembersRow(memberName, addedGroup); this.membersTableAdapter.Update(this.GroupsDataSet.Members); There is also a Refresh on insert setting that needs to be checked. If you look at Figure 3 in this link: (I am assuming SQL Server is the db.) http://blogs.msdn.com/b/vsdata/archive/2009/09/14/refresh-the-primary-key-identity-column-during-insert-operation.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7560503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return value from For loop I have a listView in my app. I loop through the items to check which one is currently selected and then return a value. As all paths have to return a value I have to return a value outside the loop which overwrites the for loop return, how do I keep this without overwriting it after the loop? public string GetItemValue() { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Checked == true) { return listView1.Items[i].Text; // I want to keep this value } } // Without overwriting it with this but the compiler // requires me to return a value here return "Error"; } Any help is most appreciated. Thanks. P.S I have tried using break after the if but no luck. A: Well, your return outside of the loop, return "Error"; shouldn't get called based on your logic. Since return causes your method to immediately exit, the "Error" return will never happen, that is unless the code never steps into the if inside the loop. All things considered, this may be an exceptional case in your code. Thus, throwing an exception may be the appropriate thing to do: public string GetItemValue() { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Checked == true) { return listView1.Items[i].Text; // I want to keep this value } } throw new InvalidOperationException("Did not find value expected."); } Exceptions are usually thrown to indicate that a bug exists in code. A "Hey, that should really not be happening." The application stops, and hopefully the user gets an opportunity to contact support to help you reproduce it. Based on your comment: When I run it, it just returns the error text... That means your check in your if statement is not succeeding. if (listView1.Items[i].Checked == true) Which means that none of your items in your ListView are checked. A: That's the kind of situations where you are probably better of throwing an exception in order to signal the exceptional situation: public string GetItemValue() { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Checked == true) { // Here you are leaving the GetItemValue method // and the loop stops return listView1.Items[i].Text; } } // if we get that far it means that none of the items of // the select list was actually checked => we are better of // reporting this to the caller of the method throw new Exception("Please select a value"); } A: The return in your for loop isn't overwritten -- the method will return the value in the loop if your conditions are met. Execution of the method ends immediately upon reaching a return statement. If your method is returning "Error", then I'd recommend looking at your code in a debugger, because it's reaching the end of the loop and returning the value "Error". A: If you're returning a value in the loop, it should not reach the return that's outside of the loop. I would check to make sure that the loop is finding the selected item. The other option is to create a local variable to hold the return value: string returnValue = "Error"; for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Checked == true) { returnValue = listView1.Items[i].Text; break; } } return returnValue; Lastly, you might also consider returning an exception when no selections are found, and handling the exception from the calling method. A: On edit: bringing down my comment from above. You don't need to worry about this. As soon as it hits the first return inside the loop, it will return immediately with that value. No code outside the loop is ever hit in that case. Incidentally, this code would be cleaner: public string GetItemValue() { foreach (var item in listView1.Items) { if (item.Checked) return item.Text; } throw new InvalidOperationException("No checked items found"); } Exceptions are a more idiomatic way of handling errors, and the foreach loop is preferred to a for loop when you're just iterating over collections. Also using LINQ, you can get even more concise: public string GetItemValue() { return listView1.Items.Cast<ListViewItem>().Single(i => i.Checked).Text; } A: The return "Error" bit will not overwrite your loop return value. When a return is hit, the function exits, so when a value that is selected is found, the function will spit out your data and stop. A: The compiler requires that all paths of the function return a value. The compiler cannot know before hand whether your inner loop if condition will be met. You can cache the value at a variable and return this in the end of the function e.g. : public string GetItemValue() { string temp = null; for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].Checked == true) { temp = listView1.Items[i].Text; // I want to keep this value break; } } return temp; // Without overwriting it with this but the compiler requires me to return a value here } A: Actually, there is no need for a loop here: return (listView1.SelectedItems.Count > 0) ? listView1.SelectedItems[0].Text : "Error"; But, as it was said, the original question is misleading since return does not override values. You might be thinking about assignment, instead of return. In this case a working code can look like this: string ret = "Error"; foreach(var item in listView1.Items) { if(item.Checked) { ret = item.Text; break; } } return ret;
{ "language": "en", "url": "https://stackoverflow.com/questions/7560505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java rmi, differentiating between multiple client Edit: To be clearer, I basically need to differentiate between the different clients doing remote method invocation in objects stored in the server remote object registry. How could I do that? And here is the situation: I am currently in the process of creating a client/server command line interface application using Java rmi to exchange data (stored in Strings) between the clients and server. I'm having problem whereas I must allow a client to send an authentication command with a user/pass. This authentication command (exemple: >user myUserName myPassword) must be sent through the same remotely called method used to send all the other commands for which the server must answer. My problem : The client must, strictly, only send his commands and display the text result of his command received from the server. As simple a client as it gets, it has no state. Since some methods requires the client to be logged in or have a different server-side implementation if the client is logged in or not, I need to to keep track of the client logged in state on the server(not a problem, I plan to simply keep a time stamp on each user in the user database and use a timeout) and must also differentiate between different clients. Now, I think I have a good idea of how remote object works and I've been able to register a remote object on the server side and access a remote method from it using the client. So, I need to do more, I must not only have client being able to access remote method, I also need the remote method(and the server running them) to know which network client is invoking this method(without passing the client username/pass as parameters in the remote method). I think the rmiclientsocketfactory and rmiserversocketfactory must be customly used to do this, but I don't know how to proceed. thanks you all for your time. A: Objects are not stored in the registry. Stubs are stored in the registry. The remote objects are in the server host. See java.rmi.server.RemoteServer.getClientHost(). Socket factories haven nothing to do with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SecurityID doesn't match, possible CSRF attack I'm working on a site which was coded with Silverstripe, I've got a problem with importing images from the existing folders and wonder if someone can help me on this. Here is what I'm experiencing with SS admin (please see the image attached). 1) I click on File & Images tab, then select a folder eg called Uploads 2) I choose 'Add files to Uploads' button, it will ask me to upload from my computer or import from an existing folder. 3) When I try to import an image from an existing folder, the message - "SecurityID doesn't match, possible CSRF attack." comes up, and I can't go any further. I've never experienced this before, and wonder if someone can point me to the right direction to solve the problem? I can copy some code here if you let me know which part, and I'm using SilverStripe 2.4.1 Thank you very much for your help. A: i've once come across this error when importing existing files in FileDataObjectManager my fix was to add the SecurityID field the FieldSet that's returned by the getImportFields method (around line 452 in FileDataObjectManager.php): new HiddenField('SecurityID','',Session::get('SecurityID')) A: The error message is misleading. I had this error while trying to import images from a directory which did not have read permissions for the web user. Your issue might however be something completely unrelated. A: new HiddenField('SecurityID','',Session::get('SecurityID')) does fixed for me. I am thinking it could be a older version of DOM problem, the latest version all seems alright.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Merge Query - Executing Additional Query I have written a working T-SQL MERGE statement. The premise is that Database A contains records about customer's support calls. If they are returning a product for repair, Database B is to be populated with certain data elements from Database A (e.g. customer name, address, product ID, serial number, etc.) So I will run an SQL Server job that executes an SSIS package every half hour or so, in which the MERGE will do one of the following: * *If the support call in Database A requires a product return and it is not in Database B, INSERT it into Database B.. *If the support call in Database A requires a product return and it is in Database B - but data has changed - UPDATE it in Database B. *If there is a product return in Database B but it is no longer indicated as a product return in Database A (yes, this can happen - a customer can change their mind at a later time/date and not want to pay for a replacement product), DELETE it from Database B. My problem is that Database B has an additional table with a 1-to-many FK relationship with the table being populated in the MERGE. I do not know how, or even if, I can go about using a MERGE statement to first delete the records in the table with FK constraint before deleting the records as I am currently doing in my MERGE statement. Obviously, one way would be to get rid of the DELETE in the MERGE and hack out writing IDs to delete in a temp table, then deleting from the FK table, then the PK table. But if I can somehow delete from both tables in WHEN NOT MATCHED BY SOURCE that would be cleaner code. Can this be done? A: You can only UPDATE, DELETE, or INSERT into/from one table per query. However, if you added an ON DELETE CASCADE to the FK relationship, the sub-table would be cleaned up as you delete from the primary table, and it would be handled in a single operation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can we reject app after getting apple approval? i have uploaded new binary as a new version of my application and at the time of uploading binary, i select the option that "I Will Release this version" means i just put it in "Hold for Developer Release". Suppose my application is approved by apple and i dont want to release that version then what i have to do.is it possible to reject that binary or remove that version from iTunes connect? From itunes connect guide NOTE: You can only use the Version Release Control on app updates. It is not available for the first version of your app since you already have the ability to control when your first version goes live, using the Availability Date setting within Rights and Pricing. If you decide that you do not want to ever release a Pending Developer Release version, you can reject your binary to submit a new one. You are not permitted to skip over an entire version From this, we can remove that option from our application at any version upload. but can we reject after application is approved by apple? A: To reject a approved release, select the approved release in iTunesConnect and at the top of the profile is a link "Cancel this release" A: Paras, once you submit a new binary, it goes to the end of the queue for review! I see a few possible cases related with your question: * *You have no app yet, you submitted an app and waiting for review. Assume that you found a problem with the submitted app, and you wanted to provide a new one. Just submit the new binary, but remember, it will replace the original submission, it will go to the end of the queue and it will wait for review as before. *You have an app on the AppStore, and you wanted to provide an update for the app. As usual, submit your app, and wait to be notified. Once it is approved, your new app will be available to your users. *You have an app on the AppStore, you want to remove it from sales immediately, and provide an update: In this case, you can go to Manage Your Apps in your iTunes Connect, select the app and click on Rights and Pricing then choose an Availability Date in the future. You get a warning message as following: "You have selected an Available Date in the future. This will remove your currently live version from the App Store until the new date. Changing Available Date affects all versions of the application, both Ready For Sale and In Review." That is fine, your app still in the store but not be in the sales. Now you provide your update and wait for the approval, once you get it, go ahead and set your app's availability date accordingly! I hope that answers your question, and good luck on the mobile apps :) A: Read what they say. The answer is right in front of you :) 'If you decide that you do not want to ever release a Pending Developer Release version, you can reject your binary to submit a new one' A: Yes you can reject it! Click on your "New version" > "Binary Details" > "Reject Binary" A: You can remove your app from the AppStore any time you want. For that, simply go to itunesconnect.apple.com and on the "Manage your Application", choose the "Rights & Pricing" button then click on the "specific stores" link. From there you can select in which stores your app will be in sale. You can then deselect all the countries so that your app won't be visible in any store. From the iTunes Connect portal: Select the App Stores where your app will be sold. Note that if you deselect all territories, your app will be removed from sale in all App Stores worldwide. A: Bit of an update. If you have an app with Developer Release and The app has been approved then The Web iTunes Connect does not provide any method to reject the binary, only a release button. There is however a Reject Binary option still available on the iPhone iTunesConnect App. So if you find yourself with this issue * *Start the iTunesConnect App *Select the manage option *Tap on your apps pending version release *Select the 'Reject Binary' button Hope that helps. A: I was not an admin but an app manager in App Store Connect. I did not have permission to remove the app but I was able to withdraw from the sale in order to pull back acceptance. Pricing and Availability -> Availability -> Remove from sale A: It appears that you can not reject a app after it is approved by Apple. One possible sequence is to release the approved version for sale in only some tiny country for an hour, then remove it from sale and submit a new update.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How can I inspect a Hadoop SequenceFile for which I lack full schema information? I have a compressed Hadoop SequenceFile from a customer which I'd like to inspect. I do not have full schema information at this time (which I'm working on separately). But in the interim (and in the hopes of a generic solution), what are my options for inspecting the file? I found a tool forqlift: http://www.exmachinatech.net/01/forqlift/ And have tried 'forqlift list' on the file. It complains that it can't load classes for the custom subclass Writables included. So I will need to track down those implementations. But is there any other option available in the meantime? I understand that most likely I can't extract the data, but is there some tool for scanning how many key values and of what type? A: My first thought would be to use the Java API for sequence files to try to read them. Even if you don't know which Writable is used by the file, you can guess and check the error messages (there may be a better way that I don't know). For example: private void readSeqFile(Path pathToFile) throws IOException { Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(conf); SequenceFile.Reader reader = new SequenceFile.Reader(fs, pathToFile, conf); Text key = new Text(); // this could be the wrong type Text val = new Text(); // also could be wrong while (reader.next(key, val)) { System.out.println(key + ":" + val); } } This program would crash if those are the wrong types, but the Exception should say which Writable type the key and value actually are. Edit: Actually if you do less file.seq usually you can read some of the header and see what the Writable types are (at least for the first key/value). On one file, for example, I see: SEQ^F^Yorg.apache.hadoop.io.Text"org.apache.hadoop.io.BytesWritable A: I'm not a Java or Hadoop programmer, so my way of solving problem could be not the best one, but anyway. I spent two days solving the problem of reading FileSeq locally (Linux debian amd64) without installation of hadoop. The provided sample while (reader.next(key, val)) { System.out.println(key + ":" + val); } works well for Text, but didn't work for BytesWritable compressed input data. What I did? I downloaded this utility for creating (writing SequenceFiles Hadoop data) github_com/shsdev/sequencefile-utility/archive/master.zip , and got it working, then modified for reading input Hadoop SeqFiles. The instruction for Debian running this utility from scratch: sudo apt-get install maven2 sudo mvn install sudo apt-get install openjdk-7-jdk edit "sudo vi /usr/bin/mvn", change `which java` to `which /usr/lib/jvm/java-7-openjdk-amd64/bin/java` Also I've added (probably not required) ' PATH="/home/mine/perl5/bin${PATH+:}${PATH};/usr/lib/jvm/java-7-openjdk-amd64/"; export PATH; export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/ export JAVA_VERSION=1.7 ' to ~/.bashrc Then usage: sudo mvn install ~/hadoop_tools/sequencefile-utility/sequencefile-utility-master$ /usr/lib/jvm/java-7-openjdk-amd64/bin/java -jar ./target/sequencefile-utility-1.0-jar-with-dependencies.jar -- and this doesn't break the default java 1.6 installation that is required for FireFox/etc. For resolving error with FileSeq compatability (e.g. "Unable to load native-hadoop library for your platform... using builtin-java classes where applicable"), I used the libs from the Hadoop master server as is (a kind of hack): scp root@10.15.150.223:/usr/lib/libhadoop.so.1.0.0 ~/ sudo cp ~/libhadoop.so.1.0.0 /usr/lib/ scp root@10.15.150.223:/usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so ~/ sudo cp ~/libjvm.so /usr/lib/ sudo ln -s /usr/lib/libhadoop.so.1.0.0 /usr/lib/libhadoop.so.1 sudo ln -s /usr/lib/libhadoop.so.1.0.0 /usr/lib/libhadoop.so One night drinking coffee, and I've written this code for reading FileSeq hadoop input files (using this cmd for running this code "/usr/lib/jvm/java-7-openjdk-amd64/bin/java -jar ./target/sequencefile-utility-1.3-jar-with-dependencies.jar -d test/ -c NONE"): import org.apache.hadoop.io.*; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.SequenceFile.ValueBytes; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; Path file = new Path("/home/mine/mycompany/task13/data/2015-08-30"); reader = new SequenceFile.Reader(fs, file, conf); long pos = reader.getPosition(); logger.info("GO from pos "+pos); DataOutputBuffer rawKey = new DataOutputBuffer(); ValueBytes rawValue = reader.createValueBytes(); int DEFAULT_BUFFER_SIZE = 1024 * 1024; DataOutputBuffer kobuf = new DataOutputBuffer(DEFAULT_BUFFER_SIZE); kobuf.reset(); int rl; do { rl = reader.nextRaw(kobuf, rawValue); logger.info("read len for current record: "+rl+" and in more details "); if(rl >= 0) { logger.info("read key "+new String(kobuf.getData())+" (keylen "+kobuf.getLength()+") and data "+rawValue.getSize()); FileOutputStream fos = new FileOutputStream("/home/mine/outb"); DataOutputStream dos = new DataOutputStream(fos); rawValue.writeUncompressedBytes(dos); kobuf.reset(); } } while(rl>0); * *I've just added this chunk of code to file src/main/java/eu/scape_project/tb/lsdr/seqfileutility/SequenceFileWriter.java just after the line writer = SequenceFile.createWriter(fs, conf, path, keyClass, valueClass, CompressionType.get(pc.getCompressionType())); Thanks to these sources of info: Links: If using hadoop-core instead of mahour, then will have to download asm-3.1.jar manually: search_maven_org/remotecontent?filepath=org/ow2/util/asm/asm/3.1/asm-3.1.jar search_maven_org/#search|ga|1|asm-3.1 The list of avaliable mahout repos: repo1_maven_org/maven2/org/apache/mahout/ Intro to Mahout: mahout_apache_org/ Good resource for learning interfaces and sources of Hadoop Java classes (I used it for writing my own code for reading FileSeq): http://grepcode.com/file/repo1.maven.org/maven2/com.ning/metrics.action/0.2.7/org/apache/hadoop/io/BytesWritable.java Sources of project tb-lsdr-seqfilecreator that I used for creating my own project FileSeq reader: www_javased_com/?source_dir=scape/tb-lsdr-seqfilecreator/src/main/java/eu/scape_project/tb/lsdr/seqfileutility/ProcessParameters.java stackoverflow_com/questions/5096128/sequence-files-in-hadoop - the same example (read key,value that doesn't work) https://github.com/twitter/elephant-bird/blob/master/core/src/main/java/com/twitter/elephantbird/mapreduce/input/RawSequenceFileRecordReader.java - this one helped me (I used reader.nextRaw the same as in nextKeyValue() and other subs) Also I've changed ./pom.xml for native apache.hadoop instead of mahout.hadoop, but probably this is not required, because the bugs for read->next(key, value) are the same for both so I had to use read->nextRaw(keyRaw, valueRaw) instead: diff ../../sequencefile-utility/sequencefile-utility-master/pom.xml ./pom.xml 9c9 < <version>1.0</version> --- > <version>1.3</version> 63c63 < <version>2.0.1</version> --- > <version>2.4</version> 85c85 < <groupId>org.apache.mahout.hadoop</groupId> --- > <groupId>org.apache.hadoop</groupId> 87c87 < <version>0.20.1</version> --- > <version>1.1.2</version> 93c93 < <version>1.1</version> --- > <version>1.1.3</version> A: I was just playing with Dumbo. When you run a Dumbo job on a Hadoop cluster, the output is a sequence file. I used the following to dump out an entire Dumbo-generated sequence file as plain text: $ bin/hadoop jar contrib/streaming/hadoop-streaming-1.0.4.jar \ -input totals/part-00000 \ -output unseq \ -inputformat SequenceFileAsTextInputFormat $ bin/hadoop fs -cat unseq/part-00000 I got the idea from here. Incidentally, Dumbo can also output plain text. A: From shell: $ hdfs dfs -text /user/hive/warehouse/table_seq/000000_0 or directly from hive (which is much faster for small files, because it is running in an already started JVM) hive> dfs -text /user/hive/warehouse/table_seq/000000_0 works for sequence files. A: Check the SequenceFileReadDemo class in the 'Hadoop : The Definitive Guide'- Sample Code. The sequence files have the key/value types embedded in them. Use the SequenceFile.Reader.getKeyClass() and SequenceFile.Reader.getValueClass() to get the type information. A: Following the anwer of Praveen Sripati, here a small example of SequenceFileReadDemo.java from Hadoop the Definitive Guide by Tom White. Data are in HDFS, in this position : user/hduser/output-hashsort/ and the file is part-r-00001 In eclipse, in the Arguments folder I've written this string : and this is part of the output, with the debugger
{ "language": "en", "url": "https://stackoverflow.com/questions/7560515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Controlling Windows in WPF when using MVVM pattern A little while ago, I wrote this SO post looking for a good way to handle UI and business layer interaction, and I liked the answer which was to use the MVVM pattern. So I did so quite successfully, but I'm a bit stuck with a problem using this pattern. Indeed, in some part of my UI, one of my buttons is supposed to open a dialog with the details of an item displayed in a ListView. I saw this SO post asking about the same question, but I didn't quite understand the answer and I wonder if it is suitable in my case. The idea was to use the Unity framework and to call the window associated with the view in the repository using App.Container.Resolve<MyChildView>().ShowDialog(), for example. However, my problem is that I have implemented the ViewModels in project separate from the UI client project. I did this in order to be able to use the VMs from another client if need at a later stage of the project. First question, was that a wrong implementation of the pattern? Second question, as my ViewModels project isn't actually in the client's project, and hence I do not have access to the App global variable. Therefore, I don't think I can use the solution I found in the previously mentioned post. Is there any workaround? A: 1) Your implementation is not wrong at all. I regularly separate UI, VM, and models into separate assemblies. 2) As you mentioned, it isn't appropriate to reference App within a VM. Consider App a "UI class" and treat it as such. Have you considered injecting the appropriate UnityContainer into your VM? If injecting the container isn't an option for you, think about adding a controller to your solution or using the Mediator pattern as suggested by other answers in that SO post you mentioned. A: Try this. Set up a new thread, initialize and show your window (You can also use ShowDialog() instead of Show()), and then convert the thread to a UI thread by calling Dispatcher.Run() which will block until the window is closed. Then, afterwards, you can handle the dialog result however you want. new Thread(() => { MyDialogWindow m = new MyDialogWindow(); m.ShowDialog(); Dispatcher.Run(); // Handle dialog result here. }).Start(); Be sure to add an event in your dialog for when you close the window, to have the Dispatcher stop. Add this to your constructor of the dialog: Closed += (_,__) => Dispatcher.InvokeShutdown();
{ "language": "en", "url": "https://stackoverflow.com/questions/7560521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: when are cookies sent from the user? I have a class that has a function, lets say class.php: class fun { public function get_cookie() { $old_cookie = $_COOKIE['mycookie']; } public function ssl() { //redirect from http to https } In another php file, lets say index.php: //include fun class $fun = new fun; $fun->ssl(); $fun->get_cookie(); My question is since the function get_cookie is after $fun->ssl() does the user send the cookie encrypted? or since the cookie code is coded before the $fun->ssl() is executed, the cookie gets sent unencrypted? A: Never send anything via cookies which requires encryption. Regardless of the answer to the actual question posed here, the contents of your cookies should be considered to be publically accessible and insecure. Firstly, the entire set of cookies for the site is sent (in both directions) with every single web request. So even if you successfully encrypted them with SSL in this particular request, the user would only need to make a plain HTTP request for an image on your site, and he'd transmit them and get them sent back unencrypted. Secondly, it is not unheard of for cookies to leak between sites. Many cross-site scripting hacks exist which can allow third-parties to get hold of your user's cookies. These would not be stored encrypted on the user's machine, even if they were sent via SSL. So I'll repeat my initial statement again: never send anything via cookies which you need to keep secure. A: The Wikipedia article has a very nice explanation of how cookies work. Basically, cookies are sent along with the request header. So unless the connection is being made via HTTPS then the cookie is being sent in the clear. A: The cookie is sent before your code is running. PHP reads the header, fills the global variable $_COOKIE[] and then executes your code. So if somebody makes a request with HTTP, he will get the cookie unencrypted. When you create the cookie, you can define, that the cookie is only sent to pages requested with HTTPS. You do this with the functions session_set_cookie_params() or setcookie() with the $secure parameter. Such cookies won't be sent, if a page is requested with HTTP.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to do something with selected values of an xforms:select every time they change? I have this problem with XForms I am running on Orbeon Forms. I am using a fr:box-select control as follows: <fr:box-select bind="box-select-bind" id="box-select-control"> <xforms:action ev:event="xforms-value-changed"> <xxforms:variable name="selected-value" select="."/> <xforms:message level="modal">Hello:<xforms:output select="$selected-value" /> </xforms:message> </xforms:action> <xforms:itemset nodeset="instance('codes')/box-select/item"> <xforms:label ref="label"/> <xforms:value ref="value"/> </xforms:itemset> </fr:box-select> The binding is to a simple XML file: <box-results></box-results> The codes XML looks like: <box-select> <item> <label>Cat</label> <value>cat</value> </item> <item> <label>Dog</label> <value>dog</value> </item> <item> <label>Bird</label> <value>bird</value> </item> <item> <label>Fish</label> <value>fish</value> </item> </box-select> When I check entries in the box, my node <box-results> gets updated with the selected values separated by a space, which seems to be what is expected. However, I can't seem to find any documentation on how to process the selected values. I want to get access to what value was just selected, de-selected and use the value of this item in an xpath. So, if a value was selected then I would do this: <setvalue ref="somexpath[id=$selected-value]/display value="'true'"/> And if a value was deselected I would do this: <setvalue ref="somexpath[id=$selected-value]/display value="'false'"/> Basically, I just want to know the event to use, and how to get access to the value when it fires. Then I want to use this value in an xpath. I am going to use this to hide/display portions of the form. Using the xforms-value-changed event the Xpath "." doesn't return what I would expect, as it does in "select1" controls. I can loop through all the values that are selected like so: <xforms:action ev:event="xforms-select" xxforms:iterate="for $s in tokenize(instance('data-inst')/box-results,'\s')return xxforms:element('text',$s)"> <xforms:message level="modal">Hello selected:<xforms:output select="$s" /> </xforms:action> However, this isn't exactly what I need. I might be able to make this work, but it would require a lot more work because I need to do know what ones are deselected to change the display for the user. A: Since in your case you don't need to know specifically which value changed, you can on value change reset all the values in somexpath[id=$selected-value] as needed. You can do this with the following code which uses just <xforms:setvalue> with an xxforms:iterate: <xforms:action ev:event="xforms-value-changed"> <xxforms:variable name="selected-values" select="tokenize(., '\s+')"/> <xforms:setvalue xxforms:iterate="instance('codes')/item" ref="@selected">false</xforms:setvalue> <xforms:setvalue xxforms:iterate="$selected-values" ref="for $v in . return instance('codes')/item [value = $v]/@selected">true</xforms:setvalue> </xforms:action> Also see the full source of an example that uses the above snippet. A: you can use ev:event="xforms-select" and ev:event="xforms-deselect" events. Also the selected value can be captured using event('xxforms:item-value') Here is how it would be used in case anyone is wondering: <xforms:action ev:event="xforms-select"> <xxforms:variable name="selected" select="event('xxforms:item-value')" /> <xforms:message level="modal">Select:<xforms:output value="$selected" /></xforms:message> </xforms:action> <xforms:action ev:event="xforms-deselect"> <xxforms:variable name="deselected" select="event('xxforms:item-value')" /> <xforms:message level="modal">deSelect:<xforms:output value="$deselected" /> </xforms:message> </xforms:action>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560527", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create themed/skinned WPF FileDialogs I would like to have my own FileDialogs like OpenFileDialog,SaveFileDialog,BrowseDialog etc... to skin them with the theme of my application to have a unique look/user experience. Well I know I cant skin the win32 dialogs but what about creating my own file dialogs with a window + tree for the folders and datagrid for the files. Would it be too much work to get them safely working? A: Of course you can create your own dialogs, which would give you the ability to skin them however you want. As for whether it would be "too much work", I'd have to say that depends on your time/budget. If the unique look is important to your design, then it is worth the time. From a manager's viewpoint, I'd encourage you to finish the core application features first, to realize a return on investment on your work. Most people, even with a skinned application, aren't terribly surprised by the common dialogs. When you find yourself with extra time at the end of the project, you can allot some time to replace the common dialogs. Good luck and hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: what can i put in beforeUnload? I would like to have an animation effect which starts when people leave a page. I use this currently: window.onbeforeunload = function (){ alert("test"); console.log("test"); sliderIntervalId = setInterval('SlideDown()',1); } While the "test" is indeed logged to the console, the neither the function slideDown nor the test alert is produced... Is this normal behavior? can we use the beforeunload function only for backend purposes? P.S. I'm testing on chrome, that's why I had to use onbeforeUnload i.s.o onUnLoad which seems not to be supported by Chrome? A: Assuming jQuery for the sake of brevity: $('nav a').click(function (e) { //ignore any "modified" click that usually doesn't open in the current window if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) { return; } //where you going here? var place = this.href; //you're not going anywhere, buddy e.preventDefault(); //watch me dance, first $('.animate-me').fadeOut(1000, function afterAnimation () { //you're free to go! document.location = place; }); }); Basically, you don't use onbeforeunload. One advantage is that you can keep the user as long as you want, one disadvantage is that the user won't see an animation when using a link outside nav (but you can just change the selector) Obviously keep the animation fast, like suddenlyoslo.com do. A: Jorrebor, If your trying to have this animation fire when they leave your site or close the browser it will not work as intended. However, you can create this animation while the user travels within your site by removing the 'href' property of your links and creating animations that have a callback function that set the window.location property. Something like: document.getElementById('home').onclick(function(){ yourAnimationFunction(function(){ window.location="example.com"; }); }); alot of work and wont be seo friendly however A: I am working with onbeforeunload and What I was able to figure out is: * *onbeforeunload handler is blocking the browser from destroying the current page *if you don't return anything, the popup does not appear. So your code will be working as long as the event handler runs. This means that timer functions are not usable. They just add to the execution queue, so anything they would do is being queued after the end of currently running handler, which is after the last point in time you were guaranteed your code is still running. So there is only one way to stop the browser from unloading before the animation finishes: * *put a blocking loop that wastes some time in the beforeunload handler *start CSS3 animation by setting an appropriate class on the element before the loop *make the loop end when the animation finishes (make the loop check the actual height of an element or something) Oh, and yes, this is a nastiest hack of all, but I was able to find a way to stop the browser from unloading the page, right? I would appreciate comments with ideas on what to put in the loop. I am taking some options into account: * *wasting CPU on come math on large numbers *accessing localstorage (synchronous call, IO operration) *accessing DOM (this solution already has to) Any ideas? A: onbeforeunload can delay the page unload in only one case: When a return statement with a defined value is returned. In this case, the user gets a confirmation dialog, which offers the user an option to not leave the page. Your desired result cannot be forced in any way. Your animation will run until the browser starts loading the next page: [User] Navigates away to http://other.website/ [Your page] Fires `beforeunload` event [Your page] `unload` event fires [Browser] Received response from http://other.website/ [Browser] Leaves your page [Browser] Starts showing content from http://other.website/
{ "language": "en", "url": "https://stackoverflow.com/questions/7560532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Which CAS Server should I use? I don't know very much about CAS, except that I need Single Sign On for a few internal websites, and that this is probably my best option. What's a good CAS Server to use in an all Ruby on Rails environment? What's a good CAS Server to use in a mix of Ruby on Rails and Java environment? I see rubycas. They have a client. Will this client work in Rails with all CAS Servers or just the rubycas server? If I'm looking to overhaul the entire sign on system, should I add LDAP behind CAS? A: If it needs to be an all Ruby environment you will need to use rubycas-server (http://code.google.com/p/rubycas-server/) and the unofficial Ruby CAS client (https://wiki.jasig.org/display/CASC/Ruby+on+Rails+CAS+Client). If it can be a mixed Ruby/Java environment, I'd imagine that you would want to look at using the original Java CAS server (http://www.jasig.org/cas/download) and the unofficial Ruby CAS client. The Java CAS server is really just a webapp that can be run on something like Tomcat. Any client should work with either server according to documentation (I've tried a few for the Java "server" and all have worked fine). The backend should not really matter to the overall architecture. If you want to use LDAP...go for it. In fact, if you want to use the original CAS Server and don't want to write much Java, there will be projects you can leverage to use LDAP whereas if you are using a homegrown solution, you will need to write that implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I remove duplicates from one List that are found in another? This is for .NET 2.0, so I cannot use LINQ. I have a bit of an interesting problem. I am merging two lists of custom type "Article". The below code does the job nicely: List<Article> merge = new List<Article>(GetFeatureArticles()); merge.AddRange(result); return merge; GetFeatureArticle has only 2 items that are the first two elements in the merged list. "result" is large and its elements trail "GetFeatureArticle"'s elements. The problem is that I need to compare the list returned from "GetFeatureArticles()" to the list in "result" and, if there is a match, remove the matched item in result, not in "GetFeatureArticles". Both lists are of type List<Article>. I am limited by C# 2.0 unfortunately. Thank you. EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT EDIT This is the implementation I ultimately went with as GetFeaturedArticles() will always be two items: List<Article> k = new List<Article>(GetFeatureArticles()); foreach (Article j in k) { for( int i = 0; i < tiles.Count; i++ ) { if (j.ID == tiles[i].ID) tiles.Remove(tiles[i]); } } k.AddRange(tiles); return k; A: Assuming you have some sort of object equality implemented. var listA = new List<Article> {a, b, c, d}; var listB = new List<Article> {e, f}; //Where e, f are equal to b, c in a. listA.RemoveAll(listB.Contains); A: use List<Article> g = new List<Article>(GetFeatureArticles()); foreach (Article a in g) { if (result.Contains (a)) result.Remove (a); } g.AddRange (result); return g; EDIT - as per comments: I assume that Article is a reference type and is implemented with suitable Equals and GetHashCode methods respectively - otherwise the above would only work for equal references (= "same object in both Lists")... A: returnList = returnList.Union(ListToAdd).ToList(); or if combinging multiple lists of items... foreach (List<ListItem> l in ListsToAdd) { returnList = returnList.Union(l).ToList(); } A: Build a Dictionary from the result set. Then: foreach (Article a featuredArticles) { if (resultsDictionary.ContainsKey(a.Key)) { resultsDictionary.Remove(a.Key); } } Then convert the dictionary back to a list. A: This works against .NET Framework 2.0: var featured = new List<Article>(GetFeaturedArticles()); result.RemoveAll(featured.Contains); result.InsertRange(0, featured); return result;
{ "language": "en", "url": "https://stackoverflow.com/questions/7560545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the most optimized/shortest JSON structure I can use to submit multiple records to SOLR Is this JSON legal to add documents to SOLR? { "add": [{"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"} }, {"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"}}] } I am using SOLR 3.4 and submit using CURL from inside PHP. What should I see in the logs if this is not correct? EDIT:This question was mistakenly understood as if I have a bug in the structure above (I did have a missing bracket) That was not the purpose. The question is a more generalized one, I edited the title to reflect this. A: You are missing a } at the end there, are you not? { "add": [{"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"} }, {"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"} }] } A: According to this site: http://jsonformatter.curiousconcept.com/ No, it is not valid JSON. Here it is, cleaned up for you: { "add": [ {"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"} }, {"doc": {"id" : "TestDoc1", "title" : "test1"} }, {"doc": {"id" : "TestDoc2", "title" : "another test"} } ] } A: Use - curl http://localhost:8983/solr/update/json -H 'Content-type:application/json' -d ' { "add": {"doc": {"id" : "TestDoc1", "title" : "test1"} }, "add": {"doc": {"id" : "TestDoc2", "title" : "another test"} }, "add": {"doc": {"id" : "TestDoc1", "title" : "test1"} }, "add": {"doc": {"id" : "TestDoc2", "title" : "another test"}} }' OR curl http://localhost:8983/solr/update/json -H 'Content-type:application/json' -d ' [ {"id" : "TestDoc1", "title" : "test1"}, {"id" : "TestDoc2", "title" : "another test"}, {"id" : "TestDoc1", "title" : "test1"}, {"id" : "TestDoc2", "title" : "another test"} ]'
{ "language": "en", "url": "https://stackoverflow.com/questions/7560552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I query mysql data with array I have 2 tables colorcode & users colorcode ID colorid colorname ------------------------ 1 1 yellow 2 2 black 3 3 red 4 4 white users ID userid colorid ------------------------ 1 1 1,2 2 2 3,4 3 3 1,3,4 4 4 1 How do I retrieve & query individual colorid $aa = $db->query("SELECT * FROM colorcode"); $colors = array(); while ($colordata = mysql_fetch_assoc($aa)) { $colors[] = $colordata["colorid"]; } Let's say I want query which users have yellow color & what it's the statement should I use for users SELECT .. FROM users WHERE colorid .... A: It's a bad design... since you're trying to access the individual color_ids in the user table, but have stored them as a comma-separated list, you canot have the database do a normal join for you - you've killed off the main point of using a relational database by making it impossible to for the database to do the relating for you. However, since you're on mysql, you're in luck - mysql has a function for cases like this: SELECT users.ID, userid, GROUP_CONCAT(colorcode.colorname) FROM users LEFT JOIN colorcode ON FIND_IN_SET(colorcode.ID, users.colorid) GROUP BY users.id A: SELECT * FROM users WHERE colorid LIKE "%1%" But what I would really do is make a link table from users to colors: usersToColors: ID userid colorid ------------------------ 1 1 1 2 1 2 3 2 3 4 2 4 ... Then you could do: SELECT * FROM users u, usersToColors utc WHERE u.userid = utc.userid AND utc.colorid = 1; Or even: SELECT * FROM users u, usersToColors utc, colors c WHERE u.userid = utc.userid AND utc.colorid = c.colorid AND c.colorname = "yellow";
{ "language": "en", "url": "https://stackoverflow.com/questions/7560555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OpenGL VBO shader I have a 2D VBO object that represent points in 2D space. What is the best way to draw an arbitrary shape at that point? Lets say I wanted to draw a red 'X' at each. Can I use a shader to do this? A: You don't neccessarily need a special shader for that, you might just use point sprites. This would basically mean to draw the VBO as a point set (using glDrawArrays(GL_POINTS, ...)) and enabling point sprites to draw a textured square (with a texture of the 'X') at the position of each point, assuming a point size of more than 1 pixel. For actually generating geometry at the location of each point you could use the geometry shader. This way you also render the VBO as point set and generate two lines (the 'X') or whatever geometry for each point inside the geometry shader. An alternative to the geometry shader are instanced arrays (requiring the same GL3/DX10 hardware as neccessary for geometry shaders). This way you draw multiple instances of the 'X' shape and source the instances' individual positions from the point VBO by using an attribute whose index is advanced once per instance. The last alternative would be to generate the shapes' geometries manually on the CPU, so that you end up with a line set or a quad set conatining all the 'X's as lines or sprites or whatever. But the easiest (and maybe fastest, not sure about that) way should be the point sprite approach mentioned first, as their usual clipping problems shouldn't be that much of a problem in your case and you don't seem to need 3d shapes anyway. This way you neither need to generate the geometry yourself on the CPU, nor do you need special shaders or GL3/DX10 hardware (although this is quite common nowadays). All you need is a texture of the shape and enable point sprites (which should be core since GL 1.5). If all these general ideas don't tell you anything, you might want to delve a little deeper into OpenGL and real-time computer graphics in general.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Templating ItemControl items without using ItemsSource I am trying to build a custom Silverlight ItemsControl. I want the users of this control to add items using XAML. The items will be other UI elements. I would like to add a margin around all added items and therefore I want to add an ItemTemplate. I am trying to do this using the ItemsControl.ItemTemplate, but that does not seem to be used when binding to elements in XAML, i.e using the ItemsControl.Items property. However, if I use the ItemsControl.ItemsSource property, the ItemTemplate is used. Is there anyway to use the ItemTemplate even though I am not assigning ItemsSource? This is my code so far <ItemsControl x:Class="MyControl"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate > <toolkit:WrapPanel/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel Margin="20" Background="Red"> <TextBlock Text="Test text"/> <ContentPresenter Content="{Binding}"/> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.Template> <ControlTemplate> <Border> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <ItemsPresenter x:Name="ItemsPresenter"/> <Button Command="{Binding SearchCommand}"/> </Grid> </Border> </ControlTemplate> </ItemsControl.Template> </ItemsControl> And when I use my control <MyControl> <Button Content="Button"/> <Button Content="Button"/> </MyControl> This got me a display of the items, with a wrap panel layout but no applied data template. Then I found this post that mentioned two methods to override. Son in my code-behind of the class I have now protected override bool IsItemItsOwnContainerOverride(object item) { return false; } protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); ((ContentPresenter)element).ContentTemplate = ItemTemplate; } BUT - this gets me two items, with the style (I.E a red textblock) but no actual content. The buttons in the list are not added. It feels like I am doing something wrong - any pointers on what? Thanks! A: If all you want to do is add some margin then you can just set the ItemContainerStyle instead of specifying a template: <ItemsControl> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="FrameworkElement.Margin" Value="10" /> <!-- or whatever margin you want --> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> This will allow you to set any property of the container control (which in the case of an ItemsControl will be a ContentControl) through the style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Form submit simulation - Javascript menu I'd like to get contents of a website using JavaScript menu. I need to simulate clicks (or typing javascript:gotoPage("p10"); into a browser) on menu links to be able to move from one page to another. The website uses a form activated by JS. It's probably not possible to go to another page by entering URL, because there are some hidden fields (something like hash- it's dependent on time and the page #). That's why I have to simulate a browser using user. Basically the process will look like this: while (any_content) { file_get_contents(); clickalink(); } Can cURL or JSON be used for this task? A: If you're using PrototypeJS you could perhaps use the event.simulate library to simulate clicks on links. https://github.com/kangax/protolicious/blob/master/event.simulate.js $('link_id').simulate('click');
{ "language": "en", "url": "https://stackoverflow.com/questions/7560565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect type of Form Field in Template in Django Hi guys i have simple Django Form , but I need to get type of this field elements and I made some special operations according to this. Is there an easy way to get type of Form Field in Django Template? Any help will be appreciated. A: For your actual use case the image widget from the django-form-utils package should be a good match. On more general level: If you simply want to modify the html generated by a standard widget you should subclass the widget and tweak the render-method. Take a look at this blog post to get the basic idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Fuzzing the Linux Kernel: A student in peril. I am currently a student at a university studying a computing related degree and my current project is focusing on finding vulnerabilities in the Linux kernel. My aim is to both statically audit as well as 'fuzz' the kernel (targeting version 3.0) in an attempt to find a vulnerability. My first question is 'simple' is fuzzing the Linux kernel possible? I have heard of people fuzzing plenty of protocols etc. but never much about kernel modules. I also understand that on a Linux system everything can be seen as a file and as such surely input to the kernel modules should be possible via that interface shouldn't it? My second question is: which fuzzer would you suggest? As previously stated lots of fuzzers exist that fuzz protocols however I don't see many of these being useful when attacking a kernel module. Obviously there are frameworks such as the Peach fuzzer which allows you to 'create' your own fuzzer from the ground up and are supposedly excellent however I have tried repeatedly to install Peach to no avail and I'm finding it difficult to believe it is suitable given the difficulty I've already experienced just installing it (if anyone knows of any decent installation tutorials please let me know :P). I would appreciate any information you are able to provide me with this problem. Given the breadth of the topic I have chosen, any idea of a direction is always greatly appreciated. Equally, I would like to ask people to refrain from telling me to start elsewhere. I do understand the size of the task at hand however I will still attempt it regardless (I'm a blue-sky thinker :P A.K.A stubborn as an Ox) Cheers A.Smith A: I think a good starting point would be to extend Dave Jones's Linux kernel fuzzer, Trinity: http://codemonkey.org.uk/2010/12/15/system-call-fuzzing-continued/ and http://codemonkey.org.uk/2010/11/09/system-call-abuse/ Dave seems to find more bugs whenever he extends that a bit more. The basic idea is to look at the system calls you are fuzzing, and rather than passing in totally random junk, make your fuzzer choose random junk that will at least pass the basic sanity checks in the actual system call code. In other words, you use the kernel source to let your fuzzer get further into the system calls than totally random input would usually go. A: "Fuzzing" the kernel is quite a broad way to describe your goals. From a kernel point of view you can * *try to fuzz the system calls *the character- and block-devices in /dev Not sure what you want to achieve. Fuzzing the system calls would mean checking out every Linux system call (http://linux.die.net/man/2/syscalls) and try if you can disturb regular work by odd parameter values. Fuzzing character- or block-drivers would mean trying to send data via the /dev-interfaces in a way which would end up in odd result. Also you have to differentiate between attempts by an unprivileged user and by root. My suggestion is narrowing down your attempts to a subset of your proposition. It's just too damn broad. Good luck - Alex. A: One way to fuzzing is via system call fuzzing. Essentially the idea is to take the system call, fuzz the input over the entire range of possible values - whether it remain within the specification defined for the system call does not matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: ParseException: Expected end of text I am trying to parse text using pyparsing. My function is shown below. Firstly, I construct a list containing all the terms in my dictionary (a dictionary of commonly used terms in my website). Then I set my grammar to be this list of commonly used words. Then I construct the ZeroOrMore object with the grammar. Finally, I parse the string and I should get the matches found in my string. However, it throws a ParseException instead complaining that end of text was expected. def map_dict_words(self, pbody): dict_terms = [term.term for term in Dictionary.objects()] look_for_these = oneOf(dict_terms, caseless=True).setResultsName("dict_words") parseobj = ZeroOrMore(look_for_these) matches = parseobj.parseString(pbody, parseAll=True) print matches According to the FAQ in pyparsing's homepage http://pyparsing-public.wikispaces.com/FAQs if I want the parser to parse the entire string I should either put StringEnd() in my grammar or use the optional arg parseAll=True. If I remove parseAll=True from my code it works but it doesn't parse the entire string. Any ideas? A: Instead of parseString, you may be more interested in using scanString or searchString. Unlike parseString, these functions skim through the input looking for matches, instead of requiring a complete match of all the content in the input string. scanString returns a generator, so for large input text, will give you matches as they are found: for toks,start,end in look_for_these.scanString(pbody): print toks[0], start, end searchString is just a simple wrapper around scanString (drops start and end locations, though): for t in look_for_these.searchString(pbody): print t[0] A: Think of pyparsing as a more advanced regular expression. When you pass it parseAll=True, it expects to match the entire string, qualifying each and every byte to some part of the grammar. Your grammar however only mentions some of the words that will appear in the string. You have to account for the rest of them somehow. In other words, assuming that popular words are "parrot", "hovercraft", "eels" and "fjords", you have built an equivalent of the following regular expression: /^(?P<dict_words>eels|fjords|hovercraft|parrot)*$/
{ "language": "en", "url": "https://stackoverflow.com/questions/7560583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Newly created graphics object only showing after resize of frame This is a continuation from this post I have a set of random sized graphics adding and drawing onto a JPanel component. I have a button that is adding a new draw object to the same JPanel but is not displaying until i re-size the window. I have added the EDT information mentioned in this post and have also called the repaint() method on the component. I am not using an ArrayList yet, as suggested by Hovercraft, but I will. My brain needs to understand things slowly as i go. Thank you. The code is in two classes. import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; public class ZombieDance extends JComponent { JFrame canvas = new JFrame(); JPanel actionPanel = new JPanel(); JButton newZombie = new JButton("Add new Zombie"); ZombieDance(){ //create a couple default zombies buildGUI(); Random rand = new Random(); int i,x,y,w,h; //add zombies to my canvas for (i=1;i<8;i++) { float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat(); x = rand.nextInt(50); y = rand.nextInt(50); w = rand.nextInt(50); h = rand.nextInt(50); canvas.add(new Zombie(x,y,w,h,r,g,b)); } } //prep the canvas void buildGUI(){ actionPanel.add(newZombie); canvas.add(actionPanel); canvas.setLayout(new GridLayout(3,3)); canvas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); canvas.setSize(400,400); canvas.setBackground(Color.WHITE); canvas.setVisible(true); newZombie.addActionListener(new NewZombieClickHandler()); } public class NewZombieClickHandler implements ActionListener{ public void actionPerformed(ActionEvent e){ Random rand = new Random(); int x,y,w,h; float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat(); x = rand.nextInt(50); y = rand.nextInt(50); w = rand.nextInt(50); h = rand.nextInt(50); canvas.add(new Zombie(x,y,w,h,r,g,b)); canvas.repaint(); } } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { new ZombieDance(); } }); } } Second class import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; public class Zombie extends JPanel{ private int x,y,w,h; private float r,g,b; Zombie(int argx, int argy, int argw, int argh, float argr, float argg, float argb){ x = argx; y = argy; w = argw; h = argh; r = argr; g = argg; b = argb; } public Dimension getPreferredSize() { return new Dimension(20,20); } protected void paintComponent(Graphics gr) { super.paintComponent(gr); //g.drawString("Drawing canvas...",10,20); gr.setColor(new Color(r,g,b)); gr.fillRect(x,y,h,w); } } A: I have a button that is adding a new draw object to the same JPanel but is not displaying until i re-size the window When you add a component to a visible GUI the code should be: canvas.add(...); canvas.validate(); //canvas.repaint(); // sometimes needed (editor: changed to validate) A: I tried myself and i found that paintChildren() method resolved the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Will my WCF service be scaleable using a singleton? My ASP .Net C# web application allows its users to send files from their account on my server to any remote server using FTP. I have implemented a WCF service to do this. The service instantiates a class for each user that spawns a worker thread which performs the FTP operations on the server. The client sends a command to the service, the service finds the worker thread assigned to the client and starts the FTP commands. The client then polls the service every two seconds to get the status of the FTP operation. When the client sends the "disconnect" command, the class and the worker thread doing the FTP operations is destroyed. The FTP worker thread needed to persist between the client's queries because the FTP processing can take a long time. So, I needed a way for the client to always get the same instance of the FTP class between calls to the service. I implemented this service as a singleton, thus: [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class UserFtpService : IUserFtpService { private SortedDictionary<string, UserFTPConnection> _clients = new SortedDictionary<string, UserFTPConnection>(); ... } Where "UserFTPConnection" is the class containing the worker thread and the user's account name is used for the indexing in the dictionary. The question I have is this: In the books I have read about WCF, the singleton instance is called "the enemy of scalability." And I can see why this is so. Is there a better way to make sure the client gets the same instance of UserFTPConnection between queries to the WCF service other than using a singleton? A: Actually here your first problem is synchronizing the access to this static object. Dictionary<TKey, TValue> is not thread safe so you must ensure that only one thread is accessing it at the same time. So you should wrap every access to this dictionary in a lock, assuming of course you have methods that are writing and others that are reading. If you are only going to be reading you don't need to synchronize. As far as singleton being the enemy of scalability, that's really an exaggerated statement and pretty meaningless without a specific scenario. It would really depend on the exact scenario and implementation. In your example you've only shown a dictionary => so all we can say is that you need to ensure that no thread is reading from this dictionary while other is writing and that no thread is writing to this dictionary while other thread is reading. For example in .NET 4.0 you could use the ConcurrentDictionary<TKey, TValue> class which is thread safe in situations like this. One thing's for sure though: while the singleton pattern might or might not be an enemy of scalability depending on the specific implementation, the singleton pattern is the arch-enemy of unit testability in isolation. A: If you are going to use a singleton, I'd recommend also setting ConcurrencyMode to ConcurrencyMode.Multiple. For example... [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)] public class UserFtpService : IUserFtpService { } If you don't do this, your WCF service will be a singleton but only allow one thread to access at a time, which would certainly effect performance. Of course you will need to ensure thread safety of collections (as in previously mentioned answer).
{ "language": "en", "url": "https://stackoverflow.com/questions/7560586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Supress grep output but capture it in a variable I'm trying to get the following line to work WERRORS=`echo $VALPG | grep -q -s -o -m 1 '\<[0-9]* Errors'` What I want is that the result of grep go into WERRORS variable but not echo in the terminal. So i use -q, but then WERRORS is empty A: If grep sends any error messages, they go to the error output, which is not captured by the backticks. If you need this output in a variable (which is somewhat problematic, because it's often localized), redirect it using 2>&1: WERRORS=`echo $VALPG | grep -s -o -m 1 '\<[0-9]* Errors' 2>&1` A: WERRORS=`echo $VALPG | grep -s -o -m 1 '\<[0-9]* Errors'` A: kent$ val=abcpc kent$ a=$(echo $val|grep -o -m 1 -s 'pc') kent$ echo $a pc
{ "language": "en", "url": "https://stackoverflow.com/questions/7560587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding previously deleted code in RTC later? Conventional wisdom says to delete code once you don't need it -- as opposed to leaving it in the codebase as a comment -- because you can always find it later in the repository. Let's say I need a line of code from the past which I remember to contain a very memorable substring ("XYZ", for discussion's sake). What are my options for finding the previously deleted code using the Visual Studio 2010 Rational Team Concert (3.x) client? Can I search only the revisions of a single file (I might not know what file it was in)? Can I search quickly/easily across many files (w/o pulling those files out of the repository)? A: I am not sure there is an easy way to get back the exact file with that missing string. You can select show the history on a component of a Stream, in order to "Show the History files" for a given change set. From there, you can do some "compare with Local File". However, the Visual Studio integration might be less complete than the eclipse one, as this thread shows (where the "Show History" shows only the history of Deliver's). Even though the following article uses the Eclipse GUI, have also a look at "Practicing source control archaeology with Rational Team Concert", which has other ideas for you to try.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Accessing Smartcards from a Web Site A number of Countries have implemented electronic id cards, that their citizens can use to securely access online facilities like banking. I am interested in learning how to support these cards, but tracking down documentation on how to do this from an IIS hosted website is a real PITA: In MSDN for example the bulk of the smartcard documentation covers the end to end scenario of linking smart cards to domain logins in a corporate environment. I am just trying to authenticate the holder of - for example, a Spanish DNI-e card and perform an OSCP validation of the card via http://ocsp.dnie.es/ Now, its seems that, rather than explicitly detecting the smart card insertion, I need to create a login page on the server with SSL client authentication forced - but how do I configure one request to require ssl client authentication and to pick the correct client certificate? A: Indeed, configure your server to require client certificate authentication. You will receive the client authenticator details in the headers. You can force to only accept specific certificates by configuring the public root certificate of those client certificates on the server and removing all others that you are not interested in. In the authentication request going from your server to the browser, only the root certificates are listed that are trusted on your server system. The client browser will only offer client certificates that are somehow related to that root. A: In an Microsoft environment you would configure your IIS to require SSL on your login page. Additionally, require SSL client authentication using a certificate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery mobile doesnt apply styles after ajax load My phonegap app makes a simple .load call when a button is clicked to put ajax imported info into the ajaxarea1 div. However, it is not being styled as a collapsible type object jquery mobile creates after it is loaded from ajax. simplified js here: $('#ajaxarea1').load('http://server.net/droiddev/backbone1/index.php/welcome/', function(){ $('#ajaxarea1').css("height","auto"); }); Here is the php that is returned when .load goes to the url <?php foreach ($query as $row) { echo '<div data-role="collapsible">'; echo '<h3>'.$row->headline.'</h3>'; echo '<p>'.$row->article.'</p>'; echo '</div>'; } ?> Some simliar questions I've found on here didnt help me much. Here is some js I found that I might be part of issue $('#ajaxarea1').collapsible().page(); Thanks Full HTML: <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js"></script> <script type="text/javascript" charset="utf-8" src="main.js"></script> <style type="text/css"> #ajaxarea1{width:308px; display:block; margin:2px auto; height:50px; overflow:hidden;} #errorarea ul li{ color:red;} .center{text-align:center;} </style> </head> <body onload="init()" style=""> <!-- Start of first page --> <div data-role="page" id="firstpage" data-title="Page firstpage" data-theme="d" > <!-- <div data-role="header" data-theme="d" data-position="fixed"> </div> --> <a href="#" data-role="button" style="margin-top:15px;float:right;" data-iconpos="notext" data-icon="home">Home</a> <div data-role="content"> <p>I'm first in the source order so I'm shown as the page.</p> <p>View internal page called <a href="#secondpage" data-role="button" data-theme="d" data-transition="slide">2nd page</a></p> <a href="#addart" data-role="button" data-theme="d" >Add Article</a> <div id="ajaxarea1"></div> <button type="button" id="calcbtn" onclick="change_ajaxarea1()">Ajax call</button> </div><!-- /content --> </div> </div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="thanks" data-theme="d"> <p> Your article has been received!!</p> </div> <div data-role="page" id="secondpage" data-theme="d" data-title="Page secondpage ya firstpagel!"> <div data-role="header" data-theme="d"> <h1> <a href="#" data-role="button" style="float:left;" data-rel="back" data-icon="arrow-l" data-theme="d" data-iconpos="notext">Back</a> </h1> </div><!-- /header --> <div data-role="content"> <p>This is the second page of content.</p> <div data-role="collapsible"><!-- this works because its not loaded by ajax --> <h3>Result from Ray</h3> <p id="resultBlock"></p> </div> </div><!-- /content --> <!--<div data-role="firstpageter" data-position="fixed"> <p style="width:100%;margin:0 auto;display:block;padding:5px;">The firstpageter is over here and i hope this doesnt get cut off. </p> </div> --> <!-- /firstpageter --> </div><!-- /page --> <!-- Start of third(add) page --> <div data-role="page" id="addart" data-theme="d" data-title="Page secondpage ya firstpagel!"> <div data-role="header" data-theme="d"> <h1>Add article</h1> <a href="#" data-role="button" style="float:left;" data-rel="back" data-icon="arrow-l" data-theme="d" data-iconpos="notext">Back</a> </div><!-- /header --> <div data-role="content"> <form id="addform" style="text-align:center;"> <div id="errorarea"><ul> </ul></div><label for="Headline">Headline</label><br/><input type="text" name="Headline" title="Enter a title for the Headline at least 5 chars" class="required" id="headline" style="margin: 10px auto 20px auto;" placeholder="enter article headline.."></input> <br/> <label for="Article">Article</label><br/><textarea cols="40" rows="8" name="Article" id="article" class="required" title="Enter a article" name="textarea" style="margin: 10px auto 20px auto;" placeholder="enter article content.." id="textarea"></textarea> <br/> <input data-inline="true" style="display:inline-block;clear:both;text-align:center;" type="submit" value="Add Article" onclick="addarticle()"></input> </form> </div> <!-- /content --> <!--<div data-role="firstpageter" data-position="fixed"> <p style="width:100%;margin:0 auto;display:block;padding:5px;">The firstpageter is over here and i hope this doesnt get cut off. </p> </div> --> <!-- /firstpageter --> </div><!-- /page --> </body> </html> Full Javascript: function change_ajaxarea1(){ $('#ajaxarea1').load('http://server.net/droiddev/backbone1/index.php/welcome/', function(){ $('#ajaxarea1').css("height","auto").collapsible(); }); } function postarticle(){ $.post("http://server.net/droiddev/backbone1/", { headline: "John", article: "2pm" } ); } function addarticle(){ //$("#addform").validate(); var truth=$("#addform").validate().form() // alert(truth); if(truth==true){ var headlinetemp=$('#headline').val(); var articletemp=$('#article').val(); navigator.notification.activityStart(); $.ajax({ type:'POST', url: "http://server.net/droiddev/backbone1/index.php/welcome/addarticle/", data: { 'headline': headlinetemp, 'article': articletemp}, success:function(){ $('#headline').val(''); $('#article').val(''); $.mobile.changePage($('#thanks'), { transition: "slide"}); navigator.notification.activityStop(); }, error:function(xhr){ navigator.notification.activityStop(); alert('Error: Article was not added.'); } }); } else{alert('Please Correct the Form');} } function init(){ var container = $('#errorarea'); $('#addform').validate({ errorContainer: container, errorLabelContainer: $("ul", container), wrapper: 'li', meta: "validate" }); } function addarticletransition(){ var headlinetemp=$('#headline').val(); var articletemp=$('#article').val(); $.mobile.changePage( "http://server.net/droiddev/backbone1/index.php/welcome/addarticle/", { type: "post", data: { 'headline': headlinetemp, 'article': articletemp} }); } UPDATED ++ A: Try calling the collapsible() and page() methods after you load the dynamic content: $('#ajaxarea1').load('http://server.net/droiddev/backbone1/index.php/welcome/', function(){ $('#ajaxarea1').css("height","auto").collapsible().page(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7560597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Are microframeworks intended for large code bases? I ask about the longevity of microframeworks like Flask, Bottle, and expressjs. Advantages: small, fast, manageable. Are they intended to be replaced as code complexity and user base grow? Also asked: should they be replaced with a full framework like Django or Pyramid, or are microframeworks the new standard? A: Well, it kind of depends on what you mean by growth. Let's look at two possibilities: * *User growth. If you're building an application with fairly fixed features which you expect to have a rapidly expanding user-base (like Twitter), then a microframework may be ideally suited for scalability since it's already stripped down to the bare essentials + your application code. *Feature growth. If you have a site which you're expecting to require rapid addition of many discrete and complex yet generic features (forums, messaging, commerce, mini-applications, plugins, complex APIs, blogs), then you may save time by using a full-featured framework like Django or Ruby on Rails. Basically, the only reason a microframework might be unsuitable for your application in the long term is if you think you would benefit from plug-and-play functionality. Because fully-featured frameworks are higher-level than microframeworks, you'll often find fully-featured solutions as plugins right out of the box. Blogs, authentication, and so on. With microframeworks you're expected to roll your own solutions for these things, but with access to a lot of lower-level functionality through the community. A: It depends on what the (micro)framework supports, as well as the amount of documentation provided for it. For example, a site using Flask needs a database for storing data. Even though Flask does not have a database extension built in, there are extensions available for it. A: If the microframework can handle it why replace it with something else?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Explode data / transform it to the PHP array My data variable is following: canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4 I need it to transform to an array which should look following: $arr = array( "canv" => array("2", "3", "4", "5"), "canp" => array("2", "3", "4"), "canpr" => array("2", "3", "4"), "canpp" => array("2", "3", "4"), "all" => array("2", "3", "4") ); Can you help me? A: The following should do the trick: $data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4"; $items = explode(":::", $data); $arr = array(); foreach($items as $item) { $item = explode(" = ", $item); $arr[$item[0]] = explode(",", $item[1]); } A: $data = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4"; $result = array(); foreach (explode(':::', $data) as $line) { list($part1, $part2) = explode(' = ', $line); $result[$part1] = explode(',', $part2); } A: $orig_str = 'canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4'; $parts = explode(':::', $orig_str); $data = array() foreach($parts as $key => $subparts) { $data[$key] = explode(',', $subparts); } A: I would try something like this: this is not tested, try to print_r to debug $string = "canv = 2,3,4,5:::canp = 2,3,4:::canpr = 2,3,4:::canpp = 2,3,4:::all = 2,3,4"; $pieces = explode(':::',$string); $result = array(); foreach($pieces AS $piece) { $tmp = explode(' = ',$piece); $result[$tmp[0]] = explode(',',$tmp[1]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The correct way to dismiss a MFMailComposeViewController I'm at my wit's end. I need to dismiss an MFMailComposeViewController when my app transitions to the background and I can't do it. It ends up creating an awkward application state. Is there a way to handle this programmatically? Perhaps force the view controller to put the email into the Drafts folder and dismiss without animating? EDIT: Calls to - dismissModalViewControllerAnimated: don't work as expected. The awkward application state I'm talking about is my main view being redrawn over top of the email composer when the application returns from the background. The modal is never dismissed and that email composer is never accessible again. EDIT: Code in my initializer: // For compatibility with iOS versions below 4.0 if (&UIApplicationDidEnterBackgroundNotification != NULL) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackgroundNotification:) name:UIApplicationDidEnterBackgroundNotification object:nil]; } Code in my background-entry handler: - (void) applicationDidEnterBackgroundNotification:(NSNotification *)note { // Do some other stuff here // According to the docs, calling the method like this closes all // child views presented modally [self dismissModalViewControllerAnimated:NO]; } A: I have reproduced a simple application with the code you have above. The mail composer is dismissed properly when the application enters the background. I can only assume therefore that the //Do some other stuff here section of your code is doing too much stuff and the OS is shutting you down before you have chance to dismiss the composer. According to the docs: You should perform any tasks relating to adjusting your user interface before this method exits but other tasks (such as saving state) should be moved to a concurrent dispatch queue or secondary thread as needed. Because it's likely any background tasks you start in applicationDidEnterBackground: will not run until after that method exits, you should request additional background execution time before starting those tasks. In other words, first call beginBackgroundTaskWithExpirationHandler: and then run the task on a dispatch queue or secondary thread. Perhaps you should move your other stuff to a different thread or request extra time? If you remove the other stuff, does the composer dismiss correctly?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Actionscript Duck-typing I'm overriding a protected function in a subclass. Let's say I have two classes, Apple and Fruit. I have all variables in place, this is just a simplified version. class FruitBasket protected function getRandom():Fruit { // return random piece of fruit } class AppleBasket extends FruitBasket protected override function getRandom():Apple { // return random apple } class Fruit class Apple extends Fruit Example is trivial. The problem is that the type of the getRandom function depends on its own type. One returns an apple, the other returns a fruit. Of course I get errors about override and coercion. I've tried returning a Fruit instead of an Apple, but then the object is not an apple, therefore it has no Apple-specific properties. The problem is in ducktyping. There's a third class I cannot change, that executes the getRandom() function on each object, and I need the Apples to be something slightly different. How can I override the getRandom function in Apple, so that it returns apples, rather than fruit? A: This is a circle-ellipse problem. I would simply not override the function; rather I would rename the function to be more specific. So rename it to getRandomApple() in AppleBasket. Your semantics are getting a little muddy so I would make things separate and clearer. It's too bad you can't change the function name in FruitBasket, because I would change that to getRandomFruit() to make the semantics clearer. A: The equivalent to duck typing in AS3 would be the "*" or "Object" type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: matching container element width with that of child I want to have a setup like this: <div id="block"> <div class="btn">2</div> <div class="btn">1235e</div> <div class="btn">really long one</div> </div> jsfiddle: http://jsfiddle.net/cutcopypaste/3uu5Q/ Where the btns and block div get their width based on the content. Just like it appears in the fiddle, except that the width of the btns are based on their text rather than their container I cannot use a table because I need to be able to apply styling to get vastly different appearance, so I need the html markup to stay basically the same. If it's absolutely necessary I could apply some js. I tried a couple different ways of displaying, but not sure how to acheive this. I don't wish to hard-code any widths as the content will be changing, and I need it to work in older versions of IE (though I can use libraries like IE9.js). A: Here's an example of how the #block will be sized to be as wide as its longest button: #block { float: left; } .btn { float: left; clear: both; } The floated elements will expand only to their content's width. It's assuming you want each button on its own line. If you want the buttons to flow together, remove the clear:both from the .btn rule. However if you do want them all on one line you'll have to be aware of float drop. This will happen if the widths of all your buttons added together is greater than the available width. In this case, the rightmost button will drop down below the other buttons. Update: based on OP's comment, here's the CSS for a table cell style where #block and all .btn elements expand to the widest button's width: #block { display: inline-block; } .btn { display: block; } Along with an example. A: Where the btns and block div get their width based on the content. I'm not 100% sure whether I get you right, but using display:inline elements like spans instead of <div>s should solve your problem. A: make them float or inline, that way they won't act like blocks (wont be 100% width).
{ "language": "en", "url": "https://stackoverflow.com/questions/7560622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem using SQL Server CE with Entity Framework code-first and ASP.NET MVC 3 and mvc miniprofiler I am attempting to create an ASP.NET MVC 3 application using C#, Entity Framework 4.0 code-first and SQL Server CE, and the automated scaffolding. Everything works fine until I try to actually use a page that connects to the SQL Server CE database. My connection in the web.config is this <add name="BRX" connectionString="Data Source=|DataDirectory|BRX.sdf" providerName="System.Data.SqlServerCe.4.0"/> My model class looks like this using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace BizRadioXInternal.Models { public class KeyWordEmail { [Key] public int KeywordEmailID { get; set; } public string Name { get; set; } public string Keyword { get; set; } public string Link { get; set; } public string EmailAddress { get; set; } } } and my data context class looks like this using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using BizRadioXInternal.Models; namespace BizRadioXInternal.Models { public class BRX : DbContext { public virtual DbSet<KeyWordEmail> KeyWordEmails { get; set; } } } and every time I try go to a page that touches the database (like a standard index page) I get the following error The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) Here is the stack trace [FileLoadException: The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)] System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent) +0 System.Reflection.AssemblyName..ctor(String assemblyName) +80 System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInvariantName(DbConnection connection) +312 System.Data.Entity.ModelConfiguration.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest) +63 System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) +157 System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) +62 System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input) +117 System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +407 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18 System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +62 System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +15 System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +40 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315 System.Linq.Enumerable.ToList(IEnumerable`1 source) +58 BizRadioXInternal.Controllers.KeyWordEmailController.Index() in D:\Creative Plumbing\BusinessRadioX\BizRadioXInternal\BizRadioXInternal\BizRadioXInternal\Controllers\KeyWordEmailController.cs:21 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8963149 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 What on earth am I doing wrong? Update: The root cause of the problem seems to be in the global.asax file. I'm using the MVC Miniprofiler, and if I comment out "MiniProfilerEF.Initialize();" everything works fine. Here is the contents of the global.asax file using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using MvcMiniProfiler; namespace BizRadioXInternal { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public void Application_BeginRequest() { if (Request.IsLocal) { MiniProfiler.Start(); } } public void Application_EndRequest() { if (Request.IsLocal) { MiniProfiler.Stop(); } } public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); MiniProfilerEF.Initialize(); } } } A: This is an issue with EF 4.1 update 1 which breaks all profilers See: * *http://code.google.com/p/mvc-mini-profiler/issues/detail?id=100 *http://weblogs.asp.net/fbouma/archive/2011/07/28/entity-framework-v4-1-update-1-the-kill-the-tool-eco-system-version.aspx *http://ayende.com/blog/75777/entity-framework-4-1-update-1-backward-compatibility-and-microsoft Mark Young just implemented a SQL CE specific workaround in the main trunk, use: // only ever set to false when profiling SQL CE MvcMiniProfiler.Initialize_EF42(supportExplicitConnectionStrings: false);
{ "language": "en", "url": "https://stackoverflow.com/questions/7560624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Msdropdown opening only with a "slideDown" animation The MsDropDown located at: https://github.com/jgb146/ms-Dropdown/blob/master/msdropdown/js/jquery.dd.js only opening with a "slideDown" animation. How I can fix that to open with a slideUp animation? Anyone have a CSS or jQuery tricks? My example: <div> <html:select property="genericLayoutForm.chart" style="width:300px; height:82px" styleClass="mydds" styleId="chart"> <html:optionsCollection styleClass="mydd" property="genericLayoutForm.charts" /> </html:select> </div> Does someone have a solution for it? Maybe the creator of MsDropDown could create some new parameters to enable users to use, for example: slideUpAnimation or slideDownAnimation. Thanks a lot! A: var oDropdown = $("#dropdownId").msDropdown(openDirection:alwaysUp ).data("dd");
{ "language": "en", "url": "https://stackoverflow.com/questions/7560626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Play can't read Heroku config vars when parsing application.conf I am deploying an app written with Play! Framework 1.2.3 to heroku (cedar stack) and I am setting some environment variables via heroku config:add DB_NAME="FOO" These are set OK (seen via heroku config --app appname). These are read from the code both via manual calls to System.getenv() and substitutions done by play when reading application.conf via the morphia.db.name=${DB_NAME} mechanism. This tactic works well locally, but on heroku the environment variables are seemingly not read and the push to heroku fails since it can't substitute the variables. Warning emitted by play is: WARNING: Cannot replace DB_NAME in configuration (morphia.db.name=${DB_NAME}) And it dies because it can't connect to the database, which is a fatal error. It also reports in the error as trying to connect to ${HOST}:${PORT}, so no substitution is performed here. Am I missing something here, or is this simply not working for Play! apps on heroku at present? How should this be done? A: The push to Heroku initiates a precompile of your Play application which, in turn, reads your application.conf file. Unfortunately, the Heroku configuration variables aren't available at build time so you'll see those warnings that you mentioned: WARNING: Cannot replace VALUE in configuration (key=${VALUE}) However, this shouldn't cause the push to fail. Nor should it cause your app to fail to run. At runtime, Play re-reads application.conf and the configuration variables will be present and their values will get replaced. It's hard to tell exactly what's wrong in this case. One thing you could try is running the Play commands just as Heroku does it and see what you get: $ play precompile $ play run --http.port=5000 --%prod -Dprecompiled=true Note that the separate precompile step and the prod framework id are different then if you are just running your app locally like this: $ play run You can also log a ticket with Heroku and someone can take a look at your app. At the very least, we need to get rid of those WARNING messages because you are not the first person to notice this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CoffeeScript, Why do I need the explicit return on a conditional I was trying to learn CoffeeScript, and made this simple class as first try: class test fib: (x) -> x if x == 0 || x == 1 (this.fib x-1) + (this.fib x-2) t = new test alert(t.fib(6)); This code doesn't work because it gets compiled without a return statement in the if statement. This works: fib: (x) -> return x if x == 0 || x == 1 (this.fib x-1) + (this.fib x-2) Why do I need the explicit return ? Based on the language description, especially http://jashkenas.github.com/coffee-script/#expressions, I expected the x expression to be converted to a return by the compiler. A: Why would you expect the x expression to be converted to a return? Only the last expression in a method or function is converted to a return. In Jeremy's if/then/else example, there are two possible last expressions, and the coffeescript parser understands to be the case in an if/then/else, which is not what you have here: instead, you have on expression with no lvalue, followed by another perfectly valid expression. (There's some discussion as to whether or not the if statement itself is an expression; arguably, it should be read as one, but the compiled output of an if/then/else contains a return keyword in both the then clause and the else clause.) The compiler can't read your mind. It doesn't know what your intent is there with that rvalue x expression. All it knows is that another perfectly valid expression in the same scope follows it. To get the effect you want: if x == 0 or x == 1 x else (@fib x-1) + (@fib x-2) Or one-liner: if x == 0 or x == 1 then x else (@fib x-1) + (@fib x-2) A: It's because CoffeeScript doesn't know, for sure, that the x if x == 0 || x == 1 line is a return statement. What you want is class test fib: (x) -> if x == 0 || x == 1 x else @fib(x-1) + @fib(x-2) Which compiles into (function() { var test; test = (function() { function test() {} test.prototype.fib = function(x) { if (x === 0 || x === 1) { return x; } else { return this.fib(x - 1) + this.fib(x - 2); } }; return test; })(); }).call(this); Without the else, the conditional isn't the last block of the function, so doesn't get the return treatment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP tricky problem I have the following class structure: class Parent { public function process($action) { // i.e. processCreateMyEntity $this->{'process' . $action}; } } class Child extends Parent { protected function processCreateMyEntity { echo 'kiss my indecisive ass'; } } I need to write some unified method in Child class to process several very similar actions for creating entities. I can't change the Parent::process and I need those methods to be called from it. The first thing that comes to mind is magic __call method. The entity name is parsed from the first __call argument. So the structure turns to: class Parent { public function process($action) { // i.e. processCreateMyEntity $this->{'process' . $action}; } } class Child extends Parent { protected function __call($methodName, $args) { $entityName = $this->parseEntityNameFromMethodCalled($methodName); // some actions common for a lot of entities } } But the thing is that __call can't be protected as I need it. I put a hack method call at the beginning of __call method that checks via debug_backtrace that this method was called inside Parent::process, but this smells bad. Any ideas? A: I am assuming your child extends from the parent. Then what you could do is: public function process($action) { $methods = get_class_methods($this); $action = 'process' . $action; if(in_array($action, $methods)){ $this->{$action}() } else { die("ERROR! $action doesn't exist!"); } } A: If 'several' means 3 or 4, I'd probably just do something like: protected function processThis() { return $this->processThings(); } protected function processThat() { return $this->processThings(); } protected function processThings() { //common function } Sure, there is duplicate code, but what it does makes immediate sense. There are a handful of functions that do something similar, and it's easy to discover that. A: Actually, you don't need __call, you can create your own and protected: class Parent { public function process($action) { // i.e. processCreateMyEntity $this->entityCall('process' . $action); } } class Child extends Parent { protected function entityCall($methodName, $args) { $entityName = $this->parseEntityNameFromMethodCalled($methodName); // some actions common for a lot of entities } } According to the description in your question, this should be fitting, but I'm not entirely sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Rails 3 - AJAX request Rename it rename.js.erb alert('start'); $('div.popup').html('<%= escape_javascript(render('rename')) %>'); _rename.html.erb Some text in terminal window Processing by ArticlesController#rename as ... Rendered articles/_rename.html.erb (0.3ms) Rendered articles/rename.js.erb (2.3ms) This is my current set up for the AJAX request. I'm still getting this error message *Missing template articles/rename *. I don't understand why, I think everything should be set alright... jQuery library is loaded. The alert window in JS file don't jump... Could anyone help me, please, what is the problem? A: Can you post the full terminal output for that request? I'm interested in where Rendered articles/_rename.html.erb (0.3ms) is coming from and what it's being processed as since you simply wrote "...". The only thing I can think of is that your file isn't named correctly. ArticlesController#rename would look for rename.html.erb and not a partial like _rename.html.erb. A: Try rendering _render.html.erb explicitly as a partial within your js file. Rails might be getting confused with the (almost) conflicting names of your views. In rename.js.erb $('div.popup').html('<%= escape_javascript(render(:partial => 'rename')) %>'); Or try renaming the partial other than rename.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Convert a java.text.DateFormat instance to a strftime string? I've got a DateFormat object that I would like to turn into a strftime string so I can get consistent date formatting across multiple languages. Is there something in the SDK that I'm missing? If not, is this a feature of some 3rd-party lib that I can grab? Thanks. A: There is a strftime translator class in the Apache Tomcat project: org.apache.catalina.util.Strftime Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Best way to re-create a dynamic table in css Curious to see what method other people are using to re-create fluid tables in CSS. Back in table days, if there wasn't a width set the table would just auto-adjust to make the columns fit. Let's say: We have a 2column "table" display a product. Image on the left, Name/Description on the right. Let's also say: Image width is unknown. Typically in this situation, what I do is float the image left and hide the overflow on the content to the right. If we have rows of data though, this simply will not work as everything will have different margins. Yes, We could just say: Images will not be bigger then x so let's float the image left and set a left margin on the right side content. - or even float the content on the right to the right. Doing this really isn't a problem, however I am just curious as if there was a way to make it all fluid... Some of these sites I'm working on have enormous stylesheets and I'm trying to keep the styles to a minimum. Our designer likes to use this image to the left, content to the right - or even reversed... image to the right content to the left A LOT, but it seems as the margins are always different per situation. I really want to make this a re-usable class. A: http://jsfiddle.net/simoncereska/dGnzJ/ Take a look at this. If you add class .p-r to .img you'll get another view. Is this what you are asking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django Admin Problem Coercing to Unicode Trying to create a Django app based off the tutorial but using a different model.(First time using Djanago) I'm at the part where you alter the Admin panel to add 3 items with a dependent foreign key. I know the problem originates from the class EventAdmin(admin.ModelAdmin): on line 10 of admin.py but I'm not sure how the fields should be arranged to make it work. The admin panel works untill I try to create an event with 3 choices. Then I get the following error... coercing to Unicode: need string or buffer, Location found Code is as follows... models.py from django.db import models class Location(models.Model): icon = models.CharField(max_length=200) location = models.CharField(max_length=200) def __unicode__(self): return self.location class Event(models.Model): location = models.ForeignKey(Location) info = models.CharField(max_length=200) def __unicode__(self): return self.location class Choice(models.Model): event = models.ForeignKey(Event) choice = models.CharField(max_length=200) link = models.CharField(max_length=200) def __unicode__(self): return self.choice admin.py from map.models import Location from map.models import Event from map.models import Choice from django.contrib import admin class ChoiceInline(admin.StackedInline): model = Choice extra = 4 class EventAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['location', 'info']}), ] inlines = [ChoiceInline] admin.site.register(Event, EventAdmin) admin.site.register(Location) A: The .__unicode__() method is expected to return a unicode object. Your Event.__unicode__() however returns self.location which is a Location instance. Either have it cast self.location to unicode or explicitly reference a field in the Location object. def __unicode__(self): return u'%s' % (self.location, ) def __unicode__(self): return self.location.location
{ "language": "en", "url": "https://stackoverflow.com/questions/7560641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating SQL Server 2008 R2 DTSX from C# - Exception from HRESULT: 0xC0048021 I'm creating a dtsx from C# (.NET 4.0) but when I try add the OLEDB Source into the data flow and is time to execute the ProvideComponentProperties step, I recieve the following error in VS2010: Exception from HRESULT: 0xC0048021 This is part of the code I'm using: //add SQL destination IDTSComponentMetaData100 SQLDestination = dataflowTask.ComponentMetaDataCollection.New(); SQLDestination.ComponentClassID = "DTSAdapter.OleDbSource.1"; // Set the common properties SQLDestination.Name = "SQLDestination"; SQLDestination.Description = "SQL destination"; CManagedComponentWrapper SQLDestComponent = SQLDestination.Instantiate(); SQLDestComponent.ProvideComponentProperties(); // The error happens here I am using SQL Server 2008 R2 SP1 and C# .NET Framework 4.0 A: You are limited to VS2008 and .NET 3.5 for SQL2008 R2.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: upgradable reader lock in c# I have a dictionary that is shared among number of threads. Every thread reads specific value from the dictionary according to a given key, but - if the key does not exist in the dictionary the thread need to add it to the dictionary. To solve the sync problem, I though to use ReaderWriterLockSlim class which basically gives me readers-writers lock synchronization (meaning readers can run in parallel but only one writer at a time...) but adds upgrade option for a reader. Using the upgrade option I can test whether a given key is already in the dictionary and if not - upgrade the lock and write it, promising only one addition for every key. My problem is that I cant create two upgradeable locks at a time - meaning this solution is no good... :( Can somebody please explain to me why Microsoft chose to implement the upgradable lock this way (that I cant have more than one upgradable lock at a time...), and give me any idea how can I implement the upgradable lock by myself \ give me another idea to sync my shared dictionary? A: If you are using .NET 4.0 why not use the ConcurrentDictionary A: I have no idea why ReaderWriterLockSlim was implemented in that way. I suspect there are good reasons. Why not just use ConcurrentDictionary? Then you don't have to worry about explicit locking. That said, I don't see where having multiple upgradable reader locks would help you. Consider the following scenario: Thread1 enters the lock in upgradeable mode Thread2 enters the lock in upgradeable mode Thread1 searches for "xyzzy" and doesn't find it Thread2 searches for "xyzzy" and doesn't find it Thread2 upgrades to a write lock Thread1 waits to upgrade to a write lock Thread2 updates and releases the lock Thread1 acquires the write lock and overwrites what Thread2 had written In order to prevent Thread1 from overwriting what Thread2 did, you'd have to write this logic: Enter upgradable read lock if (!dict.TryGetValue(...)) { Enter write lock if (!dict.TryGetValue(...)) // extra check required! { } } Which is exactly what you have to do when there are no upgradeable locks. A: UpgradeableReadLock exists so you do not have to release your read lock prior to acquiring a write lock. It lets you do this: locker.EnterUpgradeableReadLock(); ... locker.EnterWriteLock(); ... instead of locker.EnterReadLock(); ... locker.ExitReadLock(); locker.EnterWriteLock(); ... As it is a ReaderWriter lock, you may still only have one writer at any given time, which an upgradeable read lock enforces. This means these two aren't equivalent; the first lets other callers sneak in, but allows concurrency in the read portion. If you have cases where you can use ReadLocks for most reads, and UpgradeableRead for data updates/inserts, this is the intent. If all of your data accesses are potential writers, then this probably doesn't work as well and you can use simple lock(object) around your writes to enforce the exclusive access when adding/updating. A: It doesn't sound like you are perhaps using the optimal solution to this problem. Example: protected static object _lockObj = new object(); if(_dictionary.ContainsKey(key)) { return _dictionary[key]; } else { lock(_lockObj) { if(_dictionary.ContainsKey(key)) return _dictionary[key]; _dictionary.Add(key, "someValue"); return "someValue"; } } If you're using .NET 4, try using the ConcurrentDictionary class that others have mentioned.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Dynamically refreshing an image using ajax within Grails I have a web page where I need periodically update image based on several conditions. For now I'm using this: <html> <head> <meta http-equiv="refresh" content="3"> </head> <body> <img src="${createLink(controller:'advertisment',action:'viewImage',id:advertismentInstance.id)}"/> </body> </html> But it causes total reload of the web page, so I want it to be done with Ajax (I'm also using Prototype framework which is default in Grails). Provide with advertisment controller method: def viewImage = { log.info("before view Image") def adv = Advertisment.get(params.id) byte[] image = adv.fileContent response.outputStream << image log.info("after view Image") } device controller method: def showAdv = { log.info("showAdv start") def deviceInstance = Device.get(params.id) int totalNumberOfAdv = deviceInstance.advertisment.size(); Random rand = new Random() int advToShow = rand.nextInt(totalNumberOfAdv+1) - 1; def advertismentInstance = deviceInstance.advertisment.toArray()[advToShow] if(advertismentInstance) { render(view: "image", model: [deviceInstance :deviceInstance,advertismentInstance: advertismentInstance]) } else { flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'advertisment.label', default: 'Advertisment'), params.id])}" } log.info("showAdv end") } A: * *Give your <img/> an id: <img id="foo" src="..."/><!-- keep the existing src --> *Remove the <meta/> that's refreshing the page. *Before the closing </body> tag, add this: <script> var img = document.getElementById('foo'); // id of image setInterval(function() { var stamp = new Date().getTime(); img.setAttribute('src', img.getAttribute('src') + '?_=' + stamp); }, 3000); </script> *Update your viewImage action to actually do the randomization before rendering the image. This probably means combining parts of showAdv into viewImage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Moving foreach loop before return statement I´m trying to place the result of a weather forecast function in a PHP return statement. To do this using concatenation I need to move a foreach loop up in the code and I just can´t get it to work. I´m trying to create a function like this: : function getWeatherForecast($atts) { all variables go here; return 'concatenated output'; } Here a link to the full script: http://pastebin.com/fcQpskmy This is what I have now: function getWeatherForecast($atts) { $xml = simplexml_load_file('http://www.google.com/ig/api?weather=barcelona'); $information = $xml->xpath("/xml_api_reply/weather/forecast_information"); $current = $xml->xpath("/xml_api_reply/weather/current_conditions"); $forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions"); /* The foreach loop should go here */ return '<h2>The weather today ' . $information[0]->city['data'] . '</h2>'; /* etc. etc. */ } And this is the foreach loop that I need to place before the return statement: <?php foreach ($forecast_list as $forecast) : ?> <div> <img src="<?php echo 'http://www.google.com' . $forecast->icon['data']?>" alt="weather"?> <div><?php echo $forecast->day_of_week['data']; ?></div> <span> <?php echo $forecast->low['data'] ?>&deg; F – <?php echo $forecast->high['data'] ?>&deg; F, <?php echo $forecast->condition['data'] ?> </span> </div> <?php endforeach ?> Thanks so much for your help!! A: Just so we're clear, you want that foreach to be inside the function right? In that case: $html_code = ""; foreach ($forecast_list as $forecast) { $html_code .='<div> <img src="http://www.google.com' . $forecast->icon['data']. '" alt="weather" /> <div>'.$forecast->day_of_week['data'].'</div> <span> '. $forecast->low['data'] .'&deg; F – '. $forecast->high['data'] .'&deg; F, '. $forecast->condition['data'] .' </span> </div> } And then $html_code will have all the html code needed to be concatenated on the return statement. Is this what you need? A: i tried this and it works: <? echo getWeatherForecast(''); function getWeatherForecast($atts) { $xml = simplexml_load_file('http://www.google.com/ig/api?weather=barcelona'); $information = $xml->xpath("/xml_api_reply/weather/forecast_information"); $current = $xml->xpath("/xml_api_reply/weather/current_conditions"); $forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions"); foreach ($forecast_list as $forecast) { ?> <div> <img src="<?php echo 'http://www.google.com' . $forecast->icon['data']?>" alt="weather"?> <div><?php echo $forecast->day_of_week['data']; ?></div> <span> <?php echo $forecast->low['data'] ?>&deg; F – <?php echo $forecast->high['data'] ?>&deg; F, <?php echo $forecast->condition['data'] ?> </span> </div> <? } return '<h2>The weather today ' . $information[0]->city['data'] . '</h2>'; /* etc. etc. */ } ?> but this is not right way to do that. Use one variable to accumulate html, and then return all the html. like this: <? echo getWeatherForecast(''); function getWeatherForecast($atts) { $xml = simplexml_load_file('http://www.google.com/ig/api?weather=barcelona'); $information = $xml->xpath("/xml_api_reply/weather/forecast_information"); $current = $xml->xpath("/xml_api_reply/weather/current_conditions"); $forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions"); $html = ''; foreach ($forecast_list as $forecast) { $html .= '<div>'; $html .= '<img src="http://www.google.com'.$forecast->icon['data'].'" alt="weather"/>'; $html .= '<div>'.$forecast->day_of_week['data'].'</div>'; $html .= '<span>'; $html .= $forecast->low['data'].'&deg; F – '.$forecast->high['data'].'&deg; F,'.$forecast->condition['data']; $html .= '</span>'; $html .= '</div>'; } $html .= '<h2>The weather today ' . $information[0]->city['data'] . '</h2>' return $html; /* etc. etc. */ } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET: can I force a download of a stored file and update a label in the same event handler? I've got a ListView datasourced to a database displaying a list of files to be downloaded along with a download count for each. In the ItemTemplate I use a Label to display the current count and a LinkButton with it's Text set to the file name and it's Command set to "select", so as to fire the Listviews SelectedIndexChanging event. All this works fine and I can force the download dialog box to appear but can't get the label updated (which indicates the new download count). I suspect since I'm using the Response to download the binary data, it loses all info to update the label...One thought I have is to save the response stream before I download the file then restore it to it's original state and try to update the ItemTemplates label. protected void FileListView_SelectedIndexChanging( Object sender, ListViewSelectEventArgs e ) { ListViewItem item = (ListViewItem)PresetUploadListView.Items[e.NewSelectedIndex]; LinkButton lb = (LinkButton)item.FindControl( "PresetUploadTitle" ); int fileID = Convert.ToInt32( lb.CommandArgument.ToString( ), 10 ); byte[] fileData = GetFileDataFromDatabasePreset(fileID); try { Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=" + lb.Text + ".zip"); BinaryWriter bw = new BinaryWriter(Response.OutputStream); bw.Write(fileData); bw.Close(); Response.ContentType = "application/zip"; Response.Flush(); //Response.Close(); //Response.End(); } catch (Exception ex) { String s = ex.Message + " " + ex.InnerException; } Label l = (Label)item.FindControl("PresetUploadDownloads"); int downloadCount = IncandreturnDownloadCount(fileID); l.Text = downloadCount.ToString(); //+> not getting updated... e.Cancel = true; } A: Your request can't give two different responses. It can't respond to a page change and serve a file at the same time. There are a few options available. * *Use window.open in JavaScript to open a window to the file handler that will initiate the download before the page posts back. The download will begin in a different window, then you update your label in the post back. *Update the label first with an AJAX call, then on success of the AJAX call, post back and do your file download.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flushing python GAE datastore when unit testing I am following the recommendations on the app engine site for unit testing coding with GAE. I have set the PseudoRandomHRConsistencyPolicy probability to 0% to force the code to account for cases where the data is not yet consistent. The problem is that in my test suite I want to do some data setup (creating and adding data to the datastore) and need a way to force the datastore to flush all the data into a consistent state before I exercise the code under test. (ie. make sure that the datastore will return all global entities I have written the next time I do a query). Is there any way to do this and if not, how are other people setting up data in their tests suites when they are using the consistency models? A: The key to doing this is noted near the end of the section on HRD testing: In the local environment, performing a get() of an Entity that belongs to an entity group with an unapplied write will always make the results of the unapplied write visible to subsequent global queries. In production this is not the case. Simply add some get operations to your tests to get the appropriate records, and they will show up in future queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: event.returnValue in IE6 The following code should not open a new window in IE and Firefox. Its not opening in Firefox, but it is opening in IE. Whats going wrong? var EventLib = { "preventDefault" : function(event){ if(event.preventDefault) { event.preventDefault(); }else{ window.event.returnValue = false; } } } window.onload = function(){ var elem = document.getElementById("link"); elem.onclick = function(e){ EventLib.preventDefault(e); } } and the HTML is: <a id="link" href="http://www.google.com" target="_blank">Click</a> A: It could be that evaluating the expression event.preventDefault throws an error when event is undefined. Try using if (event && event.preventDefault) rather than just if (event.preventDefault). A: Just change function as I have shown it below, it will work var EventLib = { "preventDefault" : function(event){ if(!event) event = window.event; if(event.preventDefault) { event.preventDefault(); }else{ window.event.returnValue = false; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Aggregate data in one column based on values in another column I know there is an easy way to do this...but, I can't figure it out. I have a dataframe in my R script that looks something like this: A B C 1.2 4 8 2.3 4 9 2.3 6 0 1.2 3 3 3.4 2 1 1.2 5 1 Note that A, B, and C are column names. And I'm trying to get variables like this: sum1 <- [the sum of all B values such that A is 1.2] num1 <- [the number of times A is 1.2] Any easy way to do this? I basically want to end up with a data frame that looks like this: A num totalB 1.2 3 12 etc etc etc Where "num" is the number of times that particular A value appeared, and "totalB" is the sum of the B values given the A value. A: Here is a solution using the plyr package plyr::ddply(df, .(A), summarize, num = length(A), totalB = sum(B)) A: Here is a solution using data.table for memory and time efficiency library(data.table) DT <- as.data.table(df) DT[, list(totalB = sum(B), num = .N), by = A] To subset only rows where C==1 (as per the comment to @aix answer) DT[C==1, list(totalB = sum(B), num = .N), by = A] A: I'd use aggregate to get the two aggregates and then merge them into a single data frame: > df A B C 1 1.2 4 8 2 2.3 4 9 3 2.3 6 0 4 1.2 3 3 5 3.4 2 1 6 1.2 5 1 > num <- aggregate(B~A,df,length) > names(num)[2] <- 'num' > totalB <- aggregate(B~A,df,sum) > names(totalB)[2] <- 'totalB' > merge(num,totalB) A num totalB 1 1.2 3 12 2 2.3 2 10 3 3.4 1 2 A: In dplyr: library(tidyverse) A <- c(1.2, 2.3, 2.3, 1.2, 3.4, 1.2) B <- c(4, 4, 6, 3, 2, 5) C <- c(8, 9, 0, 3, 1, 1) df <- data_frame(A, B, C) df %>% group_by(A) %>% summarise(num = n(), totalB = sum(B))
{ "language": "en", "url": "https://stackoverflow.com/questions/7560671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Rspec newbie question I was looking at some rspec sample code and came across this - lambda { @my_object.function }.should raise_error(ArgumentError, "Unknown tag type") Does this mean that rspec monkey patches the Proc object? Or otherwise how can I call the should method? A: I probably wouldn't call it monkey patching since it extends the core ruby Object class. But: yes, rspec will define the should method on Object so anything can be say that it should "something" 1.should eq(2) class MySuperObject end MySuperObject.new.should_not respond_to(:monkey!) A: It's unlikely it specifically monkey patches Proc since everything responds to should. Does this behavior really matter? Regardless, an easy choice is to just take a peek at the source. https://github.com/dchelimsky/rspec, specifically https://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb More about Kernel http://ruby-doc.org/core/classes/Kernel.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7560675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL sub position counters in Query I need to get a record set where I fill the field level1 for every 60 records, means I need to fill level1 field this way: * *on pos=1 and pos=60 with level1 = 1 *on pos=61 and pos=120 with level1 = 2 *on pos=121 and pos=180 with level1 = 3 ... and then: if I have let's say 630 records i must set for pos=601 and 630 level1 = 10 because I don't have 660 records the 630th record finished the level. Has anyone a idea how this can be done in a clean way? SET @pos:=0; SET @posrel:=0; SET @level1:=0; SELECT id, member_id, member_name, pos, @posrel:=@posrel+1 AS posrel, @level1:=@level1+??? AS level1 FROM ( SELECT id, member_id, LEFT(member_name, LENGTH(member_name)-36) AS member_name, @pos:=@pos+1 AS pos FROM member_directory WHERE member_name_first= 'A' ) AS directory_listing HAVING pos % 60 IN(0,1); A: -- SET @pos:=0; //Can be moved inside the query. -- SET @posrel:=0; SELECT inner.*, posrel DIV 60 as level1 FROM ( SELECT directory_listing.*, @posrel:=@posrel+1 AS posrel AS level1 FROM ( SELECT id , member_id , LEFT(member_name, LENGTH(member_name)-36) AS member_name_first , @pos:=@pos+1 AS pos FROM member_directory CROSS JOIN (SELECT @pos:= 0) x1 WHERE member_name_first = 'A' AND directory_listing.pos < 120 ) directory_listing CROSS JOIN (SELECT @posrel:= 0) x2 ) inner Or maybe -- SET @pos:=0; //Can be moved inside the query. -- SET @posrel:=0; SELECT inner.*, posrel DIV 60 as level1 FROM ( SELECT directory_listing.*, @posrel:=@posrel+1 AS posrel AS level1 FROM ( SELECT id , member_id , LEFT(member_name, 1) AS member_name_first , @pos:=@pos+1 AS pos FROM member_directory CROSS JOIN (SELECT @pos:= 0) x1 WHERE member_name LIKE 'A%' AND directory_listing.pos < 120 ) directory_listing CROSS JOIN (SELECT @posrel:= 0) x2 ) inner
{ "language": "en", "url": "https://stackoverflow.com/questions/7560679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use one registered C2DM account for multiple apps I have a platform that is up to 14 branded applications now. I am implementing C2DM and am wondering if I need a registered C2DM account for each application. I just tried it out in the emulator and got a new registration token for the second app and sending messages appears to be working fine. Anyone know if I can just plow forward using a single account? Is it only the registration key that matters? A: Correct, You will be fine using one account. It is the key that matter's
{ "language": "en", "url": "https://stackoverflow.com/questions/7560683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: POST java object from .jsp to java I've got a page where the user inputs information into a form and then hits submit. When the submit button is clicked the user POST's data to a java file. I'm using out.print() to print Strings but how would I POST an object when the HTML form is submitted? A: <form action="/myServlet"> <input name="uid" type="text" value="testUser"/> <input name="pwd" type="password" value="mypwd" /> <input name="myObj" type="hdden" value="<%=someObject%>"> <input type="submit" /> </form> If there is any form like this, when user clicks on submit button. form will be submitted to the action url "/myServlet" . here action is servlet or nay action. we can get the data from the serverside by using request.getParameter("myObj"); A: * *When submit is clicked the request will go to a servlet. *In servlet the form data can be obtained. Check this example Simple Servlet example *If an object has to be passed from jsp then DWR can be used for this purpose. Here I gave an explanation of how to do in DWR Some tutorials for DWR
{ "language": "en", "url": "https://stackoverflow.com/questions/7560696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to "Pulse" DateTime Updates in WPF App I apologize up front for the lengthy explication. I am working on a WPF desktop app (shown below): Basically there can be 0..n process status items in the list (the items themselves are ListBoxItems rendered using a DataTemplate). Recently, I decided I wanted to provide a "time elapsed" style presentation (n seconds/minutes/hours ago) as an alternative to an absolute DateTime format (mm/dd/yyyy at HH:mm:ss). I've accomplished this by using a MultiBinding to a TextBlock as such: <TextBlock> <TextBlock.Text> <MultiBinding Converter = "{StaticResource timeElapsedConverter}"> <Binding Path = "StatusDateTime" /> <Binding Source = "{StaticResource propertiesHelper}" Path = "UserOptions.UseElapsedTimeStamps" /> </MultiBinding> </TextBlock.Text> </TextBlock> I'll spare you the details of the IMultiValueConverter implementation. The second binding is to a helper class that gets the user's timestamp display preferences (i.e. they can still see absolute DateTime values if they want to). The "StatusDateTime" property to which this TextBlock is otherwise bound is nothing special; it's just a POCO property in a ViewModel class that fires OnPropertyChanged when set. This view is synchronized with the system backend every (x) seconds. I'd like to "Pulse" the timestamps during synchronization so that the elapsed time measurements stay accurate but if I just set the StatusDateTime property to its existing value, nothing seems to happen (in the case of the example below, it will just say "Published 6 seconds ago..." until either the process itself is updated on the server side or until the application is loaded a second time). I tried adding IsAsync="true" to the StatusDateTime binding as suggested in this post, but to no avail. I also tried falling back to regular binding (non-multi) with Mode="TwoWay" explicity declared and that didn't work either. I know I could just blow away the list and recreate during synchronization, but that just doesn't seem very elegant when I already have all the data I need loaded into the client. Update: I tried recreating this basic setup in a Window and it seemed to work just fine. I'm now wondering if this has something to do with the target control being on a Page or part of a DataTemplate. Any thoughts? Thanks in advance! A: The way I accomplished this in my own MVVM based app was to have a simple timer running on my ViewModel that fires OnPropertyChanged every second for the property I want to keep updated. Here's an example (in IronPython syntax): self.displayTimer = System.Timers.Timer(1000) #fire every second self.displayTimer.Elapsed += self.displayTimer_Tick self.displayTimer.Start() def displayTimer_Tick(self, sender, event): self.OnPropertyChanged("StatusDateTime") This uses a System.Timers.Timer that executes its callback on a background ThreadPool thread, so it won't interfere with the Dispatcher. A: Ok, so I believe I've figured it out. I left out a key piece of detail that more quickly would've pointed us in the right direction: My DataTemplate is backed by a CollectionViewSource. If I call the Refresh() method on the CollectionViewSource's View property, the timestamps update as expected. I always forget that changing properties of elements of an ObservableCollection doesn't necessarily cause the CollectionChanged event to fire which would thereby prompt the CollectionViewSource to refresh. Thanks to all who replied!
{ "language": "en", "url": "https://stackoverflow.com/questions/7560700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XCode UIPickerView Delay Select I wish the UIPIckerView would allow you to scroll then select but since it doesn't, is there a way to delay the auto select? For example, if I scroll down and it stops on an item, it instantly automatically selects that item. Is there any way to make it so that if it lands on the item, it must wait for example like 1-2 seconds before selecting? This way it gives to user more time to keep scrolling through the list. A: I had the same problem. When I thought about it for a while I thought well just add an NSTimer. This is what I did: [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayTime) userInfo:nil repeats:NO]; and then I added a void statement: -(void)delayTime { //Add delayed code here } Hope that helps, Seb
{ "language": "en", "url": "https://stackoverflow.com/questions/7560704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Null values in entity when entitydatasource Deleting Event raised I'm currently using the Entity Framework and I have a Gridview displaying a list of records from a database. I have a Remove button the uses the Delete command. Each record has a file on the server associated with it, so when the data source raises the deleting event I want to grab the filename and delete the file from the server as well. The weird thing is that in my ds_Deleting event some of the values in the entity are null. I can't seem to figure out why. The code for my Delete button in the gridview is the following: <asp:TemplateField HeaderText="Remove"> <ItemTemplate> <asp:Button ID="btnRemove" runat="server" Text="Remove" CssClass="button_default" CommandName="Delete" OnClientClick="return confirm('Deleting this contract will also delete the file from the server. Continue?')" /> </ItemTemplate> </asp:TemplateField> The OnDeleting event in the codebehind looks like this: protected void dsContracts_Deleting(object sender, EntityDataSourceChangingEventArgs e) { ipiModel.Contract contract = (ipiModel.Contract)e.Entity; File.Delete(Path.Combine(ConfigurationManager.AppSettings["ContractUploadPath"], contract.FileName)); } Every time the contract.FileName value is null, even though it is displayed properly in the GridView. Any help would be much appreciated. Thanks! A: I managed to figure this out and decided I'd write it down here in case anyone else has the same problem. I checked the documentation on MSDN for the deleting event of the entity data source (which can be found here) and it said The Entity property of the EntityDataSourceChangingEventArgs object is used to access the object to be deleted. The properties of this object may not be fully set. Only the properties required to identify the object must be set. So this is why I was getting null values. The solution I came up with probably isn't ideal but it works. I realized the primary key ContractID always had a value so I used it to pull the record from the database. Here is my code: protected void dsContracts_Deleting1(object sender, EntityDataSourceChangingEventArgs e) { ipiModel.Contract ct = (ipiModel.Contract)e.Entity; using (var db = new ipiModel.ipiEntities()) { var contract = db.Contracts.Where(c => c.ContractID == ct.ContractID).Single(); File.Delete(Path.Combine(ConfigurationManager.AppSettings["ContractUploadPath"], contract.FileName)); } } A: Having experienced this with an ASP.NET Dynamic Data List page, and given that there appears to be a bug with varchar foreign keys (accepted by Microsoft I believe), any solution would be something of a workaround (hack). In order to work around null values for table columns with default values (e.g. createdDate, CreatedBy etc), I've ended up with setting default values in the constructor of a partial class for the entity concerned. After the information above gave the clue that only the columns required to uniquely identify the entity are loaded, I found that adding another 'default' value for the problem (foreign key) column fixed my issue - i.e. because I don't have any cascade delete or anything else, the primary key of the entity is enough to do the delete, and it's other processing that's checking for null values in the foreign key (varchar) - so I simply set that column to String.Empty in the contructor, and the default value I set is ignored... e.g. public partial class MyEntity { public MyEntity() { CreatedDate = Datetime.Now; //Other default stuff MyProblemVarcharForeignKeyField = String.Empty; } } et voila! A: All you have to do is to Bind the property you want to access in the code behind to an object. You could add a TemplateField with Hidden objects and Bind the values you want to use to them like this : <asp:TemplateField HeaderText="Remove"> <ItemTemplate> <asp:HiddenField ID="HiddenField1" runat="server" value='<%# Bind("FileName") %>'/> </ItemTemplate>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I account for subprocess.Popen() overhead when timing in python? more-intelligent-members-of-the-coding-community-than-I! I have a python question for you all... :) I am trying to optimize a python script that is (among other things) returning the wall-clock time a subprocess took execute and terminate. I think I'm close with something like this. startTime = time.time() process = subprocess.Popen(['process', 'to', 'test']) process.wait() endTime = time.time() wallTime = endTime - startTime However, I am concerned that the overhead in subprocess.Popen() is inflating my results on older and exotic platforms. My first inclination is to somehow time the overhead caused by subprocess.Popen() by running a simple innocuous command. Such as the following on linux. startTime = time.time() process = subprocess.Popen(['touch', '/tmp/foo']) process.wait() endTime = time.time() overheadWallTime = endTime - startTime Or the following on windows. startTime = time.time() process = subprocess.Popen(['type', 'NUL', '>', 'tmp']) process.wait() endTime = time.time() overheadWallTime = endTime - startTime So, how should I account for subprocess.Popen() overhead when timing in python? Or, what is an innocuous way to sample the overhead from subprocess.Popen()? Or, maybe there's something I haven't considered yet? The caveat is that the solution must be reasonably cross-platform. A: Welcome to batteries included.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send parameter to action method from java script In controller (imagesController) I have 'crop' action get and post. I am trying to send string in it but not working. I am using replace to load view in iFrame but how to post some parameter to it? myIframe.location.replace('images/crop'); A: myIframe.location.replace('images/crop?someParam=someValue'); As far as POST is concerned, forget about it using the location property, tat works only with GET requests. If you want to perform a POST request you need either a form submission or an AJAX request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSRF security risks if Validation token in header instead of POST body Most widely found solution on Searching for CSRF prevention techiniques is what MVCAntiForgeryToken (comes with MVC 3) implements, where client of the server has to post the validation token in POST body. On server side it will be validated against the token present in Cookie. Is it equally secure to send the validation token in a custom header, and on server side validate value of custom token with one present in cookie ? A: It is even more secure :) because even if attacker can obtain a valid csrf token for current transaction, he would have to institute a cross domain ajax request to include custom headers in request. And if user has disabled js in his browser then the attacker is toasted :). It can however be overridden with java applets... but you know if users are uneducated and attacker is really motivated there is very little you can do;). But there is an issue not all custom headers will be forwarded in case a user is accessing us via firewall or corporate proxy. So i think this is the main reason for using field instead of a custom header. Although there is a header that prevents XSRF attacks: Origin, The web origin concept also as additional information Content Security Policy 1.1 it is only a draft but some interesting ideas are presented there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: When does the JVM load classes? Assume I have the following class: class Caller { public void createSomething() { new Something(); } } Would executing this line: static void main() { Class<?> clazz = Caller.class; } cause the JVM to load the class Something or is the class loading deferred until the method createSomething() is called? A: A class is loaded only when you require information about that class. public class SomethingCaller { public static Something something = null; // (1) does not cause class loading public static Class<?> somethingClass = Something.class; // (2) causes class loading public void doSomething() { new Something(); // (3) causes class loading } } The lines (2) & (3) would cause the class to be loaded. The Something.class object contains information (line (2)) which could only come from the class definition, so you need to load the class. The call to the constructor (3) obviously requires the class definition. Similarly for any other method on the class. However, line (1) doesn't cause the class to be loaded, because you don't actually need any information, it's just a reference to an object. EDIT: In your changed question, you ask whether referring to Something.class loads the class. Yes it does. It does not load the class until main() is executed though. Using the following code: public class SomethingTest { public static void main(String[] args) { new SomethingCaller(); } } public class SomethingCaller { public void doSomething() { Class<?> somethingClass = Something.class; } } public class Something {} This code does not cause the Something.class to be loaded. However, if I call doSomething(), the class is loaded. To test this, create the above classes, compile them and delete the Something.class file. The above code does not crash with a ClassNotFoundException. A: Yes, that will cause the class to load when the class containing the File.class reference is loaded. The only way to not do this is to reference a class by reflection. Then you can control when it's loaded. A: If you have performance requirements this strict, you should consider writing a custom ClassLoader object. This would let you can dump classes from memory when they aren't needed any more. You'll want to check out the loadClass, findClass and probably the defineClass methods in the ClassLoader class, overriding load and find and using defineClass in the implementation. A google search on writing custom class loaders will reveal lots of sample code to do this, but basically you are going to cache the class results in a Map (class name to Class), then provide some callback mechanism to remove loaded classes from your cache when they aren't needed. good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Dividing up 3d angles into equal quantities Say you have a 2d object, you could easily divide this into 15 degree rotations by simply rotating around the centre in 15 degree increments. If I want to calculate for a 3d object all the angles possible with equal spacing between each one how would I go about doing this. although doing p*r*y for each would work it'd be fairly arbitrary and have a huge amount of overlap. I'd really like a quaternion solution too. I'm doing this for a video game project I'm currently working on, essentially an old school flight sim which although 3d in game-play is rendered as 2d sprites. I'm looking for a simple way to render all the possible angles of my aeroplane model procedurally with equally spaced angles including each orthogonal one. A: There are various ways to do this; the solution isn't uniquely defined from the information given. Also note that the phrase "all possible angles" is misleading because there are infinite angles. Nevertheless if by "3d angle" you literally mean a solid-angle (in units of steradians), then the platonic solids will divide the sphere into equal solid-angles. (Technically you want spherical polyhedra, but they're "almost" the same in the sense that we can take a polyhedral solution and "relax" it.) Keeping in mind your condition that you want "[to include] each orthogonal [angle]" (that there should be some triplet of views which are orthogonal to each other), we are saddened to notice that there is only one platonic solid which satisfies this, namely the octahedron: Sadly this would correspond to just taking the orthogonal views (and only those views). That would be boring and probably not what you intended to ask for. What you can do however is build upon this solution, and subdivide the octahedron. Here are two possibilities: * *For each face in the octahedron, you could create a new view at the center of that face (stellate it). The result would be a view from each of the vertices as pictured in this 4-view origami (oddly the best picture I could find). Thus in addition to the orthogonal angles, you gain 8 angles between each axis, of the form (±1,±1,±1). Keeps the number of views down to a manageable size. *If you desire more views, you can do something like building a geodesic dome, except you start with an octahedron rather than an icosahedron. In the first example, we subdivide the triangular faces each into a "triforce" of subdivisive power, to obtain a "2-frequency octahedral geodesic sphere". → * * original link Algorithm: take the mathematical average of each adjacent vertex to produce the new vertices. This may not perfectly divide the angles, but it will come fairly close. If you would like even more "equality" of solid angles, see the link for an example of a "3-frequency octahedral geodesic sphere". Algorithm: To a first approximation, you can trisect an angle by taking the vectors (A+2B)/3, or vice versa. If you furthermore seek extreme precision, rather than explicitly calculating the equations, you can use the solid-angle formula for a tetrahedron as a measure of accuracy, and perform a relaxation on your initial guess, where you slowly perturb the trisections towards or away from the origin. Additionally the google search results are a bit mathematically dense, but you may be able to glean some use out of equal area spherical polyhedra.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# Lambda and LINQ tutorial for an experienced functional programmer I would like to learn the "functional" parts of C# (.NET 4). As a long time Haskell and Lisp programmer, I would prefer not to get distracted by explanations of basic concepts. Is there a book/tutorial that I should check out? A: Just look at the docs for the methods in System.Linq.Enumerable. These methods are standard functional programming operations with slightly different names (Select == Map, Where == Filter, Aggregate = foldl, etc) You'll also need to understand iterators; see Jon Skeet's excellent in-depth article. You should already understand lambda expressions and closures. A: Check this out 101 Examples on Linq here A: I would like to learn the "functional" parts of C# (.NET 4). As a long time Haskell and Lisp programmer, I would prefer not to get distracted by explanations of basic concepts. Is there a book/tutorial that I should check out? Yes, there is a book made just for you! Check out Real-World Functional Programming With Examples in F# and C#. Extraordinarily good book. A: I recommend reading some of Bart De Smet's blog posts for a decent view of the more theoretical side of C# lambdas and how they interact with LINQ. He doesn't blog often but he's got a good list of some of the more interesting posts here. I particularly like his post on MinLINQ. If you wanted to jump in I'd say look at one of the many tutorials using parser combinators in C# and build your own library (with Haskell experience I'm sure you'll find it pretty easy). This is one of the more popular tutorials but a quick search reveals plenty more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the maximum amount of characters for an ASP.NET textbox with MultiLine TextMode enabled? I know that the MaxLength property doesn't apply to System.Web.UI.WebControls.Textbox control in MultiLine mode. But what is the maximum amount of characters I can type in the textbox? It seems to be 1000 characters, but I can't find this documented anywhere. I am not asking on how to limit the number of characters in the textbox control. Thanks. A: There is no upper limit to the number of characters in a WebControls.Textbox in multiline mode. The only limits are total post data from a form and that depends on your web-servers set-up (I presume IIS) which I think is about 2mb by default in IIS but don't quote me on that. What is happening when you try to type beyond 1000 charatcters? A: There is no limit to the size of input, but if you use HTTP GET method to submit, your data will be encoded and appended to the submit URL. URLs, depending on a browser, have limitation of about 2000 characters. Try using HTTP PUT to submit the data in which case the payload is added to the HTTP header of the request which has no size limitations. Check method property of your FORM element.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hosted PowerShell cannot see Cmdlets in the same Assembly I'm trying to run PowerShell scripts from my C# code, that will use custom Cmdlets from the assembly that runs them. Here is the code: using System; using System.Management.Automation; [Cmdlet(VerbsCommon.Get,"Hello")] public class GetHelloCommand:Cmdlet { protected override void EndProcessing() { WriteObject("Hello",true); } } class MainClass { public static void Main(string[] args) { PowerShell powerShell=PowerShell.Create(); powerShell.AddCommand("Get-Hello"); foreach(string str in powerShell.AddCommand("Out-String").Invoke<string>()) Console.WriteLine(str); } } When I try to run it, I get a CommandNotFoundException. Did I write my Cmdlet wrong? Is there something I need to do to register my Cmdlet in PowerShell or in the Runspace or something? A: The easiest way to do this with your current code snippet is like this: using System; using System.Management.Automation; [Cmdlet(VerbsCommon.Get,"Hello")] public class GetHelloCommand:Cmdlet { protected override void EndProcessing() { WriteObject("Hello",true); } } class MainClass { public static void Main(string[] args) { PowerShell powerShell=PowerShell.Create(); // import commands from the current executing assembly powershell.AddCommand("Import-Module") .AddParameter("Assembly", System.Reflection.Assembly.GetExecutingAssembly()) powershell.Invoke() powershell.Commands.Clear() powershell.AddCommand("Get-Hello"); foreach(string str in powerShell.AddCommand("Out-String").Invoke<string>()) Console.WriteLine(str); } } This assumes PowerShell v2.0 (you can check in your console with $psversiontable or by the copyright date which should be 2009.) If you're on win7, you are on v2. A: Yet another simple way is to register cmdlets in a runspace configuration, create a runspace with this configuration, and use that runspace. using System; using System.Management.Automation; using System.Management.Automation.Runspaces; [Cmdlet(VerbsCommon.Get, "Hello")] public class GetHelloCommand : Cmdlet { protected override void EndProcessing() { WriteObject("Hello", true); } } class MainClass { public static void Main(string[] args) { PowerShell powerShell = PowerShell.Create(); var configuration = RunspaceConfiguration.Create(); configuration.Cmdlets.Append(new CmdletConfigurationEntry[] { new CmdletConfigurationEntry("Get-Hello", typeof(GetHelloCommand), "") }); powerShell.Runspace = RunspaceFactory.CreateRunspace(configuration); powerShell.Runspace.Open(); powerShell.AddCommand("Get-Hello"); foreach (string str in powerShell.AddCommand("Out-String").Invoke<string>()) Console.WriteLine(str); } } Just in case, with this approach cmdlet classes do not have to be public. A: You do need to register your cmdlet before you can use it in a Powershell session. You'll generally do that by way of a Powershell Snap-In. Here's a high-level overview of the process: * *Create custom cmdlets (you've already done this part) *Create a Powershell Snap-in which contains and describes your cmdlets *Install the new Snap-in on your system using Installutil *Add the Snap-in to a specific Powershell session using Add-PSSnapin There are a couple useful articles on MSDN that explain the process pretty thoroughly: * *Developing with Windows PowerShell *How to Create a Windows PowerShell Snap-in There's also a 2-part series on ByteBlocks that discusses writing custom cmdlets. That series may be your best bet, since you seem to have done the equivalent of part 1 already. You may be able to just use part 2 as a quick reference and be good to go. * *How to Write a Custom Cmdlet - Part 1 *How to Write a Custom Cmdlet - Part 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7560728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: C# and Flash integration I have integrated C# and Flash with "Sockwave Flash Object". I am trying to call a Flash method using a C# on-click event. How to do this? A: First, there is a SO question that can help with how to use Shockwave Flash Object: Displaying Flash content in a C# WinForms application Second, here is the Adobe Documentation: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7cb0.html Most importantly (as to the answer) here is the directions on calling Flash methods in C#: http://blog.another-d-mention.ro/programming/communicate-betwen-c-and-an-embeded-flash-application/ A: Flash can communicate with it's SWF container via the use of fscommand and ExternalInterface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Configuring tnsnames.ora, listener.ora anf sqlnet.ora to connect visual studio 2010 to oracle I have been trying to access an Oracle Database from Visual Studio 2010. I am confused about how to configure the tnsnames.ora, sqlnet.ora and listener.ora. I know they have to be moved into the Network/Admin folder of both the client and server but I don't know how and where to provide the instance name,user id and password of my specific database. This is the information given in my Oracle Databse control window Status Up Up Since Jun 1, 2011 8:37:15 AM CDT Instance Name lorac Version 10.2.0.1.0 Host localhost.localdomain Listener LISTENER_localhost.localdomain The DBA admin has also given me the following information: * *host: Lorac.chem.tamu.edu *instance: Stockroom2 *user/password: Inventory_mgmt/invmgmt I am very confused as to which data to include in tnsnames.ora,listener.ora and sqlnet.ora. Please do help me out. A: You would need to properly add a addres name to your TNSNAMES.ORA, for example: MYCONNECTION.TEST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = Lorac.chem.tamu.edu)(PORT = your server port)) ) (CONNECT_DATA = (SERVICE_NAME = your ORACLE server SID) ) ) I don't know if your instance means the Schema name or the SID of the SERVER, if it's the SID you should put it in the text before as: (SERVICE_NAME = Stockroom2) like shown here Configuring TNSNAMES.ora then in your app you use a connection string like this: <add name="MyDatabase" connectionString="Data Source=MYCONNECTION.TEST;User Id=Inventory_mgmt;Password=invmgmt;Integrated Security=no;"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference Between 2 DataTable I have 2 DataTable and I want to create a third DataTable that contais the difference between DataTable 1 and DataTable 2. For example, DataTable1 has the original data, and the DataTable 2 is just a copy, like a replication. But when you insert a new row in DataTable1, the DataTable2 has just insert the same row. Nowaday my code do a compare between DataTable1 and DataTable2, if not equals (1 row or more was inserted), DataTable2 record all data from DataTable1 again. How can I do a select command, that do this difference and record those datas in a third DataTable ? A: Try something like this: table1.Merge(table2); DataTable changesTable = table1.GetChanges(); A: Using only SQL you can use UNION to easily find differences, there is an excellent article on the subject here: http://weblogs.sqlteam.com/jeffs/archive/2004/11/10/2737.aspx The query will return an empty row set when the tables match, otherwise the differing rows are returned. A: I will consider that there are two columns to identify the tables(col1,col2) var rowsOnlyInDt1 = dt1.AsEnumerable().Where(r => !dt2.AsEnumerable() .Any(r2 => r["col1"].Trim().ToLower() == r2["col1"].Trim().ToLower() && r["col2"].Trim().ToLower() == r2["col2"].Trim().ToLower())); DataTable result = rowsOnlyInDt1.CopyToDataTable();//The third table
{ "language": "en", "url": "https://stackoverflow.com/questions/7560742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dependency Injection in a WPF Application with Many Windows Is it "correct" to have many factories when using Dependency Injection with a "line of business" application? By, "line of business" application I mean an application like SalesForce.com or a CRM system with many functions and associated windows/forms. Actually, SalesForce.com may be a bad example. The HTTP GET/POST mechanic creates obvious composition roots at which to invoke the DI container. But what of a long running WPF application, for example? Creating the object graphs for all possible functions seems wasteful when many of them won't be invoked during that session or maybe never if that person's role limits their use of the application. It would appear that the solution is to use the DI container to resolve each window/form as it is needed. But: * *This goes against the DI principle of only resolving at the composition root, in this case resolving the parent window at application start. *This would require a factories to create the windows/forms to prevent references to the DI container in application code. It seems that factories would multiply quickly. This seems to increase rather than decrease complexity by requiring the creation of factories whose sole function create an "artificial" composition root to hide the call to the DI Resolve method. I also understand that ideally factories should not reference the DI container, but in this case there is an object graph to resolve and not using the DI container would require me to resolve the dependecies myself, apparently defeating the purpose of using the DI container. To be honest, the application isn't that complicated right now and the factories wouldn't complicate matters greatly. However, I wrote this isolated application using DI as a learning exercise to introduce it to myself and the small dev team I am on. Most of the team is unfamiliar with DI and will wonder at the effectiveness of DI when it required extra code and classes simply to hide the introduction of the DI container. FWIW, I did pick up a copy of Mark Seemann's "Dependency Injection in .NET", but the WPF example seems too simple to cover this exact scenario, as might be expected in an introductory text. His example has a single MVVM form created in the OnStartup event. Any insight appreciated. Thanks. A: I run up against this all the time in creating Views/ViewModels in WPF and Silverlight. In fact I recently made a comment on a post in Mark Seemann's blog along these lines: See my Comment at Monday, September 19, 2011 10:39:25 PM. (The post itself is interesting as well, discussing where Mark feels it is acceptable to reference the container.) If you use Castle Windsor for DI, you can use the TypedFactoryFacility which allows you to avoid referencing the container in your factory. My general approach when not using Windsor is to just create a generic abstract factory that does call Resolve() and be done with it. This still feels like service location to me (i.e. it feels "wrong"), but I have yet to find another (non-Windsor) solution that isn't painful to code and maintain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: unmanaged dll, hangs / waiting / slow I've got an unmanaged dll working in asp.net running on IIS 7. Most of the time after a few request the application hangs for about a minute before continue or showing an error. Do I have to dispose, release or call the DLLdifferent? [DllImport("Fan.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern int GET_CALCULATION_FAN_ALONE_PC(ref string input, string buffer); Any help would be appreciated! A: It seems that the unmanged code is not thread safe. Here is a good discussion on the issue you are having: Answers From http://social.msdn.microsoft.com/Forums/en-US/asmxandxml/thread/504cdc70-16f1-4c39-a0c0-1d47b2a64f7b/ The thing to be careful about is that the unmanaged code may not be thread-safe. In the context of a web service, each request will arrive on a different thread, and the unmanaged code may not handle that. These crashes may be signs of memory corruption caused by code that has not been tested in a multithreaded environment. There are a couple of different threading issues with unmanaged code that you might like to call from managed code: 1. It might not be safe to call the unmanaged code on more than one thread at the same time. This issue can be solved with correct locking. I stress correct. 2. The unmanaged code may somehow depend on being called on the same single thread all the time. This is less likely, but possible. This cannot be solved directly within an ASP.NET web application or web service application, unless you somehow start up a thread when the application starts, and marshall all requests for this code to that one thread. 3. The unmanaged code may be COM code and depend on running in a particular apartment. I don't know if there's a solution to that. There will not be a general solution to this problem, at least not that you can solve. The general solution is for the developer or vendor of the unmanaged code to make their code safe to be called from managed code on multiple threads. Until they've thoroughly tested their code in that environment, you can't really be sure it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing attribute/option data without EAV I am making a local cafe listing website and I wanted to get some feedback on my database structure. The cafes have a bunch of attributes that they can select one or many on any option. Here is how I am planing on storing their data. TABLE: 'cafes' CREATE TABLE `cafes` ( `cafe_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `cafe_types` text NOT NULL, `location_types` text NOT NULL, `amenities` varchar(255) NOT NULL, `parking` varchar(255) NOT NULL, PRIMARY KEY (`cafe_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 ; TABLE: 'cafes_option_map' CREATE TABLE `cafes_option_map` ( `map_id` int(11) NOT NULL AUTO_INCREMENT, `column_name` varchar(30) NOT NULL, `cafe_id` int(11) NOT NULL, `name_id` int(11) NOT NULL, PRIMARY KEY (`map_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; TABlE: 'cafes_option_name' CREATE TABLE `cafes_option_name` ( `name_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, PRIMARY KEY (`name_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Columns cafe_types, location_types, amenities, and parking are multi-selects with many "options". These options need to be sorted and filtered by. My questions are: * *is this a good why of storing the data? *Would there be a better way to do it. My idea is that the 'cafes' table will contain a comma separated list of the attribute names (like human legible) for easy display with minimal DB calls and then also have the option table for filter and sorting queries. I can make some sample data for the tables if that is easer to understand. How would you suggest you store such data? I don't want a EAV structure. A: is this a good why of storing the data? Hell no! CSV is evil CSV cannot be indexed in a sane manner. Matching on CSV's is slow. Joining on CSV's is a nightmare. Once you start using them you will get bold, because you will start to pull out your hair every time you need to write a new query. Would there be a better way to do it. EAV would be much, much better than CSV. But I don't want EAV Good for you, seriously. EAV is just a stop gap measure. If you want to link n-attributes to n-cafes, you have a n-n relation and that requires a join table. table cafe ------------ id integer PK autoincrement name address table cafe_type ---------------- id integer PK autoincrement name table cafetype_link ------------------- cafe_id integer cafe_type_id integer primary key PK (cafe_id, cafe_type_id) Then you do a query on cafe-types like so: SELECT c.* FROM cafe c INNER JOIN cafetype_link cl ON (c.id = cl.cafe_id) INNER JOIN cafe_type ct ON (ct.id = cl.cafe_type_id) WHERE cafe_type.name = 'irish pub' This works very simple and very fast. However it is not as flexible as EAV.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cosine Similarity Code (non-term vectors) I am trying to find the cosine similarity between 2 vectors (x,y Points) and I am making some silly error that I cannot nail down. Pardone me am a newbie and sorry if I am making a very simple error (which I very likely am). Thanks for your help public static double GetCosineSimilarity(List<Point> V1, List<Point> V2) { double sim = 0.0d; int N = 0; N = ((V2.Count < V1.Count)?V2.Count : V1.Count); double dotX = 0.0d; double dotY = 0.0d; double magX = 0.0d; double magY = 0.0d; for (int n = 0; n < N; n++) { dotX += V1[n].X * V2[n].X; dotY += V1[n].Y * V2[n].Y; magX += Math.Pow(V1[n].X, 2); magY += Math.Pow(V1[n].Y, 2); } return (dotX + dotY)/(Math.Sqrt(magX) * Math.Sqrt(magY)); } Edit: Apart from syntax, my question was also to do with the logical construct given I am dealing with Vectors of differing lengths. Also, how is the above generalizable to vectors of m dimensions. Thanks A: If you are in 2-dimensions, then you can have vectors represented as (V1.X, V1.Y) and (V2.X, V2.Y), then use public static double GetCosineSimilarity(Point V1, Point V2) { return (V1.X*V2.X + V1.Y*V2.Y) / ( Math.Sqrt( Math.Pow(V1.X,2)+Math.Pow(V1.Y,2)) Math.Sqrt( Math.Pow(V2.X,2)+Math.Pow(V2.Y,2)) ); } If you are in higher dimensions then you can represent each vector as List<double>. So, in 4-dimensions the first vector would have components V1 = (V1[0], V1[1], V1[2], V1[3]). public static double GetCosineSimilarity(List<double> V1, List<double> V2) { int N = 0; N = ((V2.Count < V1.Count) ? V2.Count : V1.Count); double dot = 0.0d; double mag1 = 0.0d; double mag2 = 0.0d; for (int n = 0; n < N; n++) { dot += V1[n] * V2[n]; mag1 += Math.Pow(V1[n], 2); mag2 += Math.Pow(V2[n], 2); } return dot / (Math.Sqrt(mag1) * Math.Sqrt(mag2)); } A: The last line should be return (dotX + dotY)/(Math.Sqrt(magX) * Math.Sqrt(magY))
{ "language": "en", "url": "https://stackoverflow.com/questions/7560760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Returning a php element with a count with javascript I have a site where people search for music and the search is recorded with their id attached to it. I am trying to make a feed out of it and it has worked thus far. However, the feed includes a javascript function where it makes their search into a link which when clicked, populates the search field and completes the search. The problem is I am looking to make each link it's specific search, but what ends up happening is it sets the value of the php variable to the last search in the array. What I'm now trying to do is set the php search variable with an counter to call that later in javascript. I know this sounds super confusing / not clear, but I'm trying my best. Maybe the code will help. $sql_userSearch = mysql_query("SELECT id, searchstring, timecount, userSearch FROM trending WHERE userSearch != 0 ORDER BY timecount DESC LIMIT 50"); $counter = 1; while($row = mysql_fetch_array($sql_userSearch)){ $search_id = $row["id"]; $searcher_id = $row["userSearch"]; $the_search[$counter] = $row["searchstring"]; $search_date = $row["timecount"]; $convertedTime = ($myObject -> convert_datetime($search_date)); $whenSearch = ($myObject -> makeAgo($convertedTime)); $search_date = $row["timecount"]; $searchDisplayList .= '<table style="border:#999 1px solid; border-top:none;" background="img/searchBG.png" cellpadding="5" width="100%"> <tr> <td width="10%" valign="top"><img src="https://graph.facebook.com/'. $searcher_id . '/picture" width="35" height="35"></td> <td width="90%" valign="top" style="line-height:1.5em;"> <span class="liteGreyColor textsize9"><strong>' . $searcher_id . '</strong></a> searched for </span> <a href="#" onClick="swapSearch()">' . $the_search[$counter] . '</a></br> ' . $whenSearch . ' </td> </tr></table>'; $counter++; } then later on, this is the javascript I am using to return the link. <script type="text/javascript"> function swapSearch(){ document.getElementById('s').value = "<?= $the_search[$counter] ?>"; $('#searchForm').submit(); } </script> EDIT: I just ended up using some javascript that grabbed the text of the link and populated the search form. Way easier than what I was trying to do. <script type="text/javascript"> $("a.friendSearchLink").live("click",function(a) { a.preventDefault(); var searchTerm = $(this).text(); document.getElementById('s').value = searchTerm; $("#searchForm").submit(); }); </script> A: PHP is preprocessed, you can only echo a value prior to the page being sent to your client. In order to do what you're wanting to do, you must send an ajax call to a page that contains the information you're looking for, otherwise your output will be completely static. A: you could store all the searches from $the_search into a JS array and then pass in $counter to swapSearch('.$counter.'). then you can look up in js whatever the search is. The only other question I have though is are you submitting your search form as a post? Because if you change it to read from $_GET, you can just use the link to run the search just by setting href="?q=$the_search[$counter]". Other option is to pass the search id in the url and just use php to load the search result/keywords.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strategy for locating ViewModels when views are hierarchical and need to be swapped in and out Let's say I'm building a navigation system for a car: * *The main window would contain a screen, mode buttons, and a volume control. *Depending on the mode of the system, the screen would either show an audio, climate, or navigation panel. *When in audio mode, there would be another set of mode buttons and a panel that could either show radio, CD, or MP3 controls. My strategy for arrangements like this in the past has been to have my view models follow the exact same hierarchy as the views. So: * *The MainViewModel would have a ScreenViewModel. *The ScreenViewModel would have an AudioViewModel, ClimateViewModel, and NavigationViewModel. It would also have a CurrentViewModel property, which would be set to either the audio, climate or navigation view model, depending on the system mode. *The AudioViewModel would be similar to the ScreenViewModel, holding view models for each of the audio system's modes (radio, CD, and MP3) as well as a property for storing the view model for the current mode. The XAML for binding the view to the view model would go something like this: <Window.Resources> <DataTemplate DataType="{x:Type vm:AudioViewModel}"> <view:AudioPanel /> </DataTemplate> <DataTemplate DataType="{x:Type vm:ClimateViewModel}"> <view:ClimatePanel /> </DataTemplate> <DataTemplate DataType="{x:Type vm:NavigationViewModel}"> <view:NavigationPanel /> </DataTemplate> </Window.Resources> <ContentControl Content="{Binding CurrentViewModel}" /> If a user is listening to the radio and decides to enter a destination into the navigation system, they would click the Navigation mode button. There would be a command on MainWindowViewModel that changes the system mode to "Navigation" and sets the CurrentViewModel to the NavigationViewModel. This would cause the NavigationView to be swapped in. Very clean solution. Unfortunately, while doing things this way works well in execution mode, it breaks down when trying to work with a subordinate view (say AudioPanel) in Expression Blend because the parent view model (MainWindowViewModel) doesn't exist to provide an AudioViewModel. The solution that seems to be supported in toolkits such as MVVM Light and Simple MVVM is to use a ViewModelLocator instead, then have the view set it's own DataContext by binding to the correct property on the locator. The locator then serves up an instance of the view model. The "ViewModelLocator way of doing things" solves the "designability" issue, but it's not clear to me how to represent hierarchical relationships and handle swapping of one view for another. Conceptually, it just makes more sense to me to have the view model hold the child view models. It represents the hierarchy of views correctly, swapping of views is a snap, and if a view is no longer needed, the associated view model and all its subordinates will be garbage collected simply by dropping the reference to the parent. Question What is the best practice for architecting a ViewModelLocator to handle hierarchical views, swapping of views in and out based on a system mode, and deletion of views? Specifically: * *How do you organize the views models so hierarchical relationships are clearly represented? *How do you handle swapping of one existing view out for another (say replacing the audio panel with the navigation panel)? *How do you ensure that parent and child view models get released for garbage collection when the associated parent view is no longer needed? A: It seems like the current view in the hierarchy of views is part of the view 'state', so it would have a 'model' (viewmodel) entity of its own that manages this relationship. I would not use the IoC container for that, but I would use it to register a factory that the 'view manager' uses to create the 'sub-views'. A: It turns out, there's a XAML design attribute in Visual Studio/Blend that allows you to set the design-time DataContext of an element. This only applies during design time, so it should be possible to continue hooking up the DataContext using data templates (i.e., a ViewModelLocator or ViewManager may not be needed at all). For example, say you have a view called AudioPanel and a view model called AudioViewModel. You would just need to initialize some design-time data in AudioViewModel... public class AudioViewModel : ViewModelBase { public int Volume { get; set; } public AudioMode Mode { get; set; } public ViewModelBase ModePanelViewModel { get; set; } public AudioViewModel() { if (IsInDesignMode) { Volume = 5; Mode = AudioMode.Radio; ModePanelViewModel = new RadioViewModel(); } } } ...then in your view, you would just need to declare a d:DataContext attribute... <UserControl x:Class="NavSystem.Views.AudioPanel" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:NavSystem.ViewModels" mc:Ignorable="d" d:DataContext="{d:DesignInstance vm:AudioViewModel, IsDesignTimeCreatable=True}"> As long as you write a default constructor for each view model that comes into play during design time, it should be possible to view composite user interfaces in VS or Blend designers. See this blog post for more details: http://karlshifflett.wordpress.com/2009/10/28/ddesigninstance-ddesigndata-in-visual-studio-2010-beta2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7560765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add img on top of img html I have two img tags as shown below, but the img tag with the class portfolioImage1 always shows up underneath the img tag with the class portfolioItem1. How can I achieve having it the other way around so that portfolioImage1 is above portfolioItem1? <div class="portfolioContainer"> <img class="portfolioImage1" src="img/image1.png" /> <img class="portfolioItem1" src="img/portfolioItem.png" /> </div> CSS .portfolioContainer { height: 400px; width: 490px; left: 400px; top: 275px; position: absolute; } .portfolioItem1 { left: 20px; z-index: 1; position: absolute; } .portfolioImage1 { z-index: 2; } A: EDIT: You need to add a position relative, absolute or fixed to the portfolioImage1 in order for z-index to work. OLD: If you mean behind the image try using z-index: <div class="portfolioContainer" style="position: relative;"> <img class="portfolioImage1" src="img/image1.png" style="position: relative; z-index: 2" /> <img class="portfolioItem1" src="img/portfolioItem.png" style="position: relative; z-index: 1" /> </div> If you mean below, you can use absolute or relative positioning, but we need dimensions and desired results. For example, say that image1.png is 20px high and portfolioItem.png is 25px high: <div class="portfolioContainer"> <img class="portfolioImage1" src="img/image1.png" style="position: relative; top: 25px;" /> <img class="portfolioItem1" src="img/portfolioItem.png" style="position: relative; top -20px" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7560766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get all folders paths that contains music (mp3) in Cocoa? I'm new in Cocoa.I'm trying to scan computer for music folders,within my application. But I have some logic for it. What I need to start scaning from /Users , for example if I have /Users/music/anotherMusic and /Users/music/music2/music3 , I need to be able to get only the top for that folders that contains music (/Users/music ). And also need to continue iterate in subfolders to have a count of music files in the root folder (/Users/music). And so on with the same logic continue scanning whole computer.And results should be displayed in table, for example RESULTS should be like this - -/Users/myComputer/iTunes - 77 folders, 500 music files - /Users/myComputer/Documents/Music -15 music folders,400 music files - /Users/myComputer/Downloads/Media -20 music folders, 325 music files (count of all subdirectories with music) How I can do it? What I did ,it is in the code below. But it's going deep all the way down, and give me each path that contains .mp3 music, but I need logic as mentioned above. NSFileManager *manager = [NSFileManager defaultManager]; NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:@"/Users/"]; NSString * file; while((file=[direnum nextObject])) { NSString * FullPath=[NSString stringWithFormat:@"/Users/%@",file]; if ([file hasSuffix:@".mp3"]) { ///gives a music file path that contains mp3, or I can cut last part, and get the folder path. But no logic as should be. } } Any ideas, or help appreciated. Thanks. A: Correct me if I am wrong. You want to get the number of mp3 in your folder, but while a folder only contains folders and mp3 files, the mp3-count is for its parent folder (and if the parent itself only contains folders and mp3s, it counts for its grand-parent, etc.) right ? [manager enumeratorAtPath] is quite useful, but in this case it will certainly require you to maintain a stack to keep track of your browsed files. Recursion is bliss, here. - (BOOL)isMp3File:(NSString*)file { return [file hasSuffix:@".mp3"]; } - (BOOL)isHiddenFile:(NSString*)file { return [file hasPrefix:@"."]; } - (void)parseForMp3:(NSMutableDictionary*)dic inPath:(NSString*)currentPath forFolder:(NSString*)folder { BOOL comboBreak = false; NSFileManager *fileManager = [NSFileManager defaultManager]; NSError* error; NSArray* files = [fileManager contentsOfDirectoryAtPath:currentPath error:&error]; if (error) { //throw error or anything } for (NSString *file in files) { BOOL isDirectory = false; NSString *fullPath = [NSString stringWithFormat:@"%@/%@", currentPath, file]; [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory]; comboBreak = comboBreak || (!isDirectory && ![self isMp3File:file] && ![self isHiddenFile:file]); if (comboBreak) break; } for (NSString *file in files) { BOOL isDirectory = false; NSString *fullPath = [NSString stringWithFormat:@"%@/%@", currentPath, file]; [fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory]; if (isDirectory) { if (!comboBreak) { [self parseForMp3:dic inPath:fullPath forFolder:folder]; } else { [self parseForMp3:dic inPath:fullPath forFolder:fullPath]; } } else if ([self isMp3File:file]) { NSNumber *oldValue = [dic valueForKey:folder]; oldValue = [NSNumber numberWithUnsignedInteger:[oldValue unsignedIntegerValue] + 1]; [dic setValue:oldValue forKey:folder]; } } } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [self parseForMp3:dic inPath:@"/Users/panosbaroudjian" forFolder:@"/Users/panosbaroudjian"]; NSLog(@"%@", dic); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scriptaculous Builder Not Setting Selected Value In FireFox I am trying to build a select options list and apply a default value to it. It seems to work in Chrome, but not in Firefox. My code is: var sel2 = Builder.node('select',{ name: 'type_' + tId, id: 'type_' + tId }); $A(templateTypes).each(function(t,idx){ var o = Builder.node('option',{value:dataID},DataName); sel2.appendChild(o); if (curID == dataID) { $(sel2).selectedIndex = idx; } }); I tried things like: if (curID == dataID) { var o = Builder.node('option',{value:dataID,selected:'selected'},DataName); } That even though set selected="selected" in Firebug, it didn't apply to what was shown. Hard refreshing doesn't appear to solve it either. Does someone have a solution that will work across all browsers? Thanks. A: It seems adding a new node to the select box confuses Firefox. How about this instead: var sel2 = Builder.node('select',{ name: 'type_' + tId, id: 'type_' + tId }); // store the desired index in this var selectedIndex = 0; $A(templateTypes).each(function(t,idx){ var o = Builder.node('option',{value:dataID},DataName); sel2.appendChild(o); if (curID == dataID) { selectedIndex = idx; } }); // now set the selected index _after_ we've added all the options: sel2.selectedIndex = selectedIndex; Seems to work in my brief test.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Shared Header Causes Multiply Defined Symbol Error Consider the following header file example: shared_example.h #ifndef SHARED_EX #define SHARED_EX const int Shared_Int = 1; const char * Shared_CString = "This is a string"; #endif The shared_example.h file is included in multiple compilation units, which leads the linker to (correctly) complain that: error LNK2005: "char const * const Shared_CString" (?Shared_CString@@3PBDB) already defined in First_Compilation_Unit.obj Removing the Shared_CString constant from this file eliminates the issue. So, I have two questions. First, why doesn't the Shared_Int constant trigger the same issue? Second, what is the appropriate way to allow separate compilation units to make use of the same constant string value? A: shared_example.h #ifndef SHARED_EX #define SHARED_EX extern const int Shared_Int; extern const char * Shared_CString; #endif shared_example.c const int Shared_Int = 1; const char * Shared_CString = "This is a string"; A: The first declaration is of a constant integral value. In C++, const has internal linkage by default. The second declaration is of a pointer to const char. That declaration is not const itself, and has no other linkage specifiers, so it does not have internal linkage. If you changed the declaration to const char * const it would then become a const pointer to const char and have internal linkage. A: Making them static will solve the issue. You are not seeing the Shared_Int because you are not using it in more then one of the c modules that you compile. Edit: My bad - what I say is valid for C. Didn't saw the c++ tag. Sorry
{ "language": "en", "url": "https://stackoverflow.com/questions/7560792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do I get the index in a TemplateCollectionView? So I followed the sproutcore "getting started" guide, and started wandering off the path to see if I could do what I meant easily. And here I am witht this templates, that represents a list of file inputs : {{#collection SC.TemplateCollectionView contentBinding="Upload.uploadListController"}} <label>{{content.title}}</label><input type="file" name="upload[]"/> {/collection}} Nice. Now what I'd like to do is benefit from the label for attribute to point to the corresponding input. So basically, I'd like to output something like this: <label for="upload-0">Some label</label> <input id="upload-0" type="file" name="upload[]"/> <label for="upload-1">Some otherlabel</label> <input id="upload-1" type="file" name="upload[]"/> <!-- you get it --> How do I do that? I did not find the answer neither on the using handlebars page nor on the sproutcore documentation on SC.ArrayController Am I looking in the wrong place? Am I trying to do something I should do in another, more sproutcore-ish way? A: The only way I see to do this is adding an id field in your model. So you could use this id in the template. {{#collection SC.TemplateCollectionView contentBinding="Upload.uploadListController"}} <label {{bindattr for="content.id"}} >{{content.title}}</label> <input {{bindattr id="content.id"}} type="file" name="upload[]"/> {{/collection}}
{ "language": "en", "url": "https://stackoverflow.com/questions/7560801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }