text
stringlengths
8
267k
meta
dict
Q: Why is presentModalViewController not working? I am presenting a modalcontroller in a view, after i dissmiss the view i want to present another modalView but the code is not working, i have a delegate method that is being called when i press a button on the first modal vieview in witch i have the code. inside the parentView the method for the firstview delegat: -(void)newMessageModalView:(NewMessageModalView *)controller didFinishSelecting:(int)selectedChannel{ [self dismissModalViewControllerAnimated:YES]; SecondView * detailView = [[SecondView alloc] initWithNibName:@"SecondView" bundle:nil]; [self presentModalViewController:SecondView animated:YES]; [detailView release]; [self dismissModalViewControllerAnimated:YES]; } A: You are presenting SecondView, which is your class and not your instance. Even if that was right, you are dismissing it straight away. A: Move [self dismissModalViewControllerAnimated:YES]; to detailView.m -(void)newMessageModalView:(NewMessageModalView *)controller didFinishSelecting:(int)selectedChannel{ SecondView * detailView = [[SecondView alloc] initWithNibName:@"SecondView" bundle:nil]; [self presentModalViewController:SecondView animated:YES]; [detailView release]; } For example, in detailView.m - (void)cancelBtnTouched:(id)sender { [self dismissModalViewControllerAnimated:YES]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent duplicate content issue when having same user comments in multiple content pages? I have a question about duplicate content issue. I have pages with article, one page = one article. Below the article is discussion forum / comments box. These articles have sometimes very similar subjects. So it usually happens that user comments / asks the same thing, which was already discussed in similar older article. But that's because the user doesn't know about the older article(s). So for certain articles on the same subject I use one comment's box for multiple articles. All the articles are my original content, however the second part of the page would be purposely duplicate content, because in this case - it's good for user ( that's what Google says webmaster should do - what's good for user ). So my question is - should I fear this could be treated by search engines as duplicate content ? And if yes, what steps should I take to preserve this functionality and not to be penalized by Google and others ? A: I don't think that you have to take care about this. Infact the duplicated content will be a little part of the whole content (which you say is brand new). Another fact you have to bear in mind is that also if the topic is the same it's very hard that people will write them in the same way. A: Google covered this a few years ago: The duplicate content "penalty" isn't to discourage webmasters from referencing the same content via more than one URL, but it is intended to prevent mass spamming of duplicate content from your (or worse, someone else's) site. You should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: node.js - using weld with express? I'm new to node.js, and attempting to use weld to render templates on the server-side and using express as the router. However the examples for node.js doesn't show serving the content, and am fuzzy on how this would work with express: var fs = require('fs'), jsdom = require('jsdom'); jsdom.env( './test.html', ['./jquery.js', './weld.js'], function(errors, window) { var data = [{ name: 'hij1nx', title : 'code slayer' }, { name: 'tmpvar', title : 'code pimp' }]; window.weld(window.$('.contact')[0], data); } ); Help or example would be appreciated. A: I think something like this would work. Haven't tested though. var fs = require('fs'), jsdom = require('jsdom'), app = require('express').createServer(); app.get('/', function(req, res) { jsdom.env('./test.html', ['./jquery.js', './weld.js'], function(errors, window) { var data = [{ name : 'hij1nx', title : 'code slayer' }, { name : 'tmpvar', title : 'code pimp' }]; window.weld(window.$('.contact')[0], data); res.send(window.document.innerHTML); //after the welding part we just send the innerHTML window.close(); // to prevent memory leaks of JSDOM }); }); app.listen(3001);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Loop until passcode is unique This is for a file sharing website. In order to make sure a "passcode", which is unique to each file, is truely unique, I'm trying this: $genpasscode = mysql_real_escape_string(sha1($row['name'].time())); //Make passcode out of time + filename. $i = 0; while ($i < 1) //Create new passcode in loop until $i = 1; { $query = "SELECT * FROM files WHERE passcode='".$genpasscode."'"; $res = mysql_query($query); if (mysql_num_rows($res) == 0) // Passcode doesn't exist yet? Stop making a new one! { $i = 1; } else // Passcode exists? Make a new one! { $genpasscode = mysql_real_escape_string(sha1($row['name'].time())); } } This really only prevents a double passcode if two users upload a file with the same name at the exact same time, but hey better safe than sorry right? My question is; does this work the way I intend it to? I have no way to reliably (read: easily) test it because even one second off would generate a unique passcode anyway. UPDATE: Lee suggest I do it like this: do { $query = "INSERT IGNORE INTO files (filename, passcode) values ('whatever', SHA1(NOW()))"; $res = mysql_query($query); } while( $res && (0 == mysql_affected_rows()) ) [Edit: I updated above example to include two crucial fixes. See my answer below for details. -@Lee] But I'm afraid it will update someone else's row. Which wouldn't be a problem if filename and passcode were the only fields in the database. But in addition to that there's also checks for mime type etc. so I was thinking of this: //Add file $sql = "INSERT INTO files (name) VALUES ('".$str."')"; mysql_query($sql) or die(mysql_error()); //Add passcode to last inserted file $lastid = mysql_insert_id(); $genpasscode = mysql_real_escape_string(sha1($str.$lastid.time())); //Make passcode out of time + id + filename. $sql = "UPDATE files SET passcode='".$genpasscode."' WHERE id=$lastid"; mysql_query($sql) or die(mysql_error()); Would that be the best solution? The last-inserted-id field is always unique so the passcode should be too. Any thoughts? UPDATE2: Apperenatly IGNORE does not replace a row if it already exists. This was a misunderstanding on my part, so that's probably the best way to go! A: Strictly speaking, your test for uniqueness won't guarantee uniqueness under a concurrent load. The problem is that you check for uniqueness prior to (and separately from) the place where you insert a row to "claim" your newly generated passcode. Another process could be doing the same thing, at the same time. Here's how that goes... Two processes generate the exact same passcode. They each begin by checking for uniqueness. Since neither process has (yet) inserted a row to the table, both processes will find no matching passcode in database, and so both processes will assume that the code is unique. Now as the processes each continue their work, eventually they will both insert a row to the files table using the generated code -- and thus you get a duplicate. To get around this, you must perform the check, and do the insert in a single "atomic" operation. Following is an explanation of this approach: If you want passcode to be unique, you should define the column in your database as UNIQUE. This will ensure uniqueness (even if your php code does not) by refusing to insert a row that would cause a duplicate passcode. CREATE TABLE files ( id int(10) unsigned NOT NULL auto_increment PRIMARY KEY, filename varchar(255) NOT NULL, passcode varchar(64) NOT NULL UNIQUE, ) Now, use mysql's SHA1() and NOW() to generate your passcode as part of the insert statement. Combine this with INSERT IGNORE ... (docs), and loop until a row is successfully inserted: do { $query = "INSERT IGNORE INTO files (filename, passcode) values ('whatever', SHA1(NOW()))"; $res = mysql_query($query); } while( $res && (0 == mysql_affected_rows()) ) if( !$res ) { // an error occurred (eg. lost connection, insufficient permissions on table, etc) // no passcode was generated. handle the error, and either abort or retry. } else { // success, unique code was generated and inserted into db. // you can now do a select to retrieve the generated code (described below) // or you can proceed with the rest of your program logic. } Note: The above example was edited to account for the excellent observations posted by @martinstoeckli in the comments section. The following changes were made: * *changed mysql_num_rows() (docs) to mysql_affected_rows() (docs) -- num_rows doesn't apply to inserts. Also removed the argument to mysql_affected_rows(), as this function operates on the connection level, not the result level (and in any case, the result of an insert is boolean, not a resource number). *added error checking in the loop condition, and added a test for error/success after loop exits. The error handling is important, as without it, database errors (like lost connections, or permissions problems), will cause the loop to spin forever. The approach shown above (using IGNORE, and mysql_affected_rows(), and testing $res separately for errors) allows us to distinguish these "real database errors" from the unique constraint violation (which is a completely valid non-error condition in this section of logic). If you need to get the passcode after it has been generated, just select the record again: $res = mysql_query("SELECT * FROM files WHERE id=LAST_INSERT_ID()"); $row = mysql_fetch_assoc($res); $passcode = $row['passcode']; Edit: changed above example to use the mysql function LAST_INSERT_ID(), rather than PHP's function. This is a more efficient way to accomplish the same thing, and the resulting code is cleaner, clearer, and less cluttered. A: I'd personally would have write it on a different way but I'll provide you a much easier solution: sessions. I guess you're familiar with sessions? Sessions are server-side remembered variables that timeout at some point, depending on the server configuration (the default value is 10 minutes or longer). The session is linked to a client using a session id, a random generated string. If you start a session at the upload page, an id will be generated which is guaranteed to be unique as long the session is not destroyed, which should take about 10 minutes. That means that when you're combining the session id and the current time you'll never have the same passcode. A session id + the current time (in microseconds, milliseconds or seconds) are NEVER the same. In your upload page: session_start(); In the page where you handle the upload: $genpasscode = mysql_real_escape_string(sha1($row['name'].time().session_id())); // No need for the slow, whacky while loop, insert immediately // Optionally you can destroy the session id If you do destroy the session id, that would mean there's a very slim chance that another client can generate the same session id so I wouldn't advice that. I'd just allow the session to expire. A: Your question is: does this work the way I intend it to? Well, I'd say... yes, it does work, but it could be optimized. Database To make sure to not have the same value in the field passcode on the database layer, add a unique key to this: /* SQL */ ALTER TABLE `yourtable` ADD UNIQUE `passcode` (`passcode`); (duplicate key handling has to be taken care of than ofc) Code To wait a second until a new Hash is created, is ok, but if you're talking heavy load, then a single second might be a tiny eternity. Therefore I'd rather add another component to the sha1-part of your code, maybe a file id from the same database record, userid or whatever which makes this really unique. If you don't have a unique id at hand, you still can fall back to a random number rand-function in php. I don't think mysql_real_escape_string is needed in this context. The sha1 returns a 40-character hexadecimal number anyway, even if there are some bad characters in your rows. $genpasscode = sha1(rand().$row['name'].time()); ...should suffice. Style Two times the passcode generation code is used in your code sample. Start cleaning this up in moving this into a function. $genpasscode = gen_pc(row['name']); ... function gen_pc($x) { return sha1($row[rand().$x.time()); } If I'd do it, I'd do it differently, I'd use the session_id() to avoid duplicates as good as possible. This way you wouldn't need to loop and communicate with your database in that loop possibly several times. A: You can add unique constraint to your table. ALTER TABLE files ADD UNIQUE (passcode); PS: You can use microtime or uniqid to make the passcode more unique. Edit: You make your best to generate a unique value in php, and unique constraint is used to guarantee that at database side. If your unique value is very unique, but in very rare case it failed to be unique, just feel free to give the message like The system is busy now. Please try again:).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upgrade to iOS 5 caused my app to stop being debugged I have upgraded my iphone to iOS5 to test my application behavior on iOS5 After verified it has issues, i have downgraded my device to iOS 4.3.5 since than I am trying to debug my application using XCode and get the following error: Error starting executable No provisioned iOS device is connected. Does anyone know how to fix this issue - so i can debug my application again? Edit: Also another relevant piece of info when I use the configuration drop down selector i get Under Active Executable - "no device available" A: I have managed to fix the issue: I took a look at the following similar question : Xcode - No provisioned iOS device is connected So i wanted to see what i see in the snapshot that the user had : and there it was... I didn't see any information like he did, all i saw was A button called "enable for debugging" if i'm not mistaken. Clicked on it, and Worked like a charm.... :) A: You could try deleting the provisioning profile from the device via the xcode organizer window, or within the Settings App on the device. Then add back your current prov profile from the iOS provisioning portal. Also, make sure you have the debugging symbols/SDKs for that iOS under /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/[insert ios version folder here] And: /Developer/Platforms/iPhoneOS.platform/DeviceSupport/[insert ios version folder here]
{ "language": "en", "url": "https://stackoverflow.com/questions/7579572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rendering an iframe from HTML stored in the DB I have a HTML template that I'm rendering using Django. I'm passing in all the necessary context variables — my_heading is the heading, my_html is the mark-safed html. I'd like to display my_html in the iframe. <html> <head> <title>Iframe Example</title> </head> <body> <p>{% my_heading %}</p> <iframe name="iframe1" width="600" height="400" src="http://www.yahoo.com" frameborder="yes" scrolling="yes"></iframe> </body> </html> Would you know how to do this? All the examples I've found show the iframe pointing to a URL. I'm god-horrible at HTML and JS. :| Thanks A: If I understand you correctly, you just want to show the HTML content that you prepared dynamically with Python within the Django template, correct? If that is the case, you do not need an Iframe. Iframes are only necessary if you would like to integrate parts of a different URI (webpage) as a frame (section on your webpage) on your page. Here a sample: <html> <head> <title>Iframe Example</title> </head> <body> <p>{% my_heading %}</p> <div id="content">{% my_html %}</div> </body> </html> Addition to the above code, base on comment below. Sounds like you want to show an entire page with an Iframe and that this second page comes form another view/url on your box. Then use: <html> <head> <title>Iframe Example</title> </head> <body> <p>{% my_heading %}</p> <iframe src="URL_TO_MY_2ND_VIEW_IN_DJANGO" width="100%" height="300"></iframe> </body> </html> Iframe explanation on W3Schools Iframe description on W3C Site A: Michael Klocker does not answer your question, but the answer he has given is a better solution. You should rather do that. But to answer you question: You can only pass a url to a IFrame, so if really want to use a IFrame, you need to set up second url+view in django to return my_html as the response. I.e. 2 http requests will happen. 1 for the page containing the IFrame, and 1 request for then contents of the IFrame. A: I used this hack to do it. The div is hidden and contains the HTML. The IFrame doesn't point to a location because I don't want any CORS issues. I then inject my HTML into it. <html> <head> <title>Iframe Example</title> </head> <body> <p>{% my_heading %}</p> <iframe name="iframe2" id="iframe2" width="0" height="0" src="" style="border:0px; overflow-x:hidden;"></iframe> <div id="page" style="display:none" >{{ my_html }}</div> <script type="text/javascript"> function getWindow(iframe) { return (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument; } getWindow(document.getElementById('iframe2')).document.open(); getWindow(document.getElementById('iframe2')).document.write(document.getElementById('page').innerHTML); getWindow(document.getElementById('iframe2')).document.close(); document.getElementById('iframe2').style.height = (getWindow(document.getElementById('iframe2')).document.body.scrollHeight + 20) +"px"; document.getElementById('iframe2').style.width = (document.getElementById('iframe2').parentNode.offsetWidth) +"px"; </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Swing time picker Im looking for a pretty and decent time picker component. There are a lot of alternatives for date picking on Swing but no for time. I've seen nice Date/Time components picking on JQuery ( for example: http://trentrichardson.com/examples/timepicker/ ). There is something similar on Swing? Thanks in advance. A: Use JSpinner with SpinnerNumberModel A: I would suggest the TimePicker component of the LGoodDatePicker library. The time can be chosen with the (default) "drop down" menu, with (optional) "spinner" style buttons, or both. Fair disclosure: I'm the primary developer. The TimePicker can be customized with optional settings. A few of the settings are the language (locale), default times in the drop down menu, fonts and colors, display/menu/parsing formats, 12 or 24 hour clock, seconds or nanoseconds precision, and so forth. The library also includes the DatePicker and DateTimePicker components. All three components are easy to use. (They can each be instantiated with a single line of code.) I've pasted screenshots of the components and the demo application below. Project Home page: https://github.com/LGoodDatePicker/LGoodDatePicker . ( Click to enlarge the demo screenshot. ) A: I think you will like the ease of JCalendar. It offers a JDateChooser, a JDayChooser or a JSpinnField, written by Kai Toedter', available here: JCalendar 1.4. You can get your dates like this: java.util.Date fromDate = jDateChooser1.getDate(); JSpinnField lets you set max and min values easily: jSpinField1.setMaximum(59); jSpinField1.setMinimum(0);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Backbone js confusion I have heard a lot about backbone.js and quite frankly I don't understand its concept. Does it require that all the elements should be in single page to work out with its animations and effects ? Or it can grab items from server and load it with transition or i mean different pages but make look like a single page. I didn't understand its concept well, so that's why i am asking. What i am looking for is to combine backbone or any other javascript framework to work with a rails project, that could give some ease transition across pages and can give native application look. A: Backbone is also here to give you structure by being MVC, and it allows to communicate in a really simple way with the server. You'll be able to update / fetch / save your data (your rails models for example) on the server. So you'll need it if you want your user to work on an Ajax page without having to reload the page. For example, you'll fetch all your data from the server when the page loads and then you'll have access to all attributes of your models and will be able to modify it and save it to the server. Moreover, if you want your models to appear with transition, as Backbone is MVC, you'll be able to make that easily. As you have to choose when and where your views will appear on the DOM, you'll be able to put transition at that time. By the way, Backbone works really great with Rails! A: Backbone.js is all about data to be used in some way from your users, think about it as ActiveRecord plus Sinatra (or rails) on a browser, infact, the framework will give you a way to handle your data inside a browser instead of the server. If you are looking for a simple way to add transitions to your existing app/website you could use a jquery plugin like Pagify (it rely on $.getHtml()) modifying it to get a fragment of the subpages like my (buggy) fork.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: close any running application through another application programatically Can we close any other applicaton running in background from our application. Want functionality just similar to Task manager. Is it possible? Any hint. Thanx in advance A: "Victim" application should implement GlobalEventListener, and "killer" application should send a global event for the "victim" application. When "victim" app receives the specific event it closes. If you want to close not your application, there is no way to do that. It just does not know that you want to close it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Entity Framework 4.1 Server-side validation The data I work with can be added from different interfaces. So in my MVC application I need to validate that the data read from the database is correct according to the rules/attribute I sat in my model. Depending on the validation send the user to different Views. I need to do this validation on the SERVER-SIDE var myModelClassObj = myDbContextInheritedModelClass.theDbSetClassMapToModel.Find(123); // How do i validat this A: The DbContext class has a protected ValidateEntity method. You can call that method to validate your entity. public class myDbContextInheritedModelClass : DbContext { public DbEntityValidationResult Validate(object entity) { return ValidateEntity(Entry(entity)); } } Then var myModelClassObj = myDbContextInheritedModelClass .theDbSetClassMapToModel.Find(123); var validationResult = myDbContextInheritedModelClass.Validate(myModelClassObj);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP MySQL_return_rows = echos 1 then 0 I am doing an AJAX post to a PHP processing script. I am checking if MySQL returns any rows befoe proceeding with registration. The problem I'm having - MySQL quickly echoes 1 row and then echoes 0 and proceeds with registration, even if 0 rows exist. Why am I seeing 1 row returned, and then quickly correcting itself? $.ajax({ type: "POST", data: "username="+$(this).attr('username')+"password="+$(this).attr('email')+$(this).attr('password')+$(this).attr('passconf'), url: "includes/register.php", success: function(msg) { alert(data); $("#result").data($data); } }); }); PHP code: $res = mysql_query("SELECT * FROM users WHERE username = '".$username."'"); if (!$res) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } $num = mysql_num_rows($res); echo $num; A: Your event handler probably is failing to prevent the default action, causing the form to be submitted twice (once via ajax, and once via regular browser form submission). Try returning false like this: $(login_form).click(function() { $.ajax({ ... }); return false; }); Returning false prevents the default action and stops bubbling. In case you want bubbling to still apply, you can also explicitly prevent the default like this: $(login_form).click(function(ev) { ev.preventDefault(); $.ajax({ ... }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7579594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WSO2 DSS Cassandra Dependency Is the integrated Cassandra server(version 0.7.x) loosely coupled with WSO2 DSS (version 2.6) or not? Will the usage of a newer version of Cassandra (e.g. 0.8.x) affect the DSS in the low level? Thanks A: The way we integrate Cassandra is by making it into a Carbon component and then integrating its authentication / authorization model to Carbon authn/authzn. There is no issue with having a new version of that component which has the new version of Cassandra. If you're doing that please consider submitting a patch :-) .. we're planning to do it too but if you've done it already please share! DSS has two functions now: storing data (relational storage service (RSS) and Cassandra storage service (CSS) for now .. HDFS next) and making data available via a service or RESTful interface. The latter is only available for relational data right now but the plan is to make it available for Cassandra data too using CQL. When using the data services/resource aspect of course the data does not have to be stored in RSS/CSS itself. A: Current CSS admin interface only works with Cassandra 0.7.x backend ( WSO2 CSS server ). Cassandra 0.8.x support will be available in future DSS and CSS releases. A: No, Cassandra feature will not affect any DSS functionality. It is actually planned to upgrade Cassandra to 0.8 in a future release and also having CQL support in DSS to query Cassandra data stores.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WkHtmlToXSharp not rendering HTML elements as soon as I change the source HTML I have downloaded WkHtmlToXSharp (which uses WkHtmlToPdf under the hood) and opened the solution. When I run the test given with the project - CanConvertFromFile, it gives me a nicely formatted PDF output. But as soon as I delete even a blank space from the source HTML file ( WkHtmlToXSharp.Tests\Resources\page.xhtml) it renders only text with no HTML structure in place i.e. all text on the page is rendered as a single line. I am finding the same problem with my dev project using WkHtmlToXSharp. I suspect this is due to change of character encoding of the source file. Do you know what the character encoding should be? Is this an issue with WkHtmlToPdf as well? Note: Sorry for the slightly misleading tag (WkHtmlToPdf), the site did not allow me to create tag WkHtmlToXSharp. Many Thanks! A: wkhtmltopdf assumes UTF8 as default, but there's a property (WebSettings.DefaultEncoding) which can be used to override the encoding expected. However, your problem looks more like you are re-using a disposed instance or something similar. May you describe a bit deeper your use case.. is it an ASP.NET application? a console project? are you running under visual studio's dev web server? A: I believe the cause of this is in the issue tracker on Pablo's repo. Issue #7: Only works first time datimson commented 25 days ago Also, for the sake of helping anyone else who might have this problem, when debugging with WkHtmlToXSharp in ASP.NET you need to stop the ASP Development server before restarting or rebuilding the application - this is what was causing my text only PDF outputs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: patch on top of patch on the same product not working I installed my product named XYZ.msi. Then, I created a patch (patch1.msp) and applied that patch on my product and it worked fine. I can also see the changes in the Add/Remove Programs. Then I created another patch (patch2.msp) for the same product (XYZ.msi) and when I double clicked it, it says "The program to be upgraded may be missing". I don't understand this when I apply patch2.msp on XYZ.msi without applying patch1.msi first it works fine but applying both patches doesn't work. I am making patches through Windows Installer SDK through msimsp.exe by patch.pcp file. A: This happens because your patches are not authored correctly. A patch shouldn't change the ProductCode or UpgradeCode. It also shouldn't remove components or features from the original installer. You can read more about the patch authoring rules here: http://msdn.microsoft.com/en-us/library/aa367850(VS.85).aspx?ppud=4
{ "language": "en", "url": "https://stackoverflow.com/questions/7579603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: lock - 2 entrance point in the lock and 1 exit point I want to reask my previous question how to obtain a lock in two places but release on one place? because it seems too old and noone sees my updated code. The question is - is my code correct and how to fix it if not? I've tried similar code in the application and it hangs, but I don't now why, so I guess probably my code still wrong... public void obtainLock() { if (needCallMonitorExit == false) { Monitor.Enter(lockObj); needCallMonitorExit = true; } // doStuff } public void obtainReleaseLock() { try { lock (lockObj) { // doAnotherStuff } } finally { if (needCallMonitorExit == true) { needCallMonitorExit = false; Monitor.Exit(lockObj); } } } One of my methods should obtain the lock. another method should obtain the same lock and release it. sometimes just obtainReleaseLock is called. sometimes obtainLock is called (probably several times) and after a while obtainReleaseLock is called. These two methods are always called from the same thread, however lockObj is used in another thread for synchronization. A: If you really need to go this way and don't want to use the alternatives provided by Marc, at least, put it into its own class: public class LockObject { object _syncRoot = new object(); object _internalSyncRoot = new object(); public LockToken Lock() { lock(_internalSyncRoot) { if(!_hasLock) { Monitor.Enter(_syncRoot); _hasLock = true; } return new LockToken(this); } } public void Release() { lock(_internalSyncRoot) { if(!_hasLock) return; Monitor.Exit(_syncRoot); _hasLock = false; } } } public class LockToken : IDisposable { LockObject _lockObject; public LockToken(LockObject lockObject) { _lockObject = lockObject; } public void Dispose() { _lockObject.Release(); } } This would allow you to use it like this: LockObject _lockObj = new LockObject(); public void obtainLock() { _lockObj.Lock(); // doStuff } public void obtainReleaseLock() { using(_lockObj.Lock()) { // doAnotherStuff } } One word of caution: If your thread is aborted after the call to obtainLock and before the call to obtainReleaseLock, your program will deadlock. A: If you use Monitor.Enter you will need to call exactly that many Monitor.Exit calls on the same object, on the same thread. By using a lock block this is automatically done for you - as soon as you are outside the scope of the lock block, the lock count is decreased. Within the same thread it is perfectly legal to lock multiple times on the same object (via both mechanisms). Keeping that in mind, maintaining your own "lock state" variable would only make things more complex. What if two threads access the needCallMonitorExit variable at the same time? If I were you I would stick to lock blocks, and re-order code to fit inside them. Put as little code inside the blocks as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Background service on a Glassfish server is it possible to run a background service/daemon on a glassfish server? Best, T Edit: To clarify things: I mean a daemon like a windows service, that runs in the background and gets triggered by an event. A: Glassfish is Java EE container, so you can deploy any Java EE service: EJB, Webservices, JMS, etc. If you don't want to be bound by Java EE restrictions you could develop Java application, deploy it as OSGI bundle and listen to any events available to Java Runtime.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enum datatype in interface in C# How to use enum datatype in interface? Is this possible? public interface IParent1 { string method1(Test enum); } public class Parent1 : IParent1 { public enum Test { A, B, C } public string method1(Test enum) { return enum.ToString(); } } A: enum is a reserved keyword in C#. You can prefix it with @ if you want to use it as variable name: public enum Test { A, B, C }; public interface IParent1 { string method1(Test @enum); } public class Parent1 : IParent1 { public string method1(Test @enum) { return @enum.ToString(); } } But I don't like using reserved words for variable names. A better approach would be: public enum Test { A, B, C }; public interface IParent1 { string method1(Test test); } public class Parent1 : IParent1 { public string method1(Test test) { return test.ToString(); } } A: Don't see any problem with that. But why do you nest your enum declaration in the interface implementation? Your code will not compile, because: 1. You're using reserved word enum 2. value is not declared Try use this: public enum Test { A, B, C }; public interface IParent1 { string method1(Test @enum);} public class Parent1 : IParent1 { public string method1(Test @enum) { return @enum.ToString(); } } A: If you want your enum to be different in each implementing class you should use a generic interface like public interface MyInterface<T> { string MyMethod(T myEnum) } If it should be the same for all implementing classes just don't put it outside any class: public enum MyEnum { A, B, C } public interface MyInterface { string MyMethod(MyEnum myEnum) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the purpose of extending an anonymous type in Scala? I'm trying to get a better understanding of Scala, and I can't seem to find a valid usecase for code like the following: class C extends { def m() { /* ... */ } } What is the rationale for allowing such constructs? Thanks! A: I guess the only rationale here is "avoid special cases if possible". You can extend any class, an anonymous class is a class, so you can extend an anonymous class. A: That is not, in fact, an anonymous class! It's an early initializer and it runs as part of the constructor that goes before its superclass. Quoting the excellent answer from another stackoverflow question: abstract class X { val name: String val size = name.size } class Y extends { val name = "class Y" } with X If the code were written instead as class Z extends X { val name = "class Z" } then a null pointer exception would occur when Z got initialized, because size is initialized before name in the normal ordering of initialization (superclass before class). A: It's called Early definitions and they deal with super class initialization order problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How would I discover the suppressed error in Valgrind? I have following valgrind output: ==28099== ==28099== HEAP SUMMARY: ==28099== in use at exit: 0 bytes in 0 blocks ==28099== total heap usage: 131 allocs, 131 frees, 3,472 bytes allocated ==28099== ==28099== All heap blocks were freed -- no leaks are possible ==28099== ==28099== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4) --28099-- --28099-- used_suppression: 2 dl-hack3-cond-1 --28099-- used_suppression: 2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a ==28099== ==28099== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4) There are 4 suppressed error. Although there is no leak here, but creats problem while porting to another system. [EDIT] I rerun with the valgrind -v option too. But I don't find any errors there. ==30287== Memcheck, a memory error detector ==30287== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==30287== Using Valgrind-3.6.0.SVN-Debian and LibVEX; rerun with -h for copyright info ==30287== Command: ./EXECUTABLE1 test_input.txt ==30287== --30287-- Valgrind options: --30287-- --suppressions=/usr/lib/valgrind/debian-libc6-dbg.supp --30287-- -v --30287-- --gen-suppressions=all --30287-- --error-limit=no --30287-- Contents of /proc/version: --30287-- Linux version 2.6.38.3.2.amd64-smp (gcc version 4.4.5 (Debian 4.4.5-8) ) #1 SMP Wed Apr 20 17:36:19 CEST 2011 --30287-- Arch and hwcaps: AMD64, amd64-sse3-cx16 --30287-- Page sizes: currently 4096, max supported 4096 --30287-- Valgrind library directory: /usr/lib/valgrind --30287-- Reading syms from /home/path/to/file(0x400000) --30287-- Reading syms from /lib/ld-2.11.2.so (0x4000000) --30287-- Considering /lib/ld-2.11.2.so .. --30287-- .. CRC mismatch (computed cd91cee9 wanted 11b4673c) --30287-- Considering /usr/lib/debug/lib/ld-2.11.2.so .. --30287-- .. CRC is valid --30287-- Reading syms from /usr/lib/valgrind/memcheck-amd64-linux (0x38000000) --30287-- object doesn't have a dynamic symbol table --30287-- Reading suppressions file: /usr/lib/valgrind/debian-libc6-dbg.supp --30287-- Reading suppressions file: /usr/lib/valgrind/default.supp --30287-- REDIR: 0x4016230 (strlen) redirected to 0x380408a7 (vgPlain_amd64_linux_REDIR_FOR_strlen) --30287-- Reading syms from /usr/lib/valgrind/vgpreload_core-amd64-linux.so (0x4a20000) --30287-- Reading syms from /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so (0x4c21000) ==30287== WARNING: new redirection conflicts with existing -- ignoring it --30287-- new: 0x04016230 (strlen ) R-> 0x04c25850 strlen --30287-- REDIR: 0x40160a0 (index) redirected to 0x4c25460 (index) --30287-- REDIR: 0x4016120 (strcmp) redirected to 0x4c25e30 (strcmp) --30287-- Reading syms from /lib/libm-2.11.2.so (0x4e29000) --30287-- Considering /lib/libm-2.11.2.so .. --30287-- .. CRC mismatch (computed dd5c85df wanted ccd85fcf) --30287-- Considering /usr/lib/debug/lib/libm-2.11.2.so .. --30287-- .. CRC is valid --30287-- Reading syms from /lib/libc-2.11.2.so (0x50ab000) --30287-- Considering /lib/libc-2.11.2.so .. --30287-- .. CRC mismatch (computed 7d8e8f4f wanted 9b015f2c) --30287-- Considering /usr/lib/debug/lib/libc-2.11.2.so .. --30287-- .. CRC is valid --30287-- REDIR: 0x5128600 (__GI_strrchr) redirected to 0x4c25280 (__GI_strrchr) --30287-- REDIR: 0x51218c0 (malloc) redirected to 0x4c24466 (malloc) --30287-- REDIR: 0x5128d00 (memchr) redirected to 0x4c25ed0 (memchr) --30287-- REDIR: 0x512a750 (memcpy) redirected to 0x4c25f00 (memcpy) --30287-- REDIR: 0x5126b10 (strlen) redirected to 0x4a205ac (_vgnU_ifunc_wrapper) ==30287== WARNING: new redirection conflicts with existing -- ignoring it --30287-- new: 0x05126b40 (__GI_strlen ) R-> 0x04c257f0 strlen --30287-- REDIR: 0x5126b40 (__GI_strlen) redirected to 0x4c25810 (__GI_strlen) --30287-- REDIR: 0x512baf0 (__GI___rawmemchr) redirected to 0x4c26ba0 (__GI___rawmemchr) --30287-- REDIR: 0x51217e0 (free) redirected to 0x4c24076 (free) Following are the keys and their corresponding value present --30287-- REDIR: 0x512bb40 (strchrnul) redirected to 0x4c26b50 (strchrnul) A: You can view / modify the suppressed errors in /usr/lib/valgrind/default.supp. A: The suppressed errors are just errors that are system specific, known problems with your libraries. So they are not the right suspects for portability problems to another system. A: On x86 hosts valgrind outputs such line: For counts of detected and suppressed errors, rerun with: -v So run your prog like this: valgrind -v ./myprog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the appropriate event listener for a JTextPane in this scenario? I have a JTextPane that displays HTML text. HTML text has hyperlinks with tags ... I want to invoke a java function when the user clicks on a link within the html text displayed on the JTextPane. How can I achieve this? If there is a need to implement an event listener? If so what is the appropriate event listener that is to be handled? A: The listener type you are looking for is a HyperlinkListener, some code snippet: final JTextPane pane = new JTextPane(); pane.setEditable(false); pane.setContentType("text/html"); pane.setPage("http://swingx.java.net"); ToolTipManager.sharedInstance().registerComponent(pane); HyperlinkListener l = new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (HyperlinkEvent.EventType.ACTIVATED == e.getEventType()) { try { pane.setPage(e.getURL()); } catch (IOException e1) { e1.printStackTrace(); } } } }; pane.addHyperlinkListener(l);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What path is a mountable engine mounted on I need to know, from inside of a layout of a mountable engine, what path it's currently being mounted on. What would be the way to do it? E.g. my routes.rb contains the following line: mount BackendCore::Engine => "/backend" From inside of the BackendCore, I need the access to the value of "/backend". A: UPDATE: this probably applies to Rails 3 only! I found the solution: Rails.application.routes.named_routes[:backend_core].path #=> "/backend" A: Evaluating the routes to get the mount path can give unexpected results when engines are mounted inside other engines. When you take a look at https://github.com/rails/rails/pull/5008 you can read the comment by Jose Valim: Also, an engine can be mounted inside another engine, so it is unlikely that this will give you the proper result. The best option is probably to have a configuration option where the developer will set the path. For consistent results, I'm now using an accessor on the engine. For example: # APP/initializers/backend_core_engine.rb BackendCore::Engine.mount_path = "/backend" # APP/config/routes.rb mount BackendCore::Engine => BackendCore::Engine.mount_path # ENGINE/backend_core/lib/engine.rb module BackendCore class Engine < ::Rails::Engine cattr_accessor :mount_path end end A: If the engine is mouted :as => a different name, querying named_routes will not be sufficient. This monkey patch will do: class Rails::Engine def self.mounted_path route = Rails.application.routes.routes.detect do |route| route.app == self end route && route.path end end Now call mounted_path on the engine: BackendCore::Engine.mounted_path => "/backend" Note: be careful, in production mode, the classes in your engine are evaluated before the routes of the main app are loaded. Calling this method in class macros might not work! A: You could simply use the following code to tell what path engine is mount to inside an engine controller/view: env["SCRIPT_NAME"] # => "/backend"
{ "language": "en", "url": "https://stackoverflow.com/questions/7579625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Fastest way to render UIButtons using layers and Grand Central Dispatch? I have a grid of 30 UIButtons and potentially even more, subclassed to be rendered using layers: a base CALayer, a CAShapeLayer, a CAGradientLayer and a CATextLayer. I am trying to minimize the overall time required to render/display the buttons when the corresponding xib file is loaded. If I simply setup each button in turn in viewDidLoad, the time required for the view to appear is about 5-6 seconds, which is clearly too much. In order to speed-up the buttons setup, I am using Grand Central Dispatch as follows. In viewDidLoad, I setup each button layers using dispatch_async on the global queue (adding to the base layer the shape and the gradient layers), so that the buttons can be rendered in a different thread. A the end of the block, the CATextLayer is added to the gradient layer. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ CGRect base_bounds = CGRectMake(0, 0, self.layer.bounds.size.width, self.layer.bounds.size.height - self.layer.bounds.size.height * 0.10f); CGPoint move_point = CGPointMake(0.0f, base_bounds.size.height * 0.10f); self.layer.masksToBounds = NO; baseLayer = [CALayer layer]; baseLayer.cornerRadius = 10.0; baseLayer.shadowOffset = CGSizeMake(0.0f, 2.0f); baseLayer.shadowOpacity = 1.5f; baseLayer.shadowColor = [UIColor blackColor].CGColor; baseLayer.shadowRadius = 2.5f; baseLayer.anchorPoint = CGPointMake(0.5f, 0.5f); baseLayer.position = move_point; CAShapeLayer *shape = [CALayer layer]; shape.bounds = base_bounds; shape.cornerRadius = 10.0; shape.anchorPoint = CGPointMake(0.0f, 0.0f); shape.position = move_point; shape.backgroundColor = [UIColor darkGrayColor].CGColor; gradient = [CAGradientLayer layer]; gradient.anchorPoint = CGPointMake(0.0f, 0.0f); gradient.position = CGPointMake(0.0f, 0.0f); gradient.bounds = base_bounds; gradient.cornerRadius = 10.0; gradient.borderColor = [UIColor colorWithRed:0.72f green:0.72f blue:0.72f alpha:1.0].CGColor; gradient.borderWidth = 0.73; gradient.colors = [NSArray arrayWithObjects: (id)[UIColor whiteColor].CGColor, (id)[UIColor whiteColor].CGColor, nil]; [baseLayer addSublayer:shape]; [baseLayer addSublayer:gradient]; [self.layer addSublayer:baseLayer]; [textLayer setBounds:gradient.bounds]; [textLayer setPosition:CGPointMake(CGRectGetMidX(textLayer.bounds), CGRectGetMaxY(textLayer.bounds) - 6)]; [textLayer setString:self.titleLabel.text]; [textLayer setForegroundColor:[UIColor blackColor].CGColor]; [gradient addSublayer:textLayer]; }); This approach reduce the overall time to about 2-3 seconds. I am wondering if anyone can suggest a faster way to render the buttons. Please note that I am not interested to any solution which discards the use of layers. Thank you in advance. A: Perhaps I'm missing the point but wouldn't you be better off overriding the UIButton drawRect: method and doing your drawing in CoreGraphics (CG) things would be drawn A LOT faster than seconds, you can easily do gradients, text, images with the CG API. If I understand correctly you have 4 layers per button and 30+ buttons in the same view (120+ layers)? If so, I don't think you are meant to draw so many layers (rendering/blending all of them individually would explain the huge render time). Another possibility would be to have 4 big layers, for all of the buttons. A: Here's my idea, Separate your CALayers from UIButton - UIKit won't allow anything on the background thread. When you have an opportunity in a screen preceding the button grid, use [buttonGridViewController performSelectorInBackground:renderCALayers] to render your CALayers in the background. When you load your button grid in viewDidLoad, overlay UIButtons with type UIButtonTypeCustom, and backgroundColor = [UIColor clearColor] over the top of your 'button' CALayers (make sure to call bringSubviewToFront on the UIButtons so they get the touch events). If you don't know how many buttons you are rendering, you might want to pre-render the maximum number you might display. If you have any questions please comment. EDIT: A few related items, What to replace a UIButton to improve frame rate? UI design - Best way to deal with many UIButtons How to get touch event on a CALayer? I believe the only way you'll get quicker load from this point is to either replace or remove UIButtons altogether and intercept touch events with another approach. That way all rendering can be done in a background thread before the view is presented. A: Have you considered using NSOperation to generate your button's layers? In your code, you'd instantiate an operation queue and then iterate through each button, firing an operation (passing the respective parameters required to generate that button's layer) into the queue as each button is initiated. Within your NSOperation, generate your layer using CoreGraphics, then pass the layer back to the button that initiated the operation (in this case, the destination button) via your completion handler (be sure to call that on the main thread). This should give you pretty good performance as your buttons layer's will be rendered off the main thread using CoreGraphics, then passed back to UIKit for presentation only after the layer has been rendered. NSOperation sits atop GCD, has a marginal overhead but provides benefits in your case, such as the ability to set dependent prerequisites and prioritization. Also, I'm pretty sure you shouldn't call UIColor in the GCD block you shared. Hope this is helpful!
{ "language": "en", "url": "https://stackoverflow.com/questions/7579630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Showing that a recurrence relation is O(n log n) T (n) = T (xn) + T ((1 − x)n) + n = O(n log n) where x is a constant in the range 0 < x < 1. Is the asymptotic complexity the same when x = 0.5, 0.1 and 0.001? What happens to the constant hidden in the O() notation. Use Substitution Method. I'm trying to use the example on ~page 15 but I find it weird that in that example the logs change from default base to base 2. I also do not really understand why it needed to be simplified so much just so as to remove cnlog2n from the left side, could that not be done in the first step and the left side would just have "stuff-cnlog2n<=0" then evaulated for any c and n like so? From what I tried it could not prove that T(n)=O(n) A: Well, if you break this up into a tree using Master's theorem, then this will have a constant "amount" to calculate each time. You know this because x + 1 - x = 1. Thus, the time depends on the level of the tree, which is logarithmic since the pieces are reducing each time by some constant amount. Since you do O(n) calcs each level, your overall complexity is O( n log n ). I expect this will be a little more complicated to "prove". Remember that it doesn't matter what base your logs are in, they're all just some constant factor. Refer to logarithmic relations for this. PS: Looks like homework. Think harder yourself! A: This seems to me exactly the recurrence equation for the average case in Quicksort. You should look at CLRS explanation of "Balanced Partitioning". A: but I find it weird that in that example the logs change from default base to base 2 That is indeed weird. Simple fact is, that it's easier to prove with base 2, than with base unknown x. For example, log(2n) = 1+log(n) in base 2, that is a bit easier. You don't have to use base 2, you can pick any base you want, or use base x. To be absolutely correct the Induction Hypothesis must have the base in it: T(K) <= c K log_2(K). You can't change the IH later on, so what is happening now is not correct in a strict sense. You're free to pick any IH you like, so, just pick one that makes the prove easier: in this case logs with base 2. the left side would just have "stuff-cnlog2n<=0" then evaulated for any c and n What do you mean with 'evaluated for any c and n'? stuff-cnlog2n<=0 is correct, but how do you prove that there is a c so that it holds for all n? Okay, c=2 is a good guess. To prove it like that in WolframAlpha, you need to do stuff <= 0 where c=2, n=1 OK!, stuff <=0 where c=2, n=2OK!, stuff <= 0 where c=2, n=3OK!, ..., etc taking n all the way to infinity. Hmm, it will take you an infinite amount of time to check all of them... The only practical way (I can think of right now) for solving this is to simplify stuff-cnlog2n<=0. Or maybe you prefer this argument: you don't have WolframAlpha at your exam, so you must simplify.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Objective C - CLLocationManager find out when "Allow" or "Don't allow" is clicked When doing CLLocationManager, is there a delegate method that gets called when a user clicked the "Allow" or "Don't allow" prompt that request to use Location? I tried this but this doesn't get called after a user "Allow" or "Don't allow". - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status; Also, is there a variable that will tell me what the user selected? I tried the below, but that always returns true. locationManager.locationServicesEnabled Thank you, Tee A: There is a delegate method for that - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized) { // user allowed } } A: [CLLocationManager locationServicesEnabled] only tells your if the location service are enabled on the device. [CLLocationManager authorizationStatus] returns the actual status you're looking for. A: You'll have to implement didFailWithError: method: - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { if ([error domain] == kCLErrorDomain) { // We handle CoreLocation-related errors here switch ([error code]) { // "Don't Allow" on two successive app launches is the same as saying "never allow". The user // can reset this for all apps by going to Settings > General > Reset > Reset Location Warnings. case kCLErrorDenied: case kCLErrorLocationUnknown: default: break; } } else { // We handle all non-CoreLocation errors here } } EDIT: Looking at CLLocationManager's reference I've found this: + (CLAuthorizationStatus)authorizationStatus Return Value A value indicating whether the application is authorized to use location services. Discussion The authorization status of a given application is managed by the system and determined by several factors. Applications must be explicitly authorized to use location services by the user and location services must themselves currently be enabled for the system. This authorization takes place automatically when your application first attempts to use location services. A: locationManager.locationServicesEnabled indicates whether location services is available, but not necessarily mean they are allowed for your app. Use CLLocationManager.authorizationStatus() if you need to find out the status at a point in time, or implement - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status; Take note since iOS 8, the authorization request does not takes place automatically when your application first attempts to use location services. You need to call requestWhenInUseAuthorization() explicitly before you call startUpdatingLocation() on your CLLocationManager instance. And make sure you have the NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription key in Info.plist, depending on the type of authorization you are after. If these are missing, there are no errors, no logs, no hints, no nothing that will point you in the right direction :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Importing issue history from other issue tracker DB into Jira I am importing issues from a non-legacy issue tracker systems DB into Jira. I am able to import all the issues from the DB, properly with the help of customized 'jira-importer-plugin.jar'.Now I want to import the issue history of the non-legacy issue tracker into Jira. Are there any workarounds for pushing the issue change history from other issue trackers into Jira. Can anyone please tell me in detail how do I import history into Jira from the DB? A: You would need to customize the JIRA importer that you were using to also use the JIRA ChangeLogUtils and related classes to add the data to the change* tables in the JIRA database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make updatable GridView in ItemTemplate I want to show Employee details in GridView. My client wants that he should be able to update the record without clicking on Edit button to update. Hence I kept everything in the ItemTemplate field of the GridView. My Database tables are: Emp(EmpNo, EName, Sal, DeptNo) Dept(DeptNo, DeptName, Location) Hence, I have written one sp to get data: EmpNo, EName, Sal, DeptName Here, I want to show DeptName field in DropDownList. Here only I am facing the problem. DropDownList is not filling with proper DeptName value, but the first field. My code-behind is like below: public partial class GvwEmployee : System.Web.UI.Page { SqlConnection objConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["STERIAConnectionString"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { GridView1.DataSource = EmployeeList; GridView1.DataBind(); } } private List<Employee> EmployeeList { get{ List<Employee> employeeList = new List<Employee>(); SqlCommand objCmd = new SqlCommand("usp_GetEmpDetails", objConn); objCmd.CommandType = CommandType.StoredProcedure; objConn.Open(); SqlDataReader objDR = objCmd.ExecuteReader(); while (objDR.Read()) { Employee employee = new Employee(); employee.EmpNo = Convert.ToInt32(objDR["EmpNo"]); employee.EName = Convert.ToString(objDR["EName"]); employee.Salary = Convert.ToDouble(objDR["Salary"]); employee.DeptNo = Convert.ToInt32(objDR["DeptNo"]); employee.DeptName = Convert.ToString(objDR["DeptName"]); employeeList.Add(employee); } objDR.Close(); objConn.Close(); return employeeList; } } private List<Department> DeptList { get { List<Department> deptList = new List<Department>(); SqlCommand objCmd = new SqlCommand("usp_GetDeptDetails", objConn); objCmd.CommandType = CommandType.StoredProcedure; objConn.Open(); SqlDataReader objDR = objCmd.ExecuteReader(); while (objDR.Read()) { Department dept = new Department(); dept.DeptNo = Convert.ToInt32(objDR["DEPTNO"]); dept.DName = Convert.ToString(objDR["DNAME"]); dept.Location = Convert.ToString(objDR["Location"]); deptList.Add(dept); } objDR.Close(); objConn.Close(); return deptList; } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DropDownList ddlDeptName = e.Row.FindControl("ddlDeptName") as DropDownList; if (ddlDeptName != null) { ddlDeptName.DataSource = DeptList; ddlDeptName.DataBind(); ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString(); } } if (e.Row.RowType == DataControlRowType.Footer) { } } } Can anyone please tell where is the problem, why DeptName DropDownList is not filling with its proper values? A: Try this way protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var index = Convert.ToInt32(e.RowIndex.ToString()); GridViewRow row = GridView1.Rows[index]; var ddlDeptName = row.FindControl("ddlDeptName") as ddlDeptName; if (ddlDeptName != null) { ddlDeptName.DataSource = DeptList; ddlDeptName.DataTextField = "DName"; ddlDeptName.DataValueField = "DeptNo"; ddlDeptName.DataBind(); var item = new ListItem("Select Department", ""); ddlDeptName.Items.Insert(0, item); } } } A: I got the solution like below: In the GridView1_RowDataBound event method, I have written the following line of code to map DropDownList with the Data got from Backend. //ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString(); Now, I have replaced the above line with the following line of code, and hence the problem was solved: ddlDeptName.SelectedValue = ((Employee)e.Row.DataItem).DeptNo.ToString(); and this has solved my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When i do a debug, the pictures went out of place, anyone know why? I'm using WPF xaml. When i do a debug, the pictures ran out of place from what the design is shown. Any one know why? Beside codes what do i have to add in? Sry first time posting in here. What else must i add on? Btw i'm using VS2010. <Grid> <Image Source="C:TV\TV_Page_02.jpg" UseLayoutRounding="True"></Image> <Image Source="C:TV\2.jpg" UseLayoutRounding="True" Margin="19,74,115,72"></Image> <Image Source="C:TV\1.jpg" UseLayoutRounding="True" Margin="123,53,47,72"></Image> </Grid>` A: Allright, here's the issue: "Layout rounding should be used in UI scenarios where the exact location of objects can be sacrificed for overall appearance of the application. Since rounding of layout parameters occurs when using this feature, precise element placement is lost. A few of the effects layout rounding can have on exact layout are… ·width and or height of elements may grow or shrink by at most1 pixel · placement of an object can move by at most 1 pixel · centered elements can be vertically or horizontally off center by at most1 pixel If your app has an unexpectedly blurry image or icon, fuzzy lines or borders that should be crisp, or grid banding try using layout rounding." - Quoted from "WPF Text Blog". Here's the link to read more about this property: http://blogs.msdn.com/b/text/archive/2009/08/27/layout-rounding.aspx Now I guess we now what is the problem (UseLayoutRounding=true). Just remove this property
{ "language": "en", "url": "https://stackoverflow.com/questions/7579643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Looping in a String to find Unicode characters is taking too much time I am creating a custom field where I want to replace some unicode caracters by pictures. Its like doing emoticons for blackberry device. Well I have a problem looping the caracters in the edit field and replacing the unicode caracters by images. When the text becomes too long, the loop takes too much time. My code is as follows: String aabb = ""; char[] chara = this.getText().toCharArray(); for (int i = loc; i < chara.length; i ++) { Character cc = new Character(chara[i]); aabb += cc.toString(); if (unicodeCaracter) { //Get the location //draw the image in the appropriate X and Y } } Well this works fine, and the images are getting in the right place. But the problem is when the text becomes large, the looping is taking too much time, and the input of the text on the device becomes non friendly. How to find the unicode caracters in a text without having to loop each time for them? Is their another way than this that I missed? I need help with this issue. Thanks in advance A: Well you're creating a new Character and a new String in each iteration of the loop, and converting the string to a character array to start with. You're also using string concatenation in a loop rather than using a StringBuffer. All of these will be hurting performance. It's not obvious what you mean by "Unicode characters" here - all characters in Java are Unicode characters. I suspect you really want something like: String text = this.getText(); StringBuffer buffer = new StringBuffer(text.length()); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); buffer.append(c); if (c > 127) { // Or whatever // Take some action } } I'm assuming the "take some action" will be changing the buffer in some respect, otherwise the buffer is pointless of course... but fundamentally that's likely to be the sort of change you want. The string concatenation in a loop is a particularly bad idea - see my article on it for more details. A: What takes time is the string concatenation. Strings are immutable in Java. Each time you do aabb += cc.toString(); you create a new String object containing all the chars of the previous one, which must be garbage collected, plus the new ones. Use a StringBuilder to build your string: StringBuilder builder = new StringBuilder(this.getText().length() + 100); // size estimation char[] chara = this.getText().toCharArray(); for (int i = loc; i < chara.length; i++) { builder.append(chara[i]); if (unicodeCaracter) { //Get the location //draw the image in the appropriate X and Y } } String aabb = builder.toString(); A: Well, besides speeding up your loop, you could also try and minimize the work load. If the user is appending text you could store the last position you scanned previously time and start from there.. On inserts/deletes you'd need to get the caret position and scan the deleted/inserted part and maybe surrounding characters (if you have character groups instead of single characters that get replaced). However, fixing loop performance is likely to give you a better improvement in your case, as I doubt you'll have that long strings to make that algorithmic change worthwhile. A: The most important performance enhancements have already been stated but looping backwards will also help in BlackBerry apps. Programming Tips: General Coding Tips
{ "language": "en", "url": "https://stackoverflow.com/questions/7579644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Consolitate data from multible sheets ,re-arrange the data as per the column name i want a macro to consolidate the data form multiple sheets to one sheet.. here i given the example .. Sheet 1 a1:Name b1:Age a2:sathish b2:22 a3:sarathi b3:24 . sheet 2 a1:Age b1:Name c1:Dept a2:60 b2:saran c2:Comp sce a3:31 b3:rajan c3:B.com the result should be like this consolidate sheet a1:Name b1:Age c1:Dept a2:sathish b2:22 a3:sarathi b3:24 a4:saran b4:60 c4:Comp sce a5:rajan b5:31 c5:B.com Here is the code which i used for consolidate data- Sub consolidate() Dim sh As Worksheet Dim DestSh As Worksheet Dim Last As Long Dim shLast As Long Dim CopyRng As Range Dim StartRow As Long With Application .ScreenUpdating = False .EnableEvents = False End With Application.DisplayAlerts = False On Error Resume Next ActiveWorkbook.Worksheets("RDBMergeSheet").Delete On Error GoTo 0 Application.DisplayAlerts = True Set DestSh = ActiveWorkbook.Worksheets.Add DestSh.Name = "RDBMergeSheet" StartRow = 1 For Each sh In ActiveWorkbook.Worksheets If sh.Name <> DestSh.Name Then Last = LastRow(DestSh) shLast = LastRow(sh) If shLast > 0 And shLast >= StartRow Then Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast)) If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then MsgBox "There are not enough rows in the " & _ "summary worksheet to place the data." GoTo ExitTheSub End If CopyRng.Copy With DestSh.Cells(Last + 1, "A") .PasteSpecial xlPasteValues .PasteSpecial xlPasteFormats Application.CutCopyMode = False End With End If End If Next ExitTheSub: Application.Goto DestSh.Cells(1) DestSh.Columns.AutoFit With Application .ScreenUpdating = True .EnableEvents = True End With End Sub Function LastRow(sh As Worksheet) On Error Resume Next LastRow = sh.Cells.Find(What:="*", _ After:=sh.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Row On Error GoTo 0 End Function Function LastCol(sh As Worksheet) On Error Resume Next LastCol = sh.Cells.Find(What:="*", _ After:=sh.Range("A1"), _ Lookat:=xlPart, _ LookIn:=xlFormulas, _ SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _ MatchCase:=False).Column On Error GoTo 0 End Function I can able consolidate the data but can't re-arrange as per the column title.. Please help me in this ..THanks in advance A: First I identify some mistakes and bad practices in your code then I consider how to redesign your macro to achieve your objectives. Issue 1 The primary purpose of On Error is to allow you to terminate tidily if an unexpected error occurs. You should not use it to avoid errors you expect and you should not ignore errors. Consider the functions LastRow and LastCol. In both cases, if the Find fails, you ignore the error and carry on. But that means these functions return an incorrect value, so you get another error in the calling routine. If the Find fails you should investigate not ignore. This is true of any other error. Issue 2 Find returns Nothing if the sheet is empty. You call functions LastRow and LastCol for worksheet "RDBMergeSheet" when it is empty. The code should be: Set Rng = sh.Cells.Find( ...) If Rng Is Nothing Then ' Sheet sh is empty LastRow = 0 Else LastRow = Rng.Row End If Here I have set LastRow to 0 if the worksheet is empty. This ceases to be a side effect of an error but a documented feature of the function: "Return value = 0 means the worksheet is empty." The calling routine must check for this value and skip any empty worksheets. There are other approaches but the key point is: provide code to handle expected or possible errors in a tidy manner. For function LastCol you need LastCol = Rng.Column. Issue 3 The minimum syntax for a function statement is: Function Name( ... parameters ...) As ReturnType The two function statements should end: As Long. Issue 4 Consider: "ActiveWorkbook.Worksheets("RDBMergeSheet")" If you are working on multiple workbooks, ActiveWorkbook is not enough. If you are only working on one workbook, ActiveWorkbook is unnecessary. Please do not work with multiple workbooks until your understanding of Excel VBA is better. Issue 5 You delete worksheet "RDBMergeSheet" and then recreate it which hurts my soul. More importantly, you have lost the column headings. I will discuss this matter further under Redesign. Replace: Application.DisplayAlerts = False On Error Resume Next ActiveWorkbook.Worksheets("RDBMergeSheet").Delete On Error GoTo 0 Application.DisplayAlerts = True Set DestSh = ActiveWorkbook.Worksheets.Add DestSh.Name = "RDBMergeSheet" with: Set DestSh = Worksheets("RDBMergeSheet") With DestSh .Range(.Cells(2, 1), .Cells(Rows.Count, Columns.Count)).EntireRow.Delete End With You use Rows.Count, With and Cells in your code so I will not explain them. .Range(.Cells(RowTop, ColLeft), .Cells(RowBottom, ColRight)) is an easy method of specifying a range with the top left and bottom right cells. I have used .EntireRow so I do not need the column numbers. The following gives the same effect: .Rows("2:" & Rows.Count).EntireRow.Delete As far as I know ClearContents (which some people favour) has the same effect as Delete. It certainly takes the same number of micro-seconds. For the usages above, both remove any values or formatting from the second row to the last row of the worksheet. The above change means that row 1 is unchanged and the column widths are not lost. I do not need AutoFit which you have used. Issue 6 Please be systematic in the naming of your variables. You use StartRow as the first row and shLast as the last row of the source worksheet and Last as the last row of the destination worksheet. Will a colleague who takes over maintenance of your macro find this easy to understand? Will you remember it in six months when this macro needs some maintenance? Develop a naming system that works for you. Better still, get together with colleagues and agree a single system so all your employer's macros look the same. Document this system for the benefit of future staff. I would name these variables: RowNumDestLast, RowNumSrcStart and RowNumSrcLast. That is: <purpose of variable> <worksheet> <purpose within worksheet>. This system works for me but your system could be completely different. The key feature of a good system is that you can look at your code in a year and immediately know what each statement is doing. Issue 7 If shLast > 0 And shLast >= StartRow Then You set StartRow to 1 and never change it so if shLast >= StartRow then shLast > 0. The following is enough: If shLast >= StartRow Then Issue 8 If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then MsgBox "There are not enough rows in the " & _ "summary worksheet to place the data." GoTo ExitTheSub End If It is good that you are checking for conditions that will result in fatal errors but is this the most likely error? Even if you are using Excel 2003, you have room for 65,535 people and a heading line. You will break the size limit on a workbook before you exceed the maximum number of rows. Issue 9 Set CopyRng = sh.Range(sh.Rows(StartRow), sh.Rows(shLast)) This includes the heading row in the range to be copied. Since I will suggest a totally different method later, I will not suggest a correction. Issue 10 With DestSh.Cells(Last + 1, "A") .PasteSpecial xlPasteValues .PasteSpecial xlPasteFormats Why are you pasting the values and formats separately? Redesign With the corrections above, the code sort of works. With your source data, it sets the destination sheet to: Age Name Dept Name Age Sathish 22 Sarathi 24 Age Name Dept 60 Saran Comp sce 31 Rajan B.com This is not what you seek. So the rest of this answer is about design: how do you achieve the appearance you seek? There are many approaches but I offer one and explain why I have picked it without discussing alternatives. Key issues: * *How do you determine which columns to consolidate and in which sequence? *If there is a column in a source worksheet that you are not expecting, what do you do? Is someone collecting information for which there is no central interest or is the column name misspelt? I have decided to use the existing column names within worksheet "RDBMergeSheet" to determine the sequence. To prepare the macro for a new column name, just add that name to "RDBMergeSheet". If I discover a column name in a source sheet that is not in "RDBMergeSheet", I add it on the right. This second decision will highlight the error if a column name is misspelt but will not be a benefit if someone is collecting extra information in a source worksheet. I do not copy formats to worksheet "RDBMergeSheet" since, if the source worksheets are formatted differently, each part of worksheet "RDBMergeSheet" would be different. New statements and explanations Const RowFirstData As Long = 2 Const WShtDestName As String = "RDBMergeSheet" A constant means I use the name in the code and can change the value by changing the Const statement. I assume the first row of every worksheet contains column names and the first data row is 2. I use a constant to make this assumption clear. It would be possible to use this to write code that would handle a different number of heading rows but I have not done so because it would complicate the code for little advantage. ColNumDestLast = .Cells(1, Columns.Count).End(xlToLeft).Column .Cells(1, Columns.Count) identifies the last column of row 1 which I assume is blank. .End(xlToLeft) is the VBA equivalent of the keyboard Ctrl+Left. If .Cells(1, Columns.Count) is blank, .Cells(1, Columns.Count).End(xlToLeft) returns the first cell to the left which is not blank. .Column gives the column number of that cell. That is, this statement sets ColNumDestStart to the column number of the last cell in row 1 with a value. ColHeadDest = .Range(.Cells(1, 1), .Cells(1, ColNumDestLast)).Value This copies the values from row 1 to the variant array ColHeadDest. ColHeadDest will be redimensioned by this statement to (1 to 1, 1 to ColNumDestLast). The first dimension is for the rows, of which there is only one, and the second dimension is for the columns. Replacement consolidate I hope I have added enought comments for the code to make sense. You still need the corrected LastRow and LastCol. I could have replaced LastRow and LastCol but I think I have provided enough new code to be getting on with. Option Explicit Sub consolidate() Dim ColHeadCrnt As String Dim ColHeadDest() As Variant Dim ColNumDestCrnt As Long Dim ColNumDestLast As Long Dim ColNumSrcCrnt As Long Dim ColNumSrcLast As Long Dim Found As Boolean Dim RowNumDestCrnt As Long Dim RowNumDestStart As Long Dim RowNumSrcCrnt As Long Dim RowNumSrcLast As Long Dim WShtDest As Worksheet Dim WShtSrc As Worksheet Dim WShtSrcData() As Variant Const RowNumFirstData As Long = 2 Const WShtDestName As String = "RDBMergeSheet" 'With Application ' .ScreenUpdating = False ' Don't use these ' .EnableEvents = False ' during development 'End With Set WShtDest = Worksheets(WShtDestName) With WShtDest ' Clear existing data and load column headings to ColHeadDest .Rows("2:" & Rows.Count).EntireRow.Delete ColNumDestLast = .Cells(1, Columns.Count).End(xlToLeft).Column ColHeadDest = .Range(.Cells(1, 1), _ .Cells(1, ColNumDestLast)).Value End With ' Used during development to check array loaded correctly 'For ColNumDestCrnt = 1 To ColNumDestLast ' Debug.Print ColHeadDest(1, ColNumDestCrnt) 'Next RowNumDestStart = RowNumFirstData ' Start for first source worksheet For Each WShtSrc In Worksheets ColNumSrcLast = LastCol(WShtSrc) RowNumSrcLast = LastRow(WShtSrc) If WShtSrc.Name <> WShtDestName And _ RowNumSrcLast <> 0 Then ' Source sheet is not destination sheet and it is not empty. With WShtSrc ' Load entire worksheet to array WShtSrcData = .Range(.Cells(1, 1), _ .Cells(RowNumSrcLast, ColNumSrcLast)).Value End With With WShtDest For ColNumSrcCrnt = 1 To ColNumSrcLast ' For each column in source worksheet Found = False ColHeadCrnt = WShtSrcData(1, ColNumSrcCrnt) ' Find matching column in destination worksheet For ColNumDestCrnt = 1 To ColNumDestLast If ColHeadCrnt = ColHeadDest(1, ColNumDestCrnt) Then Found = True Exit For End If Next ColNumDestCrnt If Not Found Then ' Current source column's name is not present in the ' destination sheet Add new column name to array and ' destination worksheet ColNumDestLast = ColNumDestLast + 1 ReDim Preserve ColHeadDest(1 To 1, 1 To ColNumDestLast) ColNumDestCrnt = ColNumDestLast With .Cells(1, ColNumDestCrnt) .Value = ColHeadCrnt .Font.Color = RGB(255, 0, 0) End With ColHeadDest(1, ColNumDestCrnt) = ColHeadCrnt End If ' I could extract data from WShtSrcData to another array ' suitable for downloading to a column of a worksheet but ' it is easier to move the data directly to the worksheet. ' Also, athought downloading via an array is marginally ' faster than direct access, loading the array will reduce, ' and perhaps eliminate, the time benefit of using an array. RowNumDestCrnt = RowNumDestStart For RowNumSrcCrnt = RowNumFirstData To RowNumSrcLast ' Copy value from array of source data to destination sheet .Cells(RowNumDestCrnt, ColNumDestCrnt) = _ WShtSrcData(RowNumSrcCrnt, ColNumSrcCrnt) RowNumDestCrnt = RowNumDestCrnt + 1 Next Next ColNumSrcCrnt End With ' WShtDest ' Adjust RowNumDestStart ready for next source worksheet RowNumDestStart = RowNumDestStart + RowNumSrcLast - RowNumFirstData + 1 End If ' Not destination sheet and not empty source sheet Next WShtSrc With WShtDest ' Leave workbook with destination worksheet visible .Activate End With 'With Application ' .ScreenUpdating = True ' .EnableEvents = True 'End With End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7579645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: [TRAC]: Generate (welcome) pages for individual and specific user name? I want TRAC to generate individual pages for specific user name. For example USER1 after successful login will see: * *USER1_logo.jpg *USER1_welcome_text *USER1_link_to_http_ftp_file The same way USER2 will see his/her individual page/pages. Especially I'm interested in putting links exclusive to user name in welcome page or sub pages. Does anyone know a plugin or a way to do this? A: [SOLVED]: Install those TRAC plugins: TracMyPagePlugin and TracUserPagePlugin. Read documentation for them on trac-hacks.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7579646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Developing webpage for mobile, resolution choice I am developing a page that needs to be able to view on a mobile platform. What resolution should be the standard for this? I live in Norway, and there are mostly iPhones and HTC-phones on the market here. Any ideas? A: If you want to accommodate more than just iPhone and HTC resolutions, I would consider incorporating responsive design into your site. Google also recommends it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LIKE query does not work after I change CHARACTER SET of a MySQL Table to UTF-8 I have MySQL database with 30 rows in customer_customer table. Out of which 5 record has adm_name as Mike. mysql> select id from customer_customer where adm_name like '%mike%'; +----+ | id | +----+ | 1 | | 2 | | 3 | | 4 | | 5 | +----+ 5 rows in set (0.00 sec) Now I have changed character set of my table to utf8 mysql> ALTER TABLE customer_customer CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; Query OK, 30 rows affected (0.03 sec) Records: 30 Duplicates: 0 Warnings: 0 Again if I run same like query, then MySQL is not returning me any records. mysql> select id from customer_customer where adm_name like '%mike%'; Empty set (0.00 sec) I am not able to understand this behavior. Is there anyone who has came across this situation? Am I doing anything wrong? A: You changed collation to binary, in this case comparison is done byte by byte rather than character by character. Here it is a good example and explanation for the BINARY operator. mysql> SELECT 'a' = 'A'; -> 1 mysql> SELECT BINARY 'a' = 'A'; -> 0
{ "language": "en", "url": "https://stackoverflow.com/questions/7579657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to generate automatic url which is given permission for 3 times in PHP? I would like to generate a URL which will have a unique code tail at the and only will be used 3 times. After accessing 3 times from the link. the url will expire. How can I do this? Basically I think I need to create a database and map the permission for the url and have acountdown number? is there any better way of doing this? An example of this is in facebook you can just copy and send a link to the people to see your pictures without going online or being your friends. ? A: You've already thought of your own solution! There is no easier way. Lets have a look at what you need: * *An url referring to a specific page (or an image in your case) *A limit of times your url can be visited *A count of the amount of visits All 3 requirements seem to need a database. You can use an alternative database, such as local xml files but that would be way more work than using a mysql database for instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: removing of array elements an issue I have a situation where i add tables on a click of button and each table is stored in array. Now when i remove 2 or 3 tables, wrong index are being removed. addTable: function (obj) { for (var i = 0; i < obj.length; i++) { // Adding of table array.push(obj) // delete code of the table (function (i) { deleteButton.addEventListener('click', function (e) { array.splice(i, 1); }); })(i); } } The problem i am facing is the value of i is always zero. each time i click on the button a the addTable function is called and the counter is always zero and that is passed to the function(i) too. Any ideas on how can keep track of different i or counter so that it deletes the correct index in the array Here is an update this is the sample object i am sending each time. Each time i click on the Add Table button, the same object is being passed. Now i am having difficulty in keeping track of the index of each item. A: if obj.length is undefined i will allways be 0 further more, then i < obj.length return false and the for loop will never execute if obj passed in is this object: var addObjectResponse = [{...}]; then addObjectResponse is an array of 1, hence i will allways be 0 i = 0 obj.length = 1 i < obj.length => 0 < 1 => true once A: Once you've removed one table, all other tables have moved and their indexes that you installed in the delete Buttons will be wrong now. When you remove items from the array, all indexes shift. So, suppose you remove table 3. Then, you press delete for table 4. It's got an index of 4, but since you already removed table 3, it's in spot 3 in the array now (after the previous delete), not spot 4. But, you're code still has i==4 associated with that table and is trying to delete it here, but it's not there any more. What you are doing is just not a good way to do this. If you want to expand further on what you're really trying to do, we can help with much better solutions. Given the limited info we have so far, all I know of to do is to find the item in the array (wherever it might have moved to) and delete it from there. addTable: function (obj) { for (var i = 0; i < obj.length; i++) { // Adding of table array.push(obj) // delete code of the table (function (item) { deleteButton.addEventListener('click', function (e) { // search through the array to find where this item is // and remove it from the array for (var j = 0; j < array.length; j++) { if (array[j] === item) { array.splice(j, 1); // remove it break; } } }); })(obj); } } A: I do not know about deleteButton, but in case that obj is array with only one element (length equals 1): [{....}] and array.push is native Array.prototype.push method then: addTable: function (obj) { // Adding of table var index=array.push(obj); // delete code of the table deleteButton.addEventListener('click', function (e) { array.splice(index, 1); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java : get computed values outside loop I do some calculation inside for loop and when I println values inside the loop, I got the expected values, now, I need also that these values will be available outside loop and not only get the latest value. example : String[][] matrix = { { "1", "2", "3" } }; String[] y= { "TEST" ,"BUG"}; int a = 0; for (int i = 0; i < y; i++) { for (int j = 1; j < 4; j++) { int value = Integer.parseInt(matrix[i][j - 1]); System.out.println(value ); //this is OK it print me 3 values } } System.out.println(value ); //it print me only third value I would like that the value 1,2,3 will be also available outside loop A: Declare the variable value outside of your loop: String[][] matrix = { { "1", "2", "3" } }; String[] y= { "TEST" ,"BUG"}; int a = 0; int value = 0; for (int i = 0; i < y; i++) { for (int j = 1; j < 4; j++) { value = Integer.parseInt(matrix[i][j - 1]); System.out.println(value ); //this is OK it print me 3 values } } System.out.println(value ); But if you need all three values available you should use array or some other containers like ArrayList: String[][] matrix = { { "1", "2", "3" } }; String[] y= { "TEST" ,"BUG"}; int a = 0; Arraylist<Integer> values = new Arraylist<Integer>(); for (int i = 0; i < y; i++) { for (int j = 1; j < 4; j++) { values.add(Integer.parseInt(matrix[i][j - 1])); System.out.println(values); //this is OK it print me 3 values } } System.out.println(values); A: If you want to have access to all three variables. you have to declare a data structure that holds all the values. e.g. String[][] matrix = { { "1", "2", "3" } }; List<Integer> list = new ArrayList(); String[] y= { "TEST" ,"BUG"}; int a = 0; int value; for (int i = 0; i < y; i++) { for (int j = 1; j < 4; j++) { value = Integer.parseInt(matrix[i][j - 1]); list.add(value); System.out.println(value ); //this is OK it print me 3 values } } System.out.println(value ); A: you have to declare your variable (that you want to use outside of the for-loop) on top of your code. Example: for (...) { //only valid in this for loop int i = 1; } //valid also after this for loop int i = 1; for (...) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to redirect the url I am not sure what would be the exact technical term for this but i wanted to access a file which is avail in server(Apache Tomcat). i just wanted to type this in browser e.g. http://localhost:8080/myProjectName/eng : *but this should refer as. http://localhost:8080/myProjectName/english.html * http://localhost:8080/myProjectName/hin : *but this should refer as. http://localhost:8080/myProjectName/hindi.html * my project structure is myProjectName | webContent | |----WEB-INF | |_ _ _ web.xml | |--- english.html |--- hindi.html is there any way to get the possible result by writing something in web.xml. Environment : java servlet html js jQuery tomcat6.0 A: if i am understanding your question, here is the solution : * *What you need to do? file configuration *use <jsp-file> mapping instead of <servlet-class> http://localhost:8080/myProjectName/eng Just define mapping in web.xml <servlet> <servlet-name>config</servlet-name> <jsp-file>/english.html</jsp-file> /* referential page */ </servlet> <servlet-mapping> <servlet-name>config</servlet-name> <url-pattern>/eng</url-pattern> /* url pattern */ </servlet-mapping>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: understanding tcpdump trace with ethernet headers I have two packets in my tcpdump log and I have no idea what "P" and "In" in the second column mean. Could someone explain what they mean? 00:43:44.896482 P 00:00:ac:12:80:01 ethertype IPv4 (0x0800), length 76: 172.18.128.1.ssh > 155.xx.xx.xx.56365: S 1308033114:1308033114(0) ack 1315850475 win 5792 <mss 1460,sackOK,timestamp 12196173 122040733,nop,wscale 8> 00:43:44.896482 In 00:00:ac:12:80:01 ethertype IPv4 (0x0800), length 76: 172.18.128.1.ssh > 155.yy.yy.yy.4242: S 1308033114:1308033114(0) ack 1315850475 win 5792 <mss 1460,sackOK,timestamp 12196173 122040733,nop,wscale 8> Note that the dest IP changes because of this "P" thing. A: Got the following answer from the tcpdump-workers mailing list from Guy Harris. The Linux "any" device uses the DLT_LINUX_SLL/LINKTYPE_LINUX_SLL link-layer header, which includes information you get from a "recvfrom()" call on a PF_PACKET socket, which includes the source address, but not the destination address, of the packet, so the only link-layer address you see is the source address. It also includes some flags that indicate how the packet was received: * *"In" - the packet was unicast to the host; *"B" - the packet was broadcast; *"M" - the packet wasn't broadcast but was multicast; *"P" - the packet was unicast to some other host and this host received it because the network adapter was in promiscuous mode; *"Out" - the packet was sent by the host and "wrapped around" and delivered to the PF_PACKET socket. The way the Linux networking stack determines the difference between "In", "B", "M", and "P" is, I think, by looking at the destination address of the packet and seeing whether it's a broadcast address (ff:ff:ff:ff:ff:ff on networks using IEEE MAC-48 addresses), a multicast address (has the "group" bit set, on networks using IEEE MAC-48 addresses), or the address of the adapter on which it's received. It's a bit surprising that it detected a promiscuously-received packet on the "any" device, as the "any" device itself can't be put into promiscuous mode, but perhaps the particular interface from which that packet was received was in promiscuous mode for some other reason.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JQuery onclick event isn't recognizing in JQuery datatable from second page I have JQuery Datatable and I want to delete row, when delete link is clicked. It's working fine for first 10 rows, i.e. for the first page. When I move to any another from the pagination. It's not working. Here is my code: $("#example tbody td.delete").click(function(event) { var row = $(this).closest("tr").get(0); oTable.fnDeleteRow( row ); }); All last td of a row has class "delete". What should I do to work for all the pages or for all the records? A: If you're using jQuery 1.7 or older, you'll need to use the live event handler instead, as subsequent pages are added dynamically. $('#example tbody td.delete').live('click', function(event) { var row = $(this).closest('tr').get(0); oTable.fnDeleteRow( row ); }); jQuery .live() EDIT: It looks like people are still using this answer, so to update it with the latest best practices, DO NOT use .live(). Live was deprecated in 1.7 and removed in 1.9. Instead, use the .on() handler. This can handle delegated events by binding the event to a parent element, and using the actual element you want to target as the optional selector parameter. To put it to use in the above example, it would look like so: $('#example tbody').on('click', 'td.delete', function(event) { var row = $(this).closest('tr').get(0); oTable.fnDeleteRow( row ); }); A: I stuck same you when try to bind inline event it's work onclick="$('#dataConfirmOK').attr('href',$(this).attr('url'))" A: If live extension is not working then you can add live extension plugin additionaly. http://plugins.jquery.com/files/live-extension.js_4.txt It is preferable if you bind the "Click event" of next page items when they load. Please load the code below in each time the page load. and also define the function "click_function_to_call". <script type="application/javascript"> $("#example tbody td.delete").click(click_function_to_call); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Nice tool for creating slide-show using HTML5, CSS3 Is there any nice tool or plugin available to create slide-show presentation using HTML5 and CSS3? A: I use http://html5slides.pageforest.com for all my presentations ! It's pretty simple and yet powerful. A: reveal-js is cool! Support chrome/firefox/opera/safari. iOS is also supported. A: Only one i know that is designed for presentations: http://slides.html5rocks.com/ http://studio.html5rocks.com/#Deck A: There are plenty of jquery plugins for doing this sort of thing just google 'jquery gallery' or 'jquery slideshow' and you will have plenty of examples
{ "language": "en", "url": "https://stackoverflow.com/questions/7579673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Understainding Rails queries in loops I could use some help understanding Rails queries in loops. Loop 1: ruby-1.9.2-p290 :005 > (1..3).each do |i| ruby-1.9.2-p290 :006 > Unit.find(i) ruby-1.9.2-p290 :007?> end Unit Load (0.2ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 1 LIMIT 1 Unit Load (0.1ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 2 LIMIT 1 Unit Load (0.1ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 3 LIMIT 1 => 1..3 Loop 2: ruby-1.9.2-p290 :008 > (1..3).each do |i| ruby-1.9.2-p290 :009 > Unit.where("id = ?", i) ruby-1.9.2-p290 :010?> end => 1..3 Loop 3: ruby-1.9.2-p290 :011 > (1..3).each do |i| ruby-1.9.2-p290 :012 > Unit.find(i) ruby-1.9.2-p290 :013?> end Unit Load (0.2ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 1 LIMIT 1 Unit Load (0.1ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 2 LIMIT 1 Unit Load (0.1ms) SELECT `units`.* FROM `units` WHERE `units`.`id` = 3 LIMIT 1 => 1..3 Why didn't the second loop run? A: Unit.where("id = ?", i) doesn't actually run a query, it just sets up an ActiveRecord::Relation. So on it's own, it just evaluates to an expression. To actually run the query, you would do this: Unit.where("id = ?", i).first
{ "language": "en", "url": "https://stackoverflow.com/questions/7579678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Website / App sizes What would you consider a micro, small, medium and large site based on unique visitors etc. Assuming all sites are very basic like: Django, blogging, photo uploading, etc. No special apps doing any crazy processing, just normal business website. Im trying to figure out how many Django sites would be comfortable on a Linode 512 or similar. Any ideas? A: * *Micro <= 1k unique visitors/month and <= 5k pageviews *Small = 5k unique visitors/month and = 25k pageviews *Medium = 25k unique visitors/month and = 150k pageviews *Large >= 200k unique visitors/month and >= 1M - 1.5M pageviews It is hard to tell how many users you will fit on your Django site, because we have no idea what IO throughput you are expecting and how the read vs. write ratio looks like. If you are building a standard webapp, where for every write that occurs by a user there will be a 1000 reads, you will be able to fit comfortable one medium site (see above definitions) on the Linode 512MB box under the condition that you cache the dynamically generated HTML (memcache is great) and that you put all truly static content in a CDN (CloudFiles from Rackspace is awesome). Hope this helps. M. Cloudfiles (CDN) from Rackspace and Akamain Rackspace Cloud Servers, Linode 512MB equivalent for 21 bucks a month MemCache is awesome for distributed caching
{ "language": "en", "url": "https://stackoverflow.com/questions/7579682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DataGridViewComboBoxColumn very slow with lots of items I have a DataGrid, with several columns. One of them is DataGridViewComboBoxColumn. I have a lot of items in this column - more than 1000 - and I need all of them. So grouping is not an option - all items must be there, users must be able to select from all. The problem is, DataGridViewComboBoxColumn becomes painfully slow, when number of items is about 1000, and above. This issues is well known to Microsoft, it dates back to Visual Studio 2005: http://connect.microsoft.com/VisualStudio/feedback/details/117024/datagridviewcomboboxcolumn-responds-very-slow-compared-with-the-stand-alone-combobox-control. The problem is still present in Visual Studio 2010. Any ideas how to solve this? Is it possible to fill DataGridViewComboBoxColumn with data partially? I mean (that was functionality fully working in Access), when you click DataGridViewComboBoxColumn, some items are displayed (lets say, 100 items). When you scroll down to the latest item, others are loaded (another 100) and so on. I don't see any other option to make DataGridViewComboBoxColumn working faster? Problem is, how to implement this? Has anyone meet that problem before? Greetings, Frenky A: I assume you are using Windows Forms? If there is the possibility of switching to WPF, or at least hosting the WPF datagrid in a Windows Forms application (using ElementHost). WPF can utilize virtualization and allows more items without lagging (because it does not look at items that aren't rendered, pretty much like you suggested).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to load listview in android with emply list and later the contents will download? I need to load load text in list but first it should load an empty list in that time it should display a progress bar. I fetch all the contents from the json feeder. But am stuck with how to load the empty list when the process is in backgroud. /** * This class loads MainScreen in ListView */ package com.smartmedia.salonaudi; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import com.smartmedia.salonaudi.map.GoogleMapActivityClass; /** * * * */ public class SalonAudiActivity extends ListActivity { Button map; Button left; Button about; final Handler uiThreadCallback = new Handler(); Runnable runInUIThread; // WebView about; ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); ArrayList<HashMap<String, String>> mylistCopy = mylist; ArrayList<String> latitude = new ArrayList<String>(); ArrayList<String> longitude = new ArrayList<String>(); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.listplaceholder); //processDialog = ProgressDialog.show(this, "", getString(R.string.loading), true); // getDetails(); // Map Button Click map = (Button) findViewById(R.id.seeonmap); map.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(SalonAudiActivity.this, GoogleMapActivityClass.class); intent.putExtra("latitude", latitude); intent.putExtra("longitude", longitude); startActivity(intent); } }); // Live Button Click about = (Button) findViewById(R.id.about); about.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri .parse("http://google.com")); startActivity(intent); } }); JSONObject json = JSONfunctions .getJSONfromURL("http://audi.smart-media.no/api/getEvents.php"); try { JSONObject es = json.getJSONObject("events"); JSONArray event = es.getJSONArray("event"); JSONObject[] events = new JSONObject[es.length()]; for (int i = 0; i < event.length(); i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = event.getJSONObject(i); map.put("id", String.valueOf(i)); map.put("Time", "" + e.getString("startTime").split(" ")[0]); map.put("startTime", "" + e.getString("startTime").split(" ")[1] .substring(0, 5) + " @ Olympic Stadium"); map.put("title", "" + e.getString("title")); System.out.println("title" + e.getString("title")); map.put("ingress", "" + e.getString("ingress")); map.put("description", "" + e.getString("description").replaceAll( "\\<[^>]*>", "")); map.put("image", "" + e.getString("image")); map.put("latitude", "" + e.getString("latitude")); map.put("longitude", "" + e.getString("longitude")); System.out.println("latitude" + e.getString("latitude")); mylist.add(map); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main, new String[] { "startTime", "title", "description" }, new int[] { R.id.time, R.id.title, R.id.description }); setListAdapter(adapter); final ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(); intent.setClassName(SalonAudiActivity.this, "com.smartmedia.salonaudi.DetailView"); HashMap<String, String> map = mylistCopy.get(arg2); intent.putExtra("title", map.get("title")); intent.putExtra("image", map.get("image")); intent.putExtra("startTime", map.get("startTime")); intent.putExtra("ingress", map.get("ingress")); intent.putExtra("description", map.get("description")); startActivity(intent); } }); for (int i = 0; i < mylist.size(); i++) { HashMap<String, String> e = mylist.get(0); latitude.add(e.get("latitude")); longitude.add(e.get("longitude")); } } public boolean isConnected() { Context context = getApplicationContext(); ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } } A: You have to use AsyncTask for displaying dialog box while data is loading in the list. Definitely this will solve your problem There is code ... This will help you to do Your work... In doInBackground method load all ur json data into arrays or ArrayList and set into the adpater In PostExecute method , set the adapter to your list.. private class LoadingData extends AsyncTask<String, Void, String> { private ProgressDialog Dialog = new ProgressDialog(getParent()); @Override protected String doInBackground(String... params) { // perform long running operation operation //Here you have to do your network operations.. return null; } @Override protected void onPostExecute(String result) { // execution of result of Long time consuming operation try { if(Dialog.isShowing()) { Dialog.dismiss(); } // do your Display and data setting operation here } catch(Exception e) { } //Here depending upon your validation, display appropriate message. } @Override protected void onPreExecute() { Dialog.setMessage("Loading Data....."); Dialog.show(); // Things to be done before execution of long running operation. For example showing ProgessDialog } @Override protected void onProgressUpdate(Void... values) { // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: apache php - X-SendFile with Byte Range I have Apache 2.2.8 installed on a server, and I'm trying to use X-SendFile to deliver video files. Unfortunately some devices, like iPads, seem to require Byte Range in order to serve the files, but I cannot get Accept-Ranges to work with X-SendFile. Here's the code header("Content-type: application/octet-stream"); header('Content-Disposition: attachment; filename="' . basename($file_name) . '"'); header('Accept-Ranges: bytes'); header("X-Sendfile: $file_name"); I'd like to avoid the overhead and complexity caused by sending the byte chunks from php.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to make Google+ Hangout load in an HTML frame? I'm guessing Google has found a way to stop Google+ from loading in an iFrame, because whereas I can put https://www.google.com/ into a page's frame, I can't do the same with https://plus.google.com/. It just gives a blank page. I'm trying to embed a hangout in my custom page. Can anyone tell me why this isn't working and if there is a way to make it work? All I want to do is add some widgets outside of the Hangout. Here is the header that Google is returning in Firefox: (Status-Line) HTTP/1.1 200 OK Content-Type text/html; charset=UTF-8 X-Frame-Options SAMEORIGIN P3P CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info." Content-Encoding gzip Date Wed, 28 Sep 2011 07:23:04 GMT Expires Wed, 28 Sep 2011 07:23:04 GMT Cache-Control private, max-age=0 X-Content-Type-Options nosniff X-XSS-Protection 1; mode=block Content-Length 674 Server GSE In Chrome, it just says the page is not responding. A: Okay, that was dumb... it was staring me in the face: X-Frame-Options SAMEORIGIN https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header
{ "language": "en", "url": "https://stackoverflow.com/questions/7579704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can i send push alerts using Rails? I want to know if one can send push alerts using rails. If yes, is there any tutorial or plugin for this. A: Check this. https://github.com/samsoffes/apple_push_notification
{ "language": "en", "url": "https://stackoverflow.com/questions/7579705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php password generating function Here is a question i want to solve "Write a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9). When GeneratePassword(5,'abc0123') is called, it should return a random string of 5 characters taken from 'abc0123'. For Example : GeneratePassword(7,'abczxc012394') could return any of the following outputs : 2c00acb 2c23z93 030b2a4 " I have written the following code for it, but the system says that the answer is wrong. Please explain what am i doing wrong. My code : function GeneratePassword($digits,$passwordString){ if($digits > strlen($passwordString)) return ''; else { $randomSelect = ''; for($i=0;$i<$digits;$i++){ $randomChar = $passwordString[rand(0, strlen($passwordString)-1)]; $randomSelect = $randomSelect.$randomChar ; $passwordString = str_replace($randomChar,"",$passwordString); } return $randomSelect; } } A: Firstly, you shouldn't reject $digits being higher than the number of characters to choose from. You could easily receive GeneratePassword(10,'A'), in which case you'd need to return AAAAAAAAAA. Second, you shouldn't remove selected characters from the string. The examples even include duplicate characters (2c00acb for instance). Apart from that, your code seems to work. I would suggest, though, that you calculate strlen($passwordString) up front and save it in a variable, rather than computing it once for every iteration of the loop. A: function GeneratePassword($length,$characters) { $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } echo GeneratePassword(7, 'abczxc012394'); A: Here's the version I would make. Mind you that I've replaced "$digits" with "$length", because, well, that's what it's supposed to indicate. Also, I've replaced "$passwordString" with the more commonly accepted term "$seed". Explanation is inline. function GeneratePassword( $length, $seed ) { $password = ''; /** Begin with an empty string. */ $max = ( $length - 1 ); /** Calculate the number of characters in seed -1, because strings are zero-indexed. */ for( $i = 0; $i < $length; $i ++ ) { /** Loop until the maximum length is reached. */ $password .= $seed[mt_rand( 0, $max )]; /** Select a random character and append it to the password string. */ } return $password; /** return the password */ } A: function GeneratePassword($digits,$passwordString){ $randomSelect = ''; for($i=0;$i<$digits;$i++){ $randomChar = $passwordString[rand(0, strlen($passwordString)-1)]; $randomSelect = $randomSelect.$randomChar ; $passwordString = str_replace($randomChar,"",$passwordString); } return $randomSelect; } you should reuse the chars in $passwordString A: function GeneratePassword($n,$c){ $pw = ''; for ($l = 0; $l < $n; $l++){ $r = rand(0, strlen($c) - 1); $pw .= $c[$r]; } return $pw; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the Event Performed on a Control I am hoping for some help. In my application, I have a Text Box which should display the event occured in any control while clicking it. For exmaple, if I click on a button or a checkbox in the app., the text box should identify the event and display as button1.clicked, checkbox1.checked kind of things. Can anyone help me to get this done. Thanks In Advance.:) A: If you want to do it for all controls dynamically you can navigate through the controls tree and subscribe the same event handler for events like shown below, in case of predefined controls set basically just subscribe all of them for the same even handlers. Predefined controls set checkBox1.CheckedChanged += (s, e) => { /* handles Checked state changes*/ }; button1.Click += (s, e) => { /* handles button click */ }; Dynamic private void InitializeHooks() { foreach(var control in this.Controls) { var button = control as Button; if (button != null) { button.Click += OnClick; continue; } var checkBox = control as CheckBox; if (checkBox != null) { checkBox.CheckedChanged += OnCheckedChanged; } } } // Button click handler private void OnClick(object sender, EventArgs eventArgs) { txtOutput.Text = String.Format( CultureInfo.CurrentCulture, "{Control Type: {0}, Name: {1}, Event: Click", sender.GetType().Name, sender.Id); } // Checkbox Checked state changed handler private void OnCheckedChanged(object sender, EventArgs eventArgs) { txtOutput.Text = String.Format( CultureInfo.CurrentCulture, "{Control Type: {0}, Name: {1}, Event: CheckedChanged", sender.GetType().Name, sender.Id); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing binary file versions My application stores large binary files (100Mb - 1Gb) that change over time on s3. I want to offer the ability to roll back or download previous versions of these files without having to store snapshot copies. What would be the best way to achieve this? A: Since Nexus is able to work with s3 repositories (see ticket NEXUS-1121), I would advise you to record those different versions in an artifact repo like Nexus, and not in a VCS (Version Control System tool like SVN, or even worse, distributed ones like Git or Mercurial). A VCS has features (branching, merging, diff) that large binaries won't take advantage of.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inconsistency of Python plus operator In [26]: l=[] In [27]: s="asdsad" In [28]: l+=s In [29]: l Out[29]: ['a', 's', 'd', 's', 'a', 'd'] However, In [30]: l+s --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/xiaohan/code/proteincrawler/id_crawler.py in <module>() ----> 1 2 3 4 5 TypeError: can only concatenate list (not "str") to list So, the + operators in '+=' and '+' are different. But I think they should be the same, because they are all plus Am I wrong or something happens behind the scene? A: This is explained here. Copied from the link: It's because the += operator is doing the equivalent of calling the extend method, which treats its argument as a generic sequence, and doesn't enforce type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Enumerating groups in a query I'm trying to enumerate the groups inside a certain view. Example, from this view: ID FK1 FK2 FK3 FK4 104091 10160 1 1 29152 106797 10161 2 1 NULL 34682 10162 1 6 28556 61582 10162 1 6 28557 53045 10163 1 1 29154 23918 10164 1 6 28731 34683 10164 1 6 28729 89003 10164 1 4 28728 50547 10164 1 4 28727 50548 10165 1 6 29846 34684 10165 1 5 29847 23919 10165 1 5 29844 I'd like to have something like: ID FK1 FK2 FK3 FK4 C 104091 10160 1 1 29152 1 106797 10161 2 1 NULL 2 34682 10162 1 6 28556 3 61582 10162 1 6 28557 3 53045 10162 1 1 29154 4 23918 10164 1 6 28731 5 34683 10164 1 6 28729 5 89003 10164 1 4 28728 6 50547 10164 1 4 28727 6 50548 10165 1 6 29846 7 34684 10165 1 5 29847 8 23919 10165 1 5 29844 8 As you can see, it looks like a ROW_NUMBER() OVER (PARTITION BY FK1, FK2, FK3 ORDER BY FK1, FK2, FK3) AS C With the only difference that PARTITION BY resets the row_number for each group. Instead, I'd like to have a unique number for each group. More like a GROUP_NUMBER() I hope the question was clear enough :) A: DENSE_RANK() OVER (ORDER BY FK1, FK2, FK3) AS C Should do what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ActivityGroup is Deprecated I am making android application containing three tabs.. On third tab there is login screen.. when i click on login button ...i want to replace the activity with activity containing list view and logout button.... Previously i was using Activity Group to replace the activity..But activity Group is now deprecated.. Now how can i replace the activity under third tab?? I am using these code Intent intent = new Intent(MyApp.this, LoginPage.class); replaceContentVieww("activity4", intent); public void replaceContentVieww(String id, Intent newIntent) { // TODO Auto-generated method stub View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); setContentView(view); } There is link from which i came to know this class has been deprecated. A: you should use Fragment and FragmentManager in the Compatibility Package http://developer.android.com/sdk/compatibility-library.html download it using the ADT, then go to the samples here extras/android/compatibility/v4/samples/ A: Now how can i replace the activity under third tab?? You can define tab contents as existing children of the FrameLayout (via the setContent() that takes a widget ID) or as a dynamically-created View (via the setContent() that takes a TabContentFactory).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: how to alloc records to avoid an update at the same time with another user i'm using select sql (DB2 on IBM i) to read a record from database and show it into a form where an user can modify and update it! now i need that if an user is viewing this record, at the same time another user can only view but not update the same racord! how can i do it? ther is a way to select this record allocating (or blocking) the record to avoid an update at the same time? (also if there is same php instruction to do it) (for example i working with RPG language program where i use CHAIN instruction that alloc record to prevent this problem) thanks! A: In my experience you need to avoid going down this route if you possibly can. Yes it is possible to lock the record, but how long do you intend to keep the lock? What happens if your locking user goes for a long lunch before hitting 'save'? Faced with the problem you have, I would look at doing a read check of the record before updating. If you find it has been changed by another user you can flag this up or work in some logic to change only modified fields. A: Locking the row can be useful if you control all access to the table, for instance a green screen application. If you don't control all access, for instance someone else has a web application that reads rows, or an ODBC application reads rows, they might be frustrated at the inability to get at all the rows. Definitely consider the larger role the table plays in all applications accessing it. That said, the DB2 SQL way to lock the row is FETCH ... FOR UPDATE. A: Yes you can lock the table while you are updating the data. I don't know how can you do it on DB2, but propably you can lock the tables while updating your data, and unlock them after finish. May this link can help you: http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0000972.htm A: What about avoiding locked records reading? Select * from yourtable where field='comparator' SKIP LOCKED DATA Also you can retrieve a specific number of rows Select * from yourtable where field='comparator' SKIP LOCKED DATA FETCH FIRST 1 ROWS ONLY Does it fit you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7579726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FireMonkey Canvas.DrawLine on Windows XP How can I draw a line ? This code does not display anything : var my_point_1, my_point_2: tPointF; Canvas.Stroke.Color := claBlue; Canvas.Stroke.Kind:= tBrushKind.bkSolid; my_point_1.X:= 100; my_point_1.Y:= 100; my_point_2.X:= 120; my_point_2.Y:= 150; Canvas.BeginScene; Canvas.DrawLine(my_point_1, my_point_2, 1.0); Canvas.EndScene; Windows XP Service Pack 3 (tOsVersion.ToString is "Version 5.1, Build 2600, 32-bit Edition", Delphi XE2 update 1 installed) A: You expect this to be easy - as I did. However it is not. These are early days for FireMonkey, and Embarcadero seem overwhelmed with the feedback. When using the canvas directly on the TForm, you must accept that the result is volatile, i.e. it will disappear on the first repaint (resize, other windows overlapping etc.). This works for me on several machines: Create a new FM-HD project, add a button and a handler: procedure TForm1.Button1Click(Sender: TObject); var pt0,pt1 : TPointF; begin pt0.Create(0,0); pt1.Create(100,50); Canvas.BeginScene; Canvas.DrawLine(pt0,pt1,1); Canvas.EndScene; end; Run, click button, and (hopefully): voila! On a TImage Canvas, however, it is slightly more complicated (read:buggy ?) Create a new project, this time two TButtons and a TImage - set (left,top) to something like (150,150) to distinguish its Canvas it from the Canvas of the TForm. Add this code and assign to handlers (double click the form and the buttons): procedure TForm1.FormCreate(Sender: TObject); begin // Without this, you normally get a runtime exception in the Button1 handler Image1.Bitmap := TBitmap.Create(150,150); end; procedure TForm1.Button1Click(Sender: TObject); var pt0,pt1 : TPointF; begin pt0.Create(0,100); pt1.Create(50,0); with Image1.Bitmap do begin Canvas.BeginScene; Canvas.DrawLine(pt0,pt1,1); BitmapChanged; // without this, no output Canvas.EndScene; end; end; procedure TForm1.Button2Click(Sender: TObject); // This demonstrates that if you try to access the Canvas of the TImage object (and NOT its bitmap) // you are sometimes defaulted to the Canvas of the Form (on some configurations you get the line directly on the form). var pt0,pt1 : TPointF; begin pt0.Create(0,100); pt1.Create(50,0); with Image1 do begin Canvas.BeginScene; Canvas.DrawLine(pt0,pt1,1); Canvas.EndScene; end; end; A final remark: once you start playing with the ScanLine property of the Bitmap, make sure that you do it OUTSIDE a BeginScend/EndScene section - and after you're done, make a "dummy" BeginScend/EndScene section to make sure that your changes are not lost :-( I might get back to this sometimes, if necessary ;o) Good luck ! Carsten
{ "language": "en", "url": "https://stackoverflow.com/questions/7579727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to call to a python handler from jquery ajax? How to call to a python handler from jquery ajax? can any one give me an example? A: $.ajax({ url: "/resultshandler", type: 'POST', data: data, success: function(data, status){ //check status //do something with data } }); may this post will help you jquery.ajax post request to get data from app engine server
{ "language": "en", "url": "https://stackoverflow.com/questions/7579729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: need help to parse simple XML to PHP i'm trying to display this XML rss i receive using PHP , and its not working for me. can anyone help displaying this? this is the XML code: <RESPONSE> <EXPR>CAD</EXPR> <EXCH>USD</EXCH> <AMOUNT>1</AMOUNT> <NPRICES>1</NPRICES> <CONVERSION> <DATE>Thu, 10 May 2001 21:00:00 GMT</DATE> <ASK>1.5432</ASK> <BID>1.542</BID> </CONVERSION> <EXPR>CAD</EXPR> <EXCH>CAD</EXCH> <AMOUNT>1</AMOUNT> <NPRICES>1</NPRICES> <CONVERSION> <DATE>Fri, 11 May 2001 14:29:54 GMT</DATE> <ASK>1.0000</ASK> <BID>1.000</BID> </CONVERSION> </RESPONSE> this is the code i wrote, the problem is that the EXPR EXCH... are at the same level, and running a foreach loop on them is a problem: <?php oandaObj = simplexml_load_file("XMLFILENNAME.xml"); $oandaArr = $oandaObj; ?> <ul> <?php foreach ($oandaObj as $key): ?> <li><?php echo $oandaObj->EXPR;?></li> <li><?php echo $oandaObj->EXCH;?></li> <li><?php echo $oandaObj->AMOUNT;?></li> <li><?php echo $oandaObj->NPRICES;?></li> <li><?php echo $oandaObj->CONVERSION->DATE;?></li> <li><?php echo $oandaObj->CONVERSION->BID;?></li> <li><?php echo $oandaObj->CONVERSION->ASK;?></li> <?php endforeach;?> </ul> A: Here is a nice function to do it ... function ReadXml($xmlstr){ $xml = simplexml_load_string($xmlstr); echo $xml->getName()."\n"; foreach($xml->children() as $child){ echo $child->getName().': '.$child."\n"; } } $xmlstr= '<Address><to>James</to><from>Jani</from><heading>Reminder</heading><body>Please check your mail.</body></Address>'; it echos Address to : james from : jani Heading: remainder body: please check your mail. I hope it helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7579732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comboboxes not updating I have two php pages, admin_bkp.php and db_submit.php. The admin_bkp.php gives a user a table that let's the user set permissions to employees and save the permissions to a MySQL table called rights. The employee info is gathered from hs_hr_employee and saved to rights together with an extra 'Permissions' column. It was working at first, you could save the data and when you refresh the page, the admin_bkp.php shows you the default value in the comboboxes as you had previously chosen. However, now it is returning the default value as 'All' which is something I don't want. I want it to show the chosen value from before. The admin_php.bkp saves the values upon clicking the 'Save' button This is the code: admin_bkp.php <?php $connection = mysql_connect('localhost','admin','root'); if( isset($_POST['submit']) ) { if( isset( $_POST['cb_change'] ) && is_array( $_POST['cb_change'] )) { foreach( $_POST['cb_change'] as $emp_number => $permission) { echo "$permission"; $sql = "UPDATE `rights` SET Permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'"; echo __LINE__.": sql: {$sql}\n"; mysql_query( $sql ); } } } ?> <p style="text-align: center;"> <span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p> <p style="text-align: center;"> &nbsp;</p> <head> <style type="text/css"> /* http://icant.co.uk/csstablegallery/index.php?css=71 Data Tables and Cascading Style Sheets Gallery Title: Casablanca Author: RODrigo CASTilho Galv?o Ferreira - RODCAST URL: http://www.rodcast.com.br Update: 04/04/2008 10:51 AM */ body{ background: url('bg.gif'); } table { color: #666; font: 0.8em/1.6em "Trebuchet MS",Verdana,sans-serif; border-collapse: collapse; background: #fff; } table,caption { margin: 0 auto; border-right: 0px solid #CCC; border-left: 0px solid #CCC; } caption,th,td { border-left: 0; padding: 10px; } caption,thead th,tfoot th,tfoot td { background-color: #216dab; color: #FFF; font-weight: bold; text-transform: uppercase } thead th { background-color: #666; color: #fff; text-align: center } tbody th { padding: 20px 10px } tbody tr.odd { background-color: #F7F7F7; color: #666; } tbody a { padding: 1px 2px; color: #fff; text-decoration: none; border-bottom: 1px dotted #E63C1E; background: #7bafd9; } tbody a:active,tbody a:hover,tbody a:focus,tbody a:visited { color: #fff; } tbody tr:hover { background-color: #EEE; color: #333 } tbody tr:hover a { /*background-color: #FFF*/ color:fff; } tbody td+td+td+td a { color: #fff; font-weight: bold; border-bottom: 0; } tbody td+td+td+td a:active,tbody td+td+td+td a:hover,tbody td+td+td+td a:focus,tbody td+td+td+td a:visited { color: #fff } tbody td a[href="http://www.rodcast.com.br/"] { margin: 0 auto; display: block; width: 15px; height: 15px; background: transparent url('data:image/gif;base64,R0lGODlhDwAPAIAAACEpMf///yH5BAAAAAAALAAAAAAPAA8AAAIjjA8Qer0JmYvULUOlxXEjaEndliUeA56c97TqSD5pfJnhNxYAOw%3D%3D') no-repeat; text-indent: -999em; border-bottom: 0; } tbody a:visited:after { font-family: Verdana,sans-serif; content: "\00A0\221A" } </style> </head> <form method="post" action="db_submit.php"> <?php if (!$connection) { die('Could not connect: ' . mysql_error()); } mysql_select_db('users', $connection); #mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee'); $result = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, Permissions FROM rights"); mysql_query("INSERT INTO rights (emp_number, employee_id, emp_firstname, emp_lastname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee ON DUPLICATE KEY UPDATE employee_id = VALUES(employee_id), emp_number = VALUES(emp_number) "); $duplicates = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, count(*) FROM rights GROUP BY emp_number, employee_id, emp_firstname, emp_lastname having count(*) > 1"); $count = mysql_num_rows($duplicates); if ($count > 0) { while ($row = mysql_fetch_assoc($duplicates)) { $field = $row["emp_number"]; $limit = $row["count(*)"] - 1; mysql_query("DELETE FROM rights WHERE emp_number='$field' LIMIT $limit"); } mysql_free_result($duplicates); } echo "<center>"; /* echo " <table > <tr> <th>Employee Number</th> <th>ID</th> <th>Name</th> <th>Surname</th> <th>Permissions</th> <th>Change</th> </tr>"; */ echo " <table > <tr> <th>Employee Number</th> <th>ID</th> <th>Name</th> <th>Surname</th> <th>Permissions</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['emp_number'] . "</td>"; echo "<td>" . $row['employee_id'] . "</td>"; echo "<td>" . $row['emp_firstname'] . "</td>"; echo "<td>" . $row['emp_lastname'] . "</td>"; #echo "<td>" . $row['Permissions'] . "</td>"; echo "<td> <select> <option value='All'>All</option> <option value='Remote Gaming' selected='selected'>Remote Gaming</option> <option value='Landbased Gaming'>Landbased Gaming</option> <option value='General Gaming'>General Gaming</option> </select> </td> "; echo "</tr>" ; echo "<input type='hidden' name='emp_id[]' value='". $row['employee_id'] ."'>"; } $selected = $row['Permissions']; $options = array( "Remote Gaming", "Landbased Gaming", "General Gaming" ); foreach ($options as $option){ if($option == $selected){ echo "<option value='$option' selected='selected'>$option</option>"; }else{ echo "<option value='$option'>$option</option>"; } } #echo "<td>" . $row['Change'] . "</td>"; echo "</table> <p style='text-align: right;'> <input name='Save_Btn' type='Submit' value='Save' /> </p> </center>"; mysql_close($connection); ?> <p style="text-align: center;"> &nbsp;</p> <p style="text-align: center;"> &nbsp;</p> </form> db_submit.php: <html> <body> <p>Data submitted successfully.</p> <?php $connection = mysql_connect('localhost','admin','root'); mysql_select_db('users', $connection); $cbchange = $_POST['cb_change']; $emp_id = $_POST['emp_id']; foreach($cbchange as $a => $b){ echo $cbchange[$a] ." - ". $emp_id[$a]; echo "<br/>"; $query = " UPDATE `rights` SET `rights`.`Permissions`='".$cbchange[$a]."' WHERE `rights`.`employee_id`='".$emp_id[$a]."' "; mysql_query($query); } ?> </body> </html> Here are some images to give you a general idea of the setup. Original Code: <?php $connection = mysql_connect('localhost','admin','root'); if( isset($_POST['submit']) ) { if( isset( $_POST['cb_change'] ) && is_array( $_POST['cb_change'] )) { foreach( $_POST['cb_change'] as $emp_number => $permission) { echo "$permission"; $sql = "UPDATE `rights` SET Permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'"; echo __LINE__.": sql: {$sql}\n"; mysql_query( $sql ); } } } ?> <p style="text-align: center;"> <span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p> <p style="text-align: center;"> &nbsp;</p> <head> <style type="text/css"> /* http://icant.co.uk/csstablegallery/index.php?css=71 Data Tables and Cascading Style Sheets Gallery Title: Casablanca Author: RODrigo CASTilho Galv?o Ferreira - RODCAST URL: http://www.rodcast.com.br Update: 04/04/2008 10:51 AM */ body{ background: url('bg.gif'); } table { color: #666; font: 0.8em/1.6em "Trebuchet MS",Verdana,sans-serif; border-collapse: collapse; background: #fff; } table,caption { margin: 0 auto; border-right: 0px solid #CCC; border-left: 0px solid #CCC; } caption,th,td { border-left: 0; padding: 10px; } caption,thead th,tfoot th,tfoot td { background-color: #216dab; color: #FFF; font-weight: bold; text-transform: uppercase } thead th { background-color: #666; color: #fff; text-align: center } tbody th { padding: 20px 10px } tbody tr.odd { background-color: #F7F7F7; color: #666; } tbody a { padding: 1px 2px; color: #fff; text-decoration: none; border-bottom: 1px dotted #E63C1E; background: #7bafd9; } tbody a:active,tbody a:hover,tbody a:focus,tbody a:visited { color: #fff; } tbody tr:hover { background-color: #EEE; color: #333 } tbody tr:hover a { /*background-color: #FFF*/ color:fff; } tbody td+td+td+td a { color: #fff; font-weight: bold; border-bottom: 0; } tbody td+td+td+td a:active,tbody td+td+td+td a:hover,tbody td+td+td+td a:focus,tbody td+td+td+td a:visited { color: #fff } tbody td a[href="http://www.rodcast.com.br/"] { margin: 0 auto; display: block; width: 15px; height: 15px; background: transparent url('data:image/gif;base64,R0lGODlhDwAPAIAAACEpMf///yH5BAAAAAAALAAAAAAPAA8AAAIjjA8Qer0JmYvULUOlxXEjaEndliUeA56c97TqSD5pfJnhNxYAOw%3D%3D') no-repeat; text-indent: -999em; border-bottom: 0; } tbody a:visited:after { font-family: Verdana,sans-serif; content: "\00A0\221A" } </style> </head> <form method="post" action="db_submit.php"> <?php if (!$connection) { die('Could not connect: ' . mysql_error()); } mysql_select_db('users', $connection); #mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee'); $result = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, Permissions FROM rights"); mysql_query("INSERT INTO rights (emp_number, employee_id, emp_firstname, emp_lastname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee ON DUPLICATE KEY UPDATE employee_id = VALUES(employee_id), emp_number = VALUES(emp_number) "); $duplicates = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, count(*) FROM rights GROUP BY emp_number, employee_id, emp_firstname, emp_lastname having count(*) > 1"); $count = mysql_num_rows($duplicates); if ($count > 0) { while ($row = mysql_fetch_assoc($duplicates)) { $field = $row["emp_number"]; $limit = $row["count(*)"] - 1; mysql_query("DELETE FROM rights WHERE emp_number='$field' LIMIT $limit"); } mysql_free_result($duplicates); } echo "<center>"; /* echo " <table > <tr> <th>Employee Number</th> <th>ID</th> <th>Name</th> <th>Surname</th> <th>Permissions</th> <th>Change</th> </tr>"; */ echo " <table > <tr> <th>Employee Number</th> <th>ID</th> <th>Name</th> <th>Surname</th> <th>Permissions</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['emp_number'] . "</td>"; echo "<td>" . $row['employee_id'] . "</td>"; echo "<td>" . $row['emp_firstname'] . "</td>"; echo "<td>" . $row['emp_lastname'] . "</td>"; #echo "<td>" . $row['Permissions'] . "</td>"; echo "<td> <select name='cb_change[]' SELECTED VALUE=".$row['Permissions']."> <option value='All'>All</option> <option value='Remote Gaming'>Remote Gaming</option> <option value='Landbased Gaming'>Landbased Gaming</option> <option value='General Gaming'>General Gaming</option> </select> </td>"; echo "</tr>" ; echo "<input type='hidden' name='emp_id[]' value='". $row['employee_id'] ."'>"; } #echo "<td>" . $row['Change'] . "</td>"; echo "</table> <p style='text-align: right;'> <input name='Save_Btn' type='Submit' value='Save' /> </p> </center>"; mysql_close($connection); ?> <p style="text-align: center;"> &nbsp;</p> <p style="text-align: center;"> &nbsp;</p> </form> Can you kindly point me in the right direction? A: If the correct values are displaying in the database, then your problem is with displaying the data at the other end. From what I understand, you want to output a list of permissions in an html select box, with the currently stored permission set as 'selected' for that user, correct? If so, your code here: echo "<td> <select name='cb_change[]' SELECTED VALUE=".$row['Permissions']."> <option value='All'>All</option> <option value='Remote Gaming'>Remote Gaming</option> <option value='Landbased Gaming'>Landbased Gaming</option> <option value='General Gaming'>General Gaming</option> </select></td>"; Is wrong. you need to match the <option> value to the currently selected value, then stick attribute on it. eg: $selected = $row['Permissions']; $options = array( "Remote Gaming", "Landbased Gaming", "General Gaming" ); foreach ($options as $option){ if($option == $selected){ echo "<option value='$option' selected='selected'>$option</option>"; }else{ echo "<option value='$option'>$option</option>"; } } That should work. FINAL EDIT The following code marked 'Code' should be placed underneath: echo " <table > <tr> <th>Employee Number</th> <th>ID</th> <th>Name</th> <th>Surname</th> <th>Permissions</th> </tr>"; Code: $options = array( "All", "Remote Gaming", "Landbased Gaming", "General Gaming" ); while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['emp_number'] . "</td>"; echo "<td>" . $row['employee_id'] . "</td>"; echo "<td>" . $row['emp_firstname'] . "</td>"; echo "<td>" . $row['emp_lastname'] . "</td>"; #echo "<td>" . $row['Permissions'] . "</td>"; echo "<td> <select name='cb_change[]'>"; foreach($options as $option){ if($option == $row['Permissions']){ echo "<option value='" . $option . "' selected='selected'>". $option ."</option>"; }else{ echo "<option value='" . $option . "'>". $option ."</option>"; } } echo "</select> </td>"; echo "</tr>" ; echo "<input type='hidden' name='emp_id[]' value='". $row['employee_id'] ."'>"; } // end while
{ "language": "en", "url": "https://stackoverflow.com/questions/7579733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle restore database to a "newer" version Is it possible to test the incremental backups ... well, incrementally? If so: How? -and not using the words "duplicate" and "standby". Setup * *Multi-TB Oracle 11g (11.2.0.2) database, about 70% of data is in a readonly tablespace. *Backup: weekly level 0 copy (except readonly), semi-daily level 1 incremental (differential data+archivelog). After the level 0 backup, we ship all backup files to a test rig (offline for all intents and purposes) and perform a full restore and recovery. What i want, is to move the incremental backup (< 50G) to the test rig and test only those bits. A recovery test could (in my head) complete in minutes, alternatively in a few hours if the readonly data could somehow be preserved. Otherwise it takes ~9 hours for a full restore+recovery. The ultimate goal is to reduce the disaster recovery testing time by the ~70% taken by the readonly tablespace on the 12 hour incremental cycles - a full restore/recovery once a week is required by policy. If my - as yet incomplete - solution is way off suggestions are most welcome (still not using "duplicate" or "standby" :o). EDIT Oct 4 2011: So i figured out how to avoid restoring the readonly tablespace on every test, so that's 70% time saved. What remains is to figure out whether it's possible to restore only the latest incremental backup onto the test-rig. To be clear: Sunday I end up with at fresh restore+recover of everything, including readonly. Every 12 hours I perform a new restore-test, which skips the readonly bits but performs a level 0 restore of the remaining 30%, then applies the incrementals - in effect rolling back to Sunday and then catching up to the latest incremental. What I'd like is to do a full restore sunday, and every 12 hours "apply" only the latest incremental backup to this restore and avoid the rollback to Sunday. A: I'm not sure of the split between backup time, transfer time, and restore time for your configuration but here are my thoughts. If you want to reduce restore time investigate the CHECK READONLY parameter for the RMAN RESTORE command. It sounds like you can keep a copy of your read-only datafiles on your target system and not have incur the overhead of RMAN pushing all those bits and bytes around at restore time. You didn't mention version so from the 9i RMAN documentation for RMAN RESTORE command: CHECK READONLY Checks the headers of read-only files to ensure that they are current before omitting them from the recovery. If you want to reduce transfer time of your Level 0 backupset and can guarantee safety of the readonly data files, investigated the SKIP READONLY parameter for BACKUP command. SKIP READONLY Specifies that read-only datafiles should be excluded from the backup set. If you are paranoid (like me) and need another level of verification you could run a checksum your readonly datafile(s) on both sides to make sure you get back the same value. But just be aware of how you are handling this situation - will the same procedure be followed in the event of a true restore scenario (whether it is CHECK READONLY or another method)? A: I feel this needs to answered, if only partially, so here you go: The recovery-part is still open, but avoiding the readonly-tablespace bit is solved using transferable tablespaces. Basically, * *mark your readonly tablespace as transferable *generate a dump file using expdp *copy your datafiles to the test rig *do a restore, but skip the tablespace in question *drop tablespace from database *impdp to your database. (essentially re-create from import) We did this for a 3TB tablespace, took all of 30 seconds. (and 10 hours to copy :oP) A word of caution: marking as transferable and dropping a tablespace may not be the right thing to do, especially if you have dependencies between tablespaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why jstl is not working? Like in the article , I have placed the following files in WEB-INF/lib folder of my applicaion * *Standard.jar (1.1.2) *jstl.jar (1.1.2) in taglib it states that it would resolve uri tag in the TLD of a taglib deployed in a jar file (WEB-INF/lib). And my application keep throwing errors that it cannot found any tag libs. When I extracted the Standard.jar\MET-INF *.tld files under to WEB-INF\tld folder, It worked and sorted. But still is there a cleaner way I could do it, So I may not need to update that taglibs separately other than replacing it with the new version? Exception org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application A: You probably don't have them in your build path. Placing them in libs folder may not be sufficient. In Eclipse for example: right click on project -> Build Path -> Configure Build Path ... Then in Libraries tab add your jars using Add External JARs button. A: You should not extract the JAR files and clutter your webapp project with its loose contents. Remove them all. You should not manually define the taglibs in web.xml. Remove them all. You should not put them in some random /lib folder and fiddle with IDE build path properties. Remove them all and undo the changed buildpath properties. All you need to do is: * *Download the zip, extract it, open its /lib folder and copy jstl.jar and standard.jar files in /WEB-INF/lib folder (thus, not /lib) of your webapp. A bit decent IDE should already have created the /WEB-INF/lib folder for you. You just have to drop the JARs in there. *Declare the taglibs with proper URI in JSPs as per the tag documentation. For JSTL 1.1 Core taglib it's the following <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> (note the /jsp in the path, this is often overlooked because old JSTL 1.0 didn't have this) See also: * *Our JSTL tag info page A: You can check file web.xml <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> end in file .jsp add <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> A: you need to define the taglib's information in web.xml like : <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> and this uri name you can use in jap like : <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: You have already activated rake 0.8.7, but your Gemfile requires rake 0.9.2. Consider using bundle exec. I Just moved to site 5 after creating my application offline. I am having problems with rake. When i try to run cd ~/MYAPP/; rake db:migrate --trace RAILS_ENV='production' I get the following error You have already activated rake 0.8.7, but your Gemfile requires rake 0.9.2. Consider using bundle exec. When i try to unistall rake 0.8.7 I get the following warning. addressable-2.2.6 depends on [rake (>= 0.7.3)] execjs-1.2.6 depends on [rake (>= 0)] execjs-1.2.4 depends on [rake (>= 0)] friendly_id-3.3.0.1 depends on [rake (~> 0.9.2)] launchy-2.0.5 depends on [rake (~> 0.9.2)] multi_json-1.0.3 depends on [rake (~> 0.9)] orm_adapter-0.0.5 depends on [rake (>= 0.8.7)] rack-1.3.2 depends on [rake (>= 0)] rack-1.2.3 depends on [rake (>= 0)] rack-mount-0.8.3 depends on [rake (>= 0)] railties-3.1.0 depends on [rake (>= 0.8.7)] railties-3.0.9 depends on [rake (>= 0.8.7)] sprockets-2.0.0 depends on [rake (>= 0)] therubyracer-0.9.4 depends on [rake (~> 0.9.1)] thor-0.14.6 depends on [rake (>= 0.8)] treetop-1.4.10 depends on [rake (>= 0)] I have seen a lot of articles about uninstalling one. When i remove rake 0.9.2 i get an error no such file to load -- rake/dsl_definition When already have the following in my rake file. require 'rake/dsl_definition' require 'rake' Has anyone solved this problem, I have tried all too You have already activated X, but your Gemfile requires Y A: Try to run this command: bundle exec rake db:migrate --trace RAILS_ENV=production In this way you should launch your command with the pack of gem bundled with your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a possibility to display message in gmail by a an url which would contain messegaID of the message? I'm trying to find a way how to display message in gmail (using its gui) using url and messageID passed somewhere maybe in query string. I think it should look like this. https://mail.google.com/mail/?shva=1#inbox/messageID I know that each message has a unique url for example : https://mail.google.com/mail/?shva=1#inbox/132aa50e42798b61 - but I do not know how to programatically determine the identifier 132aa50e42798b61. What Im doing is retrieving messages list via Javax.mail - but I do not want to retrieve the entire content of mail message using java- I'd rather prefer to use gmail gui to display selected message. If anyone has an idea how to display message in gmail using messageID or another identifier which is a part of message, please help. A: You can only display entire conversation in Gmail, not a single message. Gmail link that points to the conversation looks like this: https://mail.google.com/mail/u/0/#inbox/13216515baefe747 “13216515baefe747″ is the Gmail thread-ID in hex. To dermine the thread-Id using IMAP you need to use X-GM-THRID extension (http://code.google.com/apis/gmail/imap/#x-gm-thrid) and convert the result to hex. IMAP conversion looks more or less like this: Mail.dll: 6 10:07:49 C: c39dcdd3ce84473a UID FETCH 10350 (UID X-GM-THRID) Mail.dll: 6 10:07:49 S: * 1 FETCH (X-GM-THRID 1381181440384575604)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to send SMS programmatically using UDID without cost in iPhone I want to know is it possible to send SMS programmatically using Objective-C in iPhone using UDID means that the TO address should be an UDID of the other iPhone than phone number. A: You cannot send an SMS to another phone that you only know by UDID. An SMS always needs a phone number as address. A: If you know the UDID then you can send Push Notification using your own server. THIS WILL ALLOW THE USER TO CHAT WITHIN YOUR APPLICATION. A: No, this is not possible. First SMS works with phone numbers, zo not a UDID. The User will also be charged for sending a SMS and you can only send a SMS via de MFMessageComposeViewController. There is not way to do it in code only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Calling COM Method From UI Thread Problem I wonder if you could help me solve my COM problem. I have a program that calls a COM method when the button is clicked. The code looks something like this: private void Send_Click(object sender, EventArgs e) { p.Send(allChanges); } This code works fine. But I have another program that calls the same COM method. the code looks like this: private void Publish(List<Tuple<string, DataPair>> allChanges) { var d = new SendCallback(Send); d.BeginInvoke(allChanges, null, null); } As you can see here I invoke the COM method using a delegate. If I don't use delegate, the program will crash due to COM exception. The underlying Send function is the same. Could anyone please advise? Thanks very much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying a certain number of columns in Oracle I have a table containing five columns. How can I display only the first three columns of the table using the number of columns like 3 instead of writing the column name? A: You cannot do that. You have to list the columns by name. The column "position" has no meaning in a relational database (just like a row does not have a "position").
{ "language": "en", "url": "https://stackoverflow.com/questions/7579750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I use `our` variables in Perl I have following PL and PM files Start.PL, ConfigReader.PM, BL.PM, Logger.PM Code extract from ConfigReader.PM Package ConfigReader use Config::Simple; use Logger; our $configIni; sub OpenConfigIni() { my ($cfg_ini_path)=@_; &Logger::LogMsg("**** OpenConfigIni starts ****","info"); &Logger::LogMsg($cfg_ini_path,"info"); $configIni = new Config::Simple($cfg_ini_path); &Logger::LogMsg("**** OpenConfigIni ends ****","info"); } Where Logger.PM is a custom module I have written using Log4Perl. Code extract from BL.PM Package BL use strict; use Logger; use ConfigReader; my %chash = %{$ConfigReader::configIni->param( -block => "UserDetails")}; Code extract from Start.PL Start.PL is the entry point to my application which initiates Logger, ConfigReader use strict; use ConfigReader; use Logger; use BL; &Logger::InitiateLogger(); &ConfigReader::OpenConfigIni("My_Config.ini"); my %qhash = %{$ConfigReader::configIni->param( -block => "ABC")}; Problem is When i run Start.PL, the code fails with following error Can't call method "param" on an undefined value at BL.pm line 9 Compilation failed in require at Start.pl line 19. BEGIN failed--compilation aborted at Start.pl line 19. (Ignore Line numbers) It is pointing to following in BL.pm my %chash = %{$ConfigReader::configIni->param( -block => "UserDetails")}; If i comment use Bl in start.Pl, the script works fine that means my %qhash = %{$ConfigReader::configIni->param( -block => "ABC")}; works fine in Start.PL what i am trying to achieve here is that 1. Use the ConfigReader.PM for handling the configuration related 2. Make use of the our $configIni in all modules 3. Initialing the Logger and ConfigReader form start.pl whioch is the entry point here What could be the problem here? A: The initialization of %chash happens when BL.pm is loaded. Which happens as part of the use BL; in Start.PL. As you can see, execution of Start.PL at that point has not yet reached the call to OpenConfigIni, so the $ConfigReader::configIni variable has not yet been initialized. The %qhash initialization in Start.pl happens after the config initialization call, so that works. As you have discovered, initializing %chash from a function works. Initializing your various modules explicitly through initialization functions is IMO better style than relying on load order to get the initializations right. And mixing and matching doesn't work that well, as you've seen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook session Fetching from facebook app in iphone I have created a sample iphone application that uses facebook api. Its work fine.I have logged in using facebook api and store the accessstoken and expiredate in NSUserDefault. When they again enter into my application.I have checked the facebook session is valid,if its valid we cannot show a login screen. We use the session for further operation. This is the process my app working now. What i want is , I have downloaded a facebook app in my iphone.I logged into facebook app using my facebook account. Now i want to run my sample application,it shows an login dialog. Here i dont want to get user credential because they already logged in on facebook app.So i want to get that facebook sesssion and use it in my application. Is it possible ? Thanks in advance.......... My objective is to get the facebook session from another application .(If he logged in using facebook account.) A: You cannot access the data from another app's sandbox. But the Facebook SDK for iOS automatically tries to circumvent it: it checks if the Facebook app is installed and if it is, launches it so that the user can authorize your app and then relaunches your app. All you have to do is register a custom URL scheme so that the Facebook app can relaunch your app. The whole procedure is described in the SDK documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert into on duplicate update Mysql error I'm trying to insert on duplicate key update in Mysql using below: INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) VALUES (NULL, qqqq, 115, 0) ON DUPLICATE KEY UPDATE keyword=VALUES(qqqq), client_id=VALUES(115), desc_id=VALUES(0) but it gives me this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '115), desc_id=VALUES(0)' at line 1 Is there a reason why? A: The VALUES "function" in the UPDATE part of the query refers to the column names that you used in the INSERT part. What you want is this: INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) VALUES (NULL, 'qqqq', 115, 0) ON DUPLICATE KEY UPDATE keyword=VALUES(keyword), client_id=VALUES(client_id), desc_id=VALUES(desc_id); This way, you can refer back to whatever values you wanted to insert; they may be calculated values, or they may have come from a SELECT query. When you get into more complex queries, I think you'll find this much more convenient than what you were trying to do. Most of the time, when you use ON DUPLICATE KEY UPDATE, you will have no reason to do anything other than UPDATE x=VALUES(x), y=VALUES(y), z=VALUES(z) for whatever columns you wanted to insert. If you really just wanted to insert the values that you had specified for the various columns, then leave out the VALUES(); you could just do it like this: INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) VALUES (NULL, 'qqqq', 115, 0) ON DUPLICATE KEY UPDATE keyword='qqqq', client_id=115, desc_id=0 However, this requires you to enter all the values twice, and every time you change the statement you'll have to make sure everything matches up. It wouldn't hurt to read the manual, as the error message suggests: http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7579762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help syntax for a dos command I'm looking for a reference regarding the syntax of the help displayed for a dos command. I didn't find anything with Google. I need this because I'm writing a batch and I want to provide help for this batch regarding arguments and options. I know I could deduce it from the help of existing dos commands, but it would be great if there was a full reference about it. A: You mean the syntax as in the following? findstr [/b] [/e] [/l] [/r] [/s] [/i] [/x] [/v] [/n] [/m] [/o] [/p] [/offline] [/g:file] [/f:file] [/c:string] [/d:dirlist] [/a:ColorAttribute] [strings] [[Drive:][Path] FileName [...]] That's easy. Things in square brackets can be omitted. The [...] at the end indicates that you can supply more files if you wish, it doesn't have to be just one. There are also alternatives sometimes: attrib [{+r|-r}] [{+a|-a}] [{+s|-s}] [{+h|-h}] [[Drive:][Path] FileName] [/s[/d]] indicated by curly braces while alternatives are separated by |. Also noteworthy here: /d at the end is only valid if you also provided /s since there are two nested levels of brackets. There is no strict syntax definition and you can usually figure out some other aspects, like the [...] on your own. Many examples need a bit interpretation (which mostly is obvious, though). E.g. date: date [mm-dd-yy] [/t] You can supply a date in a weird format as the first argument, but that's very easy to guess. And no, it doesn't tell you to supply literally mm-dd-yy, but that's why humans read that description, not machines. EDIT: I just noticed that Technet even gives a summary of the syntax at the bottom of each article:
{ "language": "en", "url": "https://stackoverflow.com/questions/7579766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Socket.io log (client not handshaken client should reconnect) is anyone facing this problem too? My logfile is flooded with that message: "client not handshaken client should reconnect" & "transport end". It's hard for me to reconstruct, as it doesn't appear when i connect to my socket server with different browsers. But on live environment with different users, my log file size grows exponential :) Anyone having this problem too? A: I have noticed that this is just happening in xhr-polling mode on chrome v14. So I installed Chrome v16 dev and the problem is fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: the mystery of the vanishing web form http://poland.inbulgaria.org/search This web form, based on jQuery, but also including a SVG map control made with Raphael, appears correctly in Opera 11.51, as well as IE 8, but, for some reason, doesn't render at all in Firefox 6. Any clue why? A: First thing I noticed is that you aren't escaping some of your class names and ID's with quotation marks, eg <div class=advBox id=advOfferType> Firebug is giving NaN values for the positioning of these elements which is a bad sign. Escape those IDs & class names, then get back to us. A: Frustrated, I asked this question in a "share your mood" thread on some tiny forum with literally 5 users, and... I got a solution. Adblock is blocking the form. Yeah, silly as that. (: Maybe it's because it's called Advanced Search, and there are a lot of DIVs with classes starting with adv. Now that's something I've never heard happen to anyone else...
{ "language": "en", "url": "https://stackoverflow.com/questions/7579768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharing intermediate files between C++ projects? I'm currently trying to figure out whether it is possible for two different native Visual-C++ projects (that have exactly the same compiler settings) to share their intermediate files (obj, pch, ...) An example should help: This is a normal setup: PROJECTS \ P1 \ p1.vcproj; p1.cpp; ... \ Release_Intermediate_Dir \ p1.obj \ tool1.obj \ P2 \ p2.vcproj; p2.cpp; ... \ Release_Intermediate_Dir \ p2.obj \ tool1.obj \ COMMON \ tool1.cpp; ... What about this setup: PROJECTS \ P1 \ p1.vcproj (uses: p1.cpp; p1_main.cpp) \ p1_test.vcproj (uses: p1.cpp; p1_test.cpp) \ Release_Intermediate_Dir \ p1.obj (used by both projects p1 and test) \ tool1.obj \ p1_main.obj (only p1.vcproj) \ p1_test.obj (only p1_test.vcproj \ COMMON \ tool1.cpp; ... Can I use the same intermediate folder for two C++ projects, thereby sharing the obj files directly? Or will I always need to have an additional static lib project? (As far as I understand, a static lib is just a container for obj files.) Why would I want to do this? Look at this blog post: Writing Unit Tests in Visual Studio for Native C++. It uses a static lib for the sole purpose of having two different executables (main functions, if you will). (Forget about the managed/CLI stuff.) This means having 3 projects in your solution (having to maintain three projects), when you really only want two projects that share the same code with the same compilation settings but use a different main/startup rigging. A: By enforcing the same compilation flags for both projects and making the intermediates of project A prerequisites of project B, you remove all degrees of freedom from B. There is no conceivable possibility to compile B alone, and your link suggests B has no raison d'etre apart from testing A. The easiest and cleanest solution would be to merge the tests from B into A and make the whole thing one project (which it is, frankly). In automake parlance, you'd declare the unit tests in B as check_PROGRAMS and they'd only be compiled for checking your program. I'm no Visual-C++ expert, but that's the clean solution and should somehow be doable with VC++. Addendum: To clarify the automake parlance, a project there would for example look like: noinst_LTLIBRARIES = libthings-to-test.la libthings-not-tested.la bin_PROGRAMS = production check_PROGRAMS = unit_test_a production_SOURCES = main.cpp production_LDADD = libthings-to-test.la libthings-not-tested.la unit_test_a_SOURCES = test.cpp unit_test_a_LDADD = libthings-to-test.la libthings_to_test_la_SOURCES = foo.cpp bar.cpp baz.cpp with the whole codebase (production code, common libraries, tests) in one project, i.e. one unit that is configured and distributed wholly and has a single version number attached. When installed by the end user/distributor, a single program production.exe would be linked. When compiled with make all, the convenience libraries and necessary objects would be compiled in the build directory, and when make check is called, the objects only necessary for unit tests are compiled, the production code linked in and the tests are run. Again, I'm sorry I can't translate this into Microsoft Speak.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find latitude and longitude Can any one help me in getting the latitude and longitude value of the place? The place details must be gotten from the user as a input. The place detail can be ZIP code, city name, address, or state code. A: You can use the Google Geocoding API to convert an address into a lat/lng. A: One way I have used is to utilise the google maps API to return a lat/long for a given zip/postcode or city etc. Its normally quite good at dealing with different inputs. Sadly I don’t have any C samples but could post up a VB.Net example if that helps A: You need to geocode the address. Since Mapkit doesn't support geocoding (only reverse-geocoding) you'll have to use a web service to accomplish that. The are tons of web services for that. For example Google Geocoding
{ "language": "en", "url": "https://stackoverflow.com/questions/7579775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to set JVM parameters for Junit Unit Tests? I have some Junit unit tests that require a large amount of heap-space to run - i.e. 1G. (They test memory-intensive functionality for a webstart app that will only run with sufficient heap-space, and will be run internally on Win 7 64-bit machines - so redesigning the tests isn't a practical suggestion.) I am developing in Intellij IDEA, so I know I can set the JVM parameters (e.g. -Xmx1024M) for the test class. However, this is only for running the whole test class - if I want to run an individual test, I have to recreate the run congfigurations for that test method. Also, those are IDE and box specific - so if I switch boxes (I develop on multiple machines) or one of my colleagues tries to run the tests, those settings are not transferred. (Also, other IDEs like Eclipse and NetBeans are used by my colleagues.) FWIW, we're using mercurial for source code control. For the build cycle, we're using Maven, so I know how to specify the JVM parameters for that. So: - I'm looking for a way of specifying the JVM parameters that will apply for the whole test class and the individual test methods; and - I'd like to share those specification across IDEs on any machine (having picked up the code from the repository). A: In Maven you can configure the surefire plugin <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.9</version> <configuration> <argLine>-Xmx256M</argLine> </configuration> </plugin> If you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the Maven Surefire Plugin documentation. A: In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse. However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it. You know how to set these for maven-surefire-plugin. Good. This is the most portable way (see Ptomli's answer for an example). For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner. To give you an example: you cannot define Xmx parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G. A: Parameters can be set on the fly also. mvn test -DargLine="-Dsystem.test.property=test" See http://www.cowtowncoder.com/blog/archives/2010/04/entry_385.html A: You can use systemPropertyVariables (java.protocol.handler.pkgs is your JVM argument name): <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <systemPropertyVariables> <java.protocol.handler.pkgs>com.zunix.base</java.protocol.handler.pkgs> <log4j.configuration>log4j-core.properties</log4j.configuration> </systemPropertyVariables> </configuration> </plugin> http://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html A: If you set it in Java code, you can set it like this static { System.getProperties().setProperty("env", "test"); System.getProperties().setProperty("spring.application.name", "spring-example"); } reference: https://stackoverflow.com/a/60654275/4712855 https://stackoverflow.com/a/10774432/4712855 A: According to this support question https://intellij-support.jetbrains.com/hc/en-us/community/posts/206165789-JUnit-default-heap-size-overridden- the -Xmx argument for an IntelliJ junit test run will come from the maven-surefire-plugin, if it's set. This pom.xml snippet <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>-Xmx1024m</argLine> </configuration> </plugin> seems to pass the -Xmx1024 argument to the junit test run, with IntelliJ 2016.2.4. A: I agree with the others who said that there is no simple way to distribute these settings. For Eclipse: ask your colleagues to set the following: * *Windows Preferences / Java / Installed JREs: *Select the proper JRE/JDK (or do it for all of them) *Edit *Default VM arguments: -Xmx1024m *Finish, OK. After that all test will run with -Xmx1024m but unfortunately you have set it in every Eclipse installation. Maybe you could create a custom Eclipse package which contains this setting and give it to you co-workers. The following working process also could help: If the IDE cannot run a test the developer should check that Maven could run this test or not. * *If Maven could run it the cause of the failure usually is the settings of the developer's IDE. The developer should check these settings. *If Maven also could not run the test the developer knows that the cause of the failure is not the IDE, so he/she could use the IDE to debug the test. A: An eclipse specific alternative limited to the java.library.path JVM parameter allows to set it for a specific source folder rather than for the whole jdk as proposed in another response: * *select the source folder in which the program to start resides (usually source/test/java) *type alt enter to open Properties page for that folder *select native in the left panel *Edit the native path. The path can be absolute or relative to the workspace, the second being more change resilient. For those interested on detail on why maven argline tag should be preferred to the systemProperties one, look, for example: Pick up native JNI files in Maven test (lwjgl)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "106" }
Q: How do create a DatePicker with only Sundays enabled? I need to allow user to select only the Sunday from my date picker so I need to disable other columns. But I couldn't find any solution for this. Currently I just check in the selection-changed event and clear the date if not valid. How do I disable the non-Sundays entirely? A: The relevant section in @kalyan's suggested link regards blackout dates, and the DatePicker's BlackoutDates property, which lets you specify ranges of dates that users cannot select. That property is of type CalendarBlackoutDatesCollection, which is a subclass of ObservableCollection<CalendarDateRange>. Knowing this, you can programmatically add ranges that include the Monday through Saturday to this collection for all weeks to be displayed on your calendar. An important consideration to note is described on the MSDN page for the BlackoutDates property: Adding a date to this collection when it is already selected or adding a date outside the range specified by DisplayDateStart and DisplayDateEnd will cause an ArgumentOutOfRangeException. So make sure you know how those two properties are defined. A simple example: //Code assumes a DateTimePicker declared in XAML with its Name property set to "calendar" var minDate = calendar.DisplayDateStart ?? DateTime.MinValue; var maxDate = calendar.DisplayDateEnd ?? DateTime.MaxValue; //pardon the somewhat clunky DateTime.MaxValue handling here; it prevents an overflow //when actually adding dates near the maximum for (var d = minDate; d <= maxDate && (DateTime.MaxValue - d.AddDays(7)).Days > 7; d = d.AddDays(7)) { var range = new CalendarDateRange(d, d.AddDays(5)); calendar.BlackoutDates.Add(range); } Please Note: by default, a DateTimePicker's DisplayDateStart/End properties are set to null. The code above therefore blacks out ALL days except Sundays from January 1, 0001 AD through December 31, 9999. This results in extremely poor performance when the Calendar control is displayed and interacted with. So if you're going to use this technique, I strongly suggest constraining the picker's start and end dates (and therefore the number of blackout-date ranges) to sensible limits. A: Did you referred to the Calendar & DatePicker Walkthrough
{ "language": "en", "url": "https://stackoverflow.com/questions/7579777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Missing Terminating "" character & Unexpexted @ in the program While writing the following code i got two errors : 1.Missing Terminating "" character 2.Unexpexted @ in the program " Here after entering "HEllO" , "WORLD" is wriiten on the next line (i.e. after HELLO enter is pressed ). NSString *str = @"HELLO --------> line 1 WORLD"; --------> line 2 Does anyone knows solution to this error. A: If you write string literal in several lines then each line must start and end with ": NSString *str = @"HELLO" --------> line 1 "WORLD"; --------> line 2 If you just want to display your text in several lines do what @jrturton suggests - add new line character ('\n') to your string A: Do this instead: NSString *str= @"HELLO\nWORLD";
{ "language": "en", "url": "https://stackoverflow.com/questions/7579781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery Ajax call not getting the respose from the servlet Once the submit button is clicked, The name typed on the name textbox is printed in the servlet . But the response send by the servlet is not coming back to the client. I am not sure where i am going wrong. Need help. JQuery-Ajax i am calling my sampleServlet. HTML PAGE <script> $(document).ready(function(){ $(".Submit").click(function(){ nameVal=$("#name").val(); alert(nameVal ) ; $.get("http://localhost:8080/dummyService/SampleServlet", {name:nameVal}, function(data) {//This function is supposed to be called once the servlet send the response alert(data) ; $("#flag").html(data) ; }); }); }); </script> <form id="sampleform" method="POST"> <center> Enter your Name: <input id="name" class="name" type="text"> <br/><br/> <input class="Submit" name="Submit" type="button" value="Submit" id="Submit"> </center> </form> <div id="flag"> </div> **SampleServlet** protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("INSIDE DO GET"); String name = request.getParameter("name"); System.out.println(name); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Hello " + name); out.flush(); out.close(); } A: The HTML page containing the JavaScript and your servlet must be on the same hostname and port because of the same origin policy.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to insert jpeg files in edittext android Is there any way to add jpeg files to edittext in android. Basically i am creating a rich text editor in android which should have a provision to display images. Or do i need to make changes in edittext canvas for that. Any suggestions would be really helpful. -Regards, Ron.. A: Maybe you could use the android-richtexteditor component. http://code.google.com/p/android-richtexteditor/ The code has been deleted from the official project but it is still available in the history. http://android-richtexteditor.googlecode.com/svn-history/r3/trunk/ A: EDIT: Sorry I did not take enough time to read. You wanted an Editable with picture, not a simple TextView. Anyway, the solution is maybe to catch user keys and update a webview on the fly using webview.loadUrl("javascript:onKeyDown("+keyCode+")"); You will need tight javascript/java linking. It can be somewhat tough to code but you will not be limited in terms of rich content. Former answer: You may want to use a WebView instead of a TextView. They can be very lightweight if you feed them with simple HTML. For example, if you want to use the image myImage.png that you stored in your project assets folder, simply use: WebView myWebView = (WebView) findViewById(R.id.myWebView); String richContent = "<html><body>This is text and an <b>Image</b>: <img src=\"file:///android_asset/myImage.png\" /></body></html>"; myWebview.loadData(richContent, "text/html", "utf-8");
{ "language": "en", "url": "https://stackoverflow.com/questions/7579797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Still getting deprecation warnings in Rails3.1 I keep getting depreciation warnings while testing in Rails 3.1 like RailsProject$ bundle exec autotest NOTE: Gem.source_index is deprecated, use Specification. It will be removed on or after 2011-11-01. Gem.source_index called from /Users/CS/.rvm/gems/ruby-1.9.2-p290/gems/ZenTest-4.5.0/lib/autotest.rb:226. NOTE: Gem::SourceIndex#gems is deprecated with no replacement. It will be removed on or after 2011-11-01. Gem::SourceIndex#gems called from /Users/CS/.rvm/gems/ruby-1.9.2-p290/gems/ZenTest-4.5.0/lib/autotest.rb:226. loading autotest/rails /Users/CS/.rvm/rubies/ruby-1.9.2-p290/bin/ruby -I.:lib:test -rubygems -e "%w[test/unit test/unit/rim_test.rb test/unit/page_test.rb test/functional/pages_controller_test.rb test/unit/helpers/pages_helper_test.rb test/unit/order_test.rb test/unit/admin_user_test.rb test/unit/helpers/cart_helper_test.rb test/unit/customer_test.rb test/unit/ordered_service_test.rb test/unit/services_test.rb test/functional/cart_controller_test.rb].each { |f| require f }" | unit_diff -u /Users/CS/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/rubygems_ext.rb:43: warning: method redefined; discarding old gem_dir /Users/CS/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1262: warning: previous definition of gem_dir was here /Users/CS/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/rubygems_ext.rb:154: warning: method redefined; discarding old hash /Users/CS/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/platform.rb:125: warning: previous definition of hash was here /Users/CS/.rvm/gems/ruby-1.9.2-p290/gems/bundler-1.0.18/lib/bundler/rubygems_integration.rb:183: warning: method redefined; discarding old initialize /Users/CS/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/deprecate.rb:53: warning: previous definition of initialize was here My versions: RailsProject$ bundle exec rails -v Rails 3.1.0 RailsProject$ bundle exec gem -v 1.8.10 RailsProject$ bundle exec bundle -v Bundler version 1.0.18 I tried all that gem pristine --all --no-extensions stuff from this post - with and without bundle exec Every gem is up-to-date. Does anybody have an idea how to solve that? A: The problem is that you're not using the latest version of ZenTest. You're using 4.5.0 and the latest is 4.6.2. Try running gem update ZenTest gem update autotest and you might need to update your Gemfile in your rails app and run bundle install to lock the gemfile to the latest versions of the gems. A: you need to install ZenTest 4.6.2. if you use rails 3.1,you will find that autotest-rails (4.1.1) dependency on ZenTest (= 4.5.0). just modified the Gemfile.lock, search the ZenTest, change it to use 4.6.2, and change the autotest (4.4.6) ZenTest (= 4.5.0) to autotest (4.4.6) ZenTest (= 4.6.2) then, run bundle install That's all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sql: joining two tables I have two tables called mp_Blogs and mp_BlogCategories mp_blog has columns and values ItemID ModuleID 3 11 4 11 5 13 mp_BlogCategories has column and values CategoryID ModuleID 1 11 2 11 3 13 I need the output like this ItemID CategoryID 3 1 4 2 5 3 I used this query SELECT a.[ItemID],b.[CategoryID] from [mp_Blogs] a join [mp_BlogCategories] b on a.ModuleID=b.ModuleID But its coming in different way ItemID CategoryID 3 1 4 1 3 2 4 2 5 3 I used groupby function also but output same as before,any mistake in query how to get my original output SELECT a.[ItemID],b.[CategoryID] from [mp_Blogs] a join [mp_BlogCategories] b on a.ModuleID=b.ModuleID group by b.CategoryID,a.ItemID A: You query is performing properly but there is problem with data in you table as you can see the table contains 11 id two time thats y its giving the result like that. its better to check out the data in table. A: From the Output it seems there is something wrong with the Data, not the Query. A: After reading comments you are lacking for unique key in both the tables so i suggest you to add key in both the tables in order to achieve your result. How it would be - tested in mysql working fine. -- id column primary key in mp_blog table. create table mp_blog(id smallint(5),ItemID smallint(5), ModuleID smallint(5),constraint mp_blog_id primary key(id)); insert into mp_Blog values(1,3,11),(2,4,11),(3,5,13); -- id column foreign key references to mp_blog primary key id. create table mp_BlogCategories(id smallint(5),CategoryID smallint(5), ModuleID smallint(5),constraint fk_mp_blogc foreign key(id) references mp_blog(id)); insert into mp_BlogCategories values(1,1,11),(2,2,11),(3,3,13); -- finally what you are trying to achieve.. select b.itemid,bc.categoryid from mp_blog b INNER JOIN mp_BlogCategories bc on b.id=bc.id; ItemID CategoryID 3 1 4 2 5 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7579803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Build Library Management System only using MySQL Stored Procedure with Java I am thinking to use only Stored Procedures while developing Library Management System in Java with MySQL. But some articles show that only using Stored Procedures is an expensive method, due to the metadata retrieval that the driver performs to support output parameters. So, performance reason it is not recommended. Just use queries in your developments. So, is it recommended to use only stored Proedures or not? Strong reasons with logics are welcomed! A: Yes this is right that there is performance issue of stored procedure so if you want to developed "online public access library catalog" (OPAC), better to use queries but if your application is to be used only in your organization stored procedure will help you to get rid of massive queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How ["03C0"] match 's grammar in Annex P? I'm writing a tool to parse Ada source file with the grammar provided in 2005 Annex P. * *With following piece of code, I know ["03C0"] stands for "greek letter Pi", but is it a legal variable name? 01 package Ada.Numerics is 02 Pi : constant := 3.14159_26535_89793_23846_26433_83279_50288_41971_69399_37511; 03 ["03C0"] : constant := Pi; 04 e : constant := 2.71828_18284_59045_23536_02874_71352_66249_77572_47093_69996; 05 end Ada.Numerics; *When using the grammar to parse line 03, I currently come to "basic_declaration". Which is the next rule? And next next rule? Next next next rule? Until ["03C0"] can be successfully parsed. Eventually, the question should be: Which rule parsed ["03C0"]? The Ada Reference Manual is at: http://www.adaic.org/resources/add_content/standards/05rm/RM-Final.pdf Ada Reference Manual Page 702 in PDF, Page 676 at the right down corner of the page . Annex P / 3.1 3.1 basic_declaration ::= type_declaration | subtype_declaration | object_declaration | number_declaration | subprogram_declaration | abstract_subprogram_declaration | null_procedure_declaration | package_declaration | renaming_declaration | exception_declaration | generic_declaration | generic_instantiation I've done further investigation based on oenone's answer. * *If I use ["03C0"] in the code, the character set does not need to be "UTF-8", which makes sense. When compile, I need "gnatmake -gnatWb Hello.adb". *If I use p in the code, I must change the character set to "UTF-8", otherwise the GPS will not recognize this character and prompt a message. After I change it to UTF-8, I need to use "gnatmake -gnatW8 Hello.adb" to compile. *I tried to change ["03C0"] to ["abcd"] and compile again, it will fail, saying "invalid wide character in identifier". I GUESS: If ["03C0"] is parsed by grammar only, ["abcd"] will also pass the grammar check. So from the fail result and message, I can say, GNAT works in this way: there is a pre-process before send source file to the grammar parser. The pre-process will evaluate the unicode value, check whether or not it is in the valid wide character set. If it is inside the valid wide character set, it will continue send to the grammar parser. Otherwise, fail. A: 1: see A.5 The Numerics Package - the RM uses the correct unicode character. Your quote seems to be from the GNAT package. For this, see the GNAT Users Guide about how to tell GNAT which encoding it should use. 2: No rule from the ARM. It is an encoding question, which is done by the implementation (GNAT). ["03C0"] (with -gnatWb, which is default) is handled like π (with -gnatW8) or even Pi as valid identifier for a variable name (or in this case constant).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Which item was selected in my TreeView In my application I build a TreeView by a binding. The ItemSource contains a list of items of type X. X has a property 'Properties' some of these properties are references to an item in the parent list. The TreeView starts at a selected root (an item from the list). All properties which are references are added to this root as TreeViewItems. However, they can be expanded too until the end is reached, or not; I mean that this could theoretically be an infinite recursion for it is possible that a reference refers to itself. The question now is, how do I know which Item is selected? I need to know the level and all its parents. I thought up these things: * *While expanding the tree, keep track of the levels and parents. This does not work obviously because after selecting an other item below a different parent, I lose track of the other path. *Check for the e.OldValue. This also doesn't work for the same reason of the previous try. *While expanding (and with that creating) the TreeView, construct a TreeView like variable in c# behind the code. At first this seems to be quite close to the solution since you cannot remove nodes from the TreeView ones they are created. For example: You go to the 5th level and collapsed the first level. If you expand the first level you'll see the the path exacly the same as before the collapse. To create the TreeView in this way I had to override the DataTemplateSelector. (C#) public class TreeViewDataTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { FrameworkElement element = container as FrameworkElement; if (element != null && item != null) { if (item is Entity) return element.FindResource("XTemplate") as DataTemplate; else return element.FindResource("PropertyWithReferenceTemplate") as DataTemplate; } return null; } } The Binding and HierarachialDataTemplate. (Xaml) <TreeView ItemsSource="{Binding ElementName=view, Path=XDefinition}" ItemTemplateSelector="{StaticResource treeViewDataTemplateSelector}" SelectedItemChanged="TreeView_SelectedItemChanged"> <TreeView.Resources> <HierarchicalDataTemplate x:Key="XTemplate" ItemsSource="{Binding Path=Properties}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate x:Key="PropertyWithReferenceTemplate" ItemsSource="{Binding Path=ReferenceToX.Properties,}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView> Can anybody help me on this problem? If there is anything else you need to know please tell me and I'll update my question. Solution I had to change my event SelectedItemChanged="TreeView_SelectedItemChanged" to TreeViewItem.Selected="TreeViewItem_Selected". With the help of the LogicalTreeHelper.GetParent i was able to retrieve the correct parent. A: What about looking up the VisualTree? You can go up until you reach the top item. Before you can evaluate all single items.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Find UIAlertView without having reference to it I'm writing application tests and want to check if an UIAlertView is currently shown. That means I don't have a pointer to it and I need to know who is the owner of the shown UIAlertView or on which views stack it can be found. A: [UPDATE] Actually the solution below is not working for iOS 7, because the alert views are not bound to a specific window any more. Read here for details: https://stackoverflow.com/a/18703524/942107 Based on KennyTM'm advice in another question Sebastien provided link to, I've created a UIAlertView category with a method returning the UIAlertView if shown to be able to dismiss it programatically. UIAlertViewAdditions.h: #import <UIKit/UIKit.h> @interface UIAlertView (UIAlertViewAdditions) + (UIAlertView *) getUIAlertViewIfShown; @end UIAlertViewAdditions.m: #import "UIAlertViewAdditions.h" @implementation UIAlertView (UIAlertViewAdditions) + (UIAlertView *) getUIAlertViewIfShown { if ([[[UIApplication sharedApplication] windows] count] == 1) { return nil; } UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; if ([window.subviews count] > 0) { UIView *view = [window.subviews objectAtIndex:0]; if ([view isKindOfClass:[UIAlertView class]]) { return (UIAlertView *) view; } } return nil; } @end
{ "language": "en", "url": "https://stackoverflow.com/questions/7579821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: rows are interchanging in uitableview in iphone? In my application i need to add contacts of users, for that i am using UITableview with sections. Each section may contains 2 or 3 rows. while the editing was completed and scrolling the table view to top, the rows are interchanging in between sections. Actually In design part i have placed FirstName and LastName in first section and email in second section but they are interchanging as firstName, email as first section and LastName as second section . can any one help me to solve this. Thanks in advance. EDIT: Please find the code snippet below. the method CellForRowAtIndexPath: static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; if(indexPath.section == 0) { if(indexPath.row == 0) { //content of first Name txtFieldFirstName = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 290, 24)]; txtFieldFirstName.tag=1; //txtFieldFirstName.placeholder = @"First"; txtFieldFirstName.delegate = self; txtFieldFirstName.font = [UIFont fontWithName:@"Helvetica" size:16.0]; [cell.contentView addSubview:txtFieldFirstName]; } else if(indexPath.row == 1) { //content of last Name } } else if(indexPath.section == 1) { if(indexPath.row == 0) { //content of Phone No } else if(indexPath.row == 1) { //content of Mobile no } this is how i am implementing my code. Please help me on this. A: You are doing everything inside if (cell == nil) This code is only executed when you first create a cell. If the table view returns a cell that has already been created, cell != nil so the code is not executed. You should only perform base configuration inside cell == nil, everything else should be done afterwards. You may need to have different reuse identifiers for cells in different sections if the layout is not the same. A: The issue is that your cells are being reused, and they are carrying with them the values from the previous contact. It may look like the rows are interchanging between sections, but actually they are interchanging between contacts. This sets the cell content outside of the if (cell == nil) so would address the issue in many cases: static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } if(indexPath.section == 0) { if (indexPath.row == 0) { //content of first Name txtFieldFirstName = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 290, 24)]; txtFieldFirstName.tag=1; //txtFieldFirstName.placeholder = @"First"; txtFieldFirstName.delegate = self; txtFieldFirstName.font = [UIFont fontWithName:@"Helvetica" size:16.0]; [cell.contentView addSubview:txtFieldFirstName]; } else if (indexPath.row == 1) { //content of last Name } } else if(indexPath.section == 1) { if(indexPath.row == 0) { //content of Phone No } else if(indexPath.row == 1) { //content of Mobile no } } However, if some cell properties are set on some occasions, and only others are used on other occasions, you may need to explicitly set the unused cell properties to nil in each case so that they do not carry over values from the previous contact they displayed, then they are reused in the dequeue process. A: Actually this is happening due to reuse identifier of your table cell Try below Code NSString *CellIdentifier=[NSString stringWithFormat:@"cell%d",indexPath.section]; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve opengl info android I have a problem retrieving OpenGL's info on Android. I know I can get'em with gl.glGetString(GLxx.GL_VENDOR) but I don't know how to do it. Is there a way to retrieve them without showing anything on the SurfaceView? I should create a page with the infos and set a textview with the info I need (eg. vendor, version, renderer). Let me know if it's not clear and thank you guys!! :) A: You have to make the call to glGetString on the rendering thread. You don't have to actually draw anything, it just needs to be called on the rendering thread. I suggest using a GLSurfaceView, collecting all the possible information you need in onCreate with glGetString(GLxx.xyz), and then adding the information to some data structure that you can search at a later point. GLSurfaceView's methods like onCreate(), onResume() and onDraw(), are all called on the rendering thread. With this approach, you will not have to call 'glGetString' on demand and therefore you will avoid issues with thread communication between the GL thread and the UI thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem in Div in asp.net <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ryan Merl's Portfolio</title> <style type='text/css'> .dataBold{ float:left; padding:10px 0 0 80px; font-weight:bold; } .dataContact{ height: 1%; padding:10px 0 0 170px; position:absolute; } .data1{ height: 1%; padding:10px 0 0 550px; position:absolute; } .dataBold1 { float:right; padding:10px 0 0 450px; font-weight:bold; text-align: right; position:absolute; } </style> </head> <body> <div class="dataBold"> <asp:Label ID="lblOffice" runat="server" Text="Office"/> </div> <div class="dataContact"> <asp:TextBox ID="txttitle" runat="server"></asp:TextBox> </div> <div class="dataBold1"> <asp:Label ID="lblRegion" Text="Region" runat="server"></asp:Label> </div> <div class="data1"> <asp:DropDownList ID="ddlRegion" runat="server"></asp:DropDownList> </div> </body> </html> Now the Problem is that when i click on text box name txttitle.....cursor is not focusing on text-box....so,i cant able to write in text box... A: Replace the Tag coding inside the body like follows and try again. <form runat="server" > <div class="dataBold"> <asp:Label ID="lblOffice" runat="server" Text="Office"/> </div> <div class="dataContact"> <asp:TextBox ID="txttitle" runat="server"/> </div> </form> A: The problem is because of your absolutely positioned elements, and the fact that you are positioning them using the padding-left style. This means that your Region <select> control is actually appearing above everything else and stopping you from clicking the textbox. If you have a look at this http://jsfiddle.net/jVQQS/6/ This is your HTML and Css. See how the background colours show you the actually layers of your html. You will need to update your html/css and not use absolutely positioned elements, or change the way the elements are positioned. This is an example of what you could do to get it working properly http://jsfiddle.net/jVQQS/11/
{ "language": "en", "url": "https://stackoverflow.com/questions/7579825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Which semantic HTML tag for displaying side notes and admonitions? I am writing an online tutorial with sort of side notes or as they call it "admonitions" similar to those in Django tutorial: https://docs.djangoproject.com/en/dev/intro/tutorial01/ (I mean the the boxes with green a frame and a note icon). Which HTML tag I should use to enclose such notes to add a semantic meaning of a note that may be useful to read at a given point of a tutorial, but is not part of the main tutorial flow? Noteworthy, the tag must allow for enclosing block elements. A: I believe the accepted answer is not quite correct. According to the HTML5 working draft, the <aside> element can be used to mark up side notes in certain, but not all cases: * *<aside> is appropriate if the side note "could be considered separate from the content", for example background material on Switzerland in a much longer news story, or a pull quote in a longer article. (examples from W3C document) *<aside> is not appropriate if the side note is "a parenthetical". The W3C gives no examples of what it means. A narrow interpretation would be anything that is put in parentheses, between commas or between dashes. If you want to interpret the W3C spec strictly, not all of the sidenotes in the Django tutorial can be marked up with <aside>. For example, the note titled "Doesn't match what you see?" could not really be considered separate from the content, since it does not make sense without the content next to it. Arguably, "Where should this code live?" is also not an <aside>, as it mentions "this code", which ties it to the content. In my opinion, the W3C definition is unnecessarily confusing and restrictive. The dictionary definition of aside is "a temporary departure from a main theme or topic", and the spec should just stick to that, rather than introducing subtle distinctions. Of course, there is no reason why you can't use <aside> for all sidenotes, if it makes your code simpler. Think of it as civil disobedience. :) Relevant quote: The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography. The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page. Note: It's not appropriate to use the aside element just for parentheticals, since those are part of the main flow of the document. A: In HTML5 (supported by all modern browsers), the tag is aside. From http://www.whatwg.org/specs/web-apps/current-work/multipage/sections.html#the-aside-element: The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography. The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page. It's not appropriate to use the aside element just for parentheticals, since those are part of the main flow of the document. This is a block-level element and enclose anything a block-level element usually can (i.e. almost anything). It is essentially a "semantic div".
{ "language": "en", "url": "https://stackoverflow.com/questions/7579826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Can I horizontal filp the UIButton? I've some problem with UIButton. In my case I have to flip the button horizontally. I tried it's width to minus value. But it doesn't work. How can I do this? A: Simply set its transform to CGAffineTransformMakeScale(-1.0, 1.0). A: If you want it to rotate 360 degrees horizontally: [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.75]; // transition speed [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.YourButton cache:NO]; [UIView commitAnimations];
{ "language": "en", "url": "https://stackoverflow.com/questions/7579831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regarding current location in android Possible Duplicate: GPS not update location after close and reopen app on android I know that question is asked already but my problem is that. every time when I open my app it shows last location not current location I have a button for current location and i want when i open my app it show current location on map after then when I click on button then it show current location. so my problem is when i open my app it shows last location but when i press then it shows current location. code in onCreate() _locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); _locationListener = new CurrentLocationListener(this,this); _locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1,1,_locationListener ); _currentGeoPoint = getKnownLocation(); _currentPosOverlay = new OverlayItem(_currentGeoPoint, "", ""); Log.d(" overlay", "overlaylast "+_currentGeoPoint); // Toast.makeText(getBaseContext(), "overlay12333vvv "+_currentGeoPoint, Toast.LENGTH_SHORT).show(); _customOverlay.addOverlay(_currentPosOverlay); _mapOverlays.add(_customOverlay); Code for getKnownLocation() // TODO Auto-generated method stub Location lastLocation = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if(lastLocation == null){ lastLocation = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } if(lastLocation != null){ GeoPoint gp = new GeoPoint((int)(lastLocation.getLatitude() * 1e6), (int)(lastLocation.getLongitude() * 1e6)); last_loc=gp; return gp; }else { return _mapView.getMapCenter(); } For the button I called getKnownLocation() A: Of cause it shows your last know location, thats what your code does. You need to give the LocationManager some time to find your current location, you can't expect it to know it without calculating it. What you can do is: * *Make a AsyncTask. *In preExecute creates a dialog or does something that shows the user that you are looking for the current location. *In backgroundProccess gets a new location. *In postExecute inform the user with the new(current) location. *When you press your button run the AsyncTask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: InfoPath non-editable fields I've created a simple list in SharePoint 2010. It has a couple of text columns and a couple of integer columns. * *I click "Customize Form" from the Sharepoint Ribbon *InfoPath 2010 is launched *I make the form look nice and ensure fields are bound to correct columns *I upload the form back to Sharepoint When I click to "Add new item" my InfoPath form is displayed. However only one of the field is editable. I can click into the other fields but when I hit the keyboard - nothing! Any ideas? Thanks Rob. . A: The fields in question might have been set to Read-only. Double-check using the following steps: * *Use "Customize Form" again from the Sharepoint Ribbon *Right click each Control in question *Click Properties *Click the Display Tab *Ensure that the Read-only checkbox is unticked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how can i dynamically add elements to my form using javascript or jquery? I have a student profile form, where student fills information about their education. My code is <script language="JavaScript"> var imCount = 0; function addRow(r, tdCount) { alert(tdCount); alert(r.innerHTML); var root = r.parentNode.parentNode.parentNode; //the root var allRows = root.getElementsByTagName('tr'); //the rows' collection var cRow = root.insertRow(7); var cRow = allRows[tdCount + imCount].cloneNode(true)//the clone of the 1strow cRow.setAttribute('name', cRow.getAttribute('name') + '_' + (allRows.length + 1 + imCount)); //change the selecet's name var cLbl = cRow.getElementsByTagName('label')[0]; cLbl.setAttribute("style", "visibility: collapse"); var cInp = cRow.getElementsByTagName('input'); //the inputs' collection of the 1st row for (var i = 0; i < cInp.length; i++) {//changes the inputs' names (indexes the names) cInp[i].setAttribute('name', cInp[0].getAttribute('name') + '_' + (allRows.length + 1 + imCount)) } var cSel = cRow.getElementsByTagName('select')[0]; cSel.setAttribute('name', cSel.getAttribute('name') + '_' + (allRows.length + 1 + imCount)); //change the selecet's name //root.appendChild(cRow);//appends the cloned row as a new row allRows[tdCount + imCount].parentNode.insertBefore(cRow, allRows[tdCount + imCount].nextSibling) imCount++; alert(imCount); } </script> <form method="post" action=""> <table width="100%"> <tr> <td> <div id="Education"> <table class="Studentprofile" id="tblEducation"> <tr> <td colspan="2"><br/> Education Details</td> </tr> <tr id="schoolRow" name="schoolRow"> <td class="studentprofileupdateHead" > <label for="schools">Schools:</label> </td> <td class="studentprofileupdateBody" id="schools"> <input type="text" id="s1" name="s1" title="S1"></input> <select name="selSYear"> <option value="0">-Select-</option> <option value="1">2010</option> <option value="2">2009</option> <option value="3">2008</option> <option value="4">2007</option> <option value="5">2006</option> <option value="6">2005</option> <option value="7">2004</option> <option value="8">2001</option> <option value="8">2000</option> <//select> </td> </tr> <tr> <td class="studentprofileupdateHead" > </td> <td class="studentprofileupdateBody"> <a href="#" onClick="javascript: addRow(this,1);">Add Shools</a> </td> </tr> <tr> <td colspan="2"><br/><hr class="profileUpdate"/><br/></td> </tr> <tr id="highschoolRow" name="highschoolRow"> <td class="studentprofileupdateHead" > <label for="highschool">High School:</label> </td> <td class="studentprofileupdateBody" id="highschool"> <input type="text" id="hs1" name="hs11" title="HS1" /> <select name="selHSYear"> <option value="0">-Select-</option> <option value="1">2010</option> <option value="2">2009</option> <option value="3">2008</option> <option value="4">2007</option> <option value="5">2006</option> <option value="6">2005</option> <option value="7">2004</option> <option value="8">2001</option> <option value="8">2000</option> <//select>> <br><br/> <hr class="profileSubSection"/> </td> </tr> <tr> <td class="studentprofileupdateHead" > </td> <td class="studentprofileupdateBody"> <a href="#" onClick="javascript: addRow(this,4);">Add High Schools</a> </td> </tr> <tr> <td colspan="2"><br/><hr class="profileUpdate"/><br/></td> </tr> <tr id="collegeRow" name="collegeRow"> <td class="studentprofileupdateHead" > <label for="college">College:</label> </td> <td class="studentprofileupdateBody" id="college"> <input type="text" id="co1" name="co1" title="CO1"/> <select name="selColYear"> <option value="0">-Select-</option> <option value="1">2010</option> <option value="2">2009</option> <option value="3">2008</option> <option value="4">2007</option> <option value="5">2006</option> <option value="6">2005</option> <option value="7">2004</option> <option value="8">2001</option> <option value="8">2000</option> <//select> <br><br/> <hr class="profileSubSection"/> </td> </tr> <tr> <td class="studentprofileupdateHead" > </td> <td class="studentprofileupdateBody"> <a href="#" onClick="javascript: addRow(this,8);">Add College</a> </td> </tr> <tr> <td colspan="2"><br/><hr class="profileUpdate"/><br/></td> </tr> <tr> <td class="studentprofileupdateHead" > </td> <td class="studentprofileupdateBody"> <input type="submit" id="saveStudentEducationInfo" name="saveStudentEducationInfo" title="Save Education Info" value="Save Details" /> <input type="submit" id="cancelStudentEducationInfo" name="cancelStudentEducationInfo" title="Cancel Education Info" value="Cancel" /> </td> </tr> <tr> <td colspan="2"><br/><br/></td> </tr> </table> </div> </td> </tr> </table> </form> When user click on Add School link it will call addRow() and passing two parameters addRow(r, tdCount). <a href="#" onClick="javascript: addRow(this,1);">Add Schools</a> i am passing 1 to add new elements to row 1 it works perfect i can add multiple new element but now looking to another section, <a href="#" onClick="javascript: addRow(this,4);">Add High Schools</a> here i am passing 4 to add new elements to my form,it works perfect without adding ADD SCHOOLS. but when i add schools 2-3 times it will not add high school. Like this in above image you can find that i have added 3 new schools and now i want to add high school but it cant be added to the form. How can i solve this issue? Any way to find tr instead of hard coding values in addRow(this,4)? A: I'd change your code like this (removing the onclick ) $('.studentprofileupdateBody a').click(function(){ console.log('ok'); var $tr = $(this).closest('tr').prev() var clone = $tr.clone(); $tr.after(clone); }); fiddle here: http://jsfiddle.net/mSRg3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7579847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Control size of Facebook auth dialog I'm using Facebook C# SDK for my WP7 app. The authentication dialog that prompts the user to grant permission to the app is displayed full screen on the app (about 480px I guess), but the allow/don't allow button are hidden at the bottom of the frame, which needs to scroll. There is a large part of the screen that is white though, so I think Facebook is serving a dialog for a larger screen. How can I specify the size of the screen when authenticating over Facebook oauth ? A: This is a bug with Facebook. I would suggest opening a bug with Facebook at https://developers.facebook.com/bugs. The one thing you might do to work around the issue is to inject either javascript or css into the page using the browser control. Your javascript/css could fix this issues and resize the page. I have done that before on an old WPF app and it worked well. Unfortunately, the Facebook support for Windows Phone is very poor and there are several major issues of this type.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OutOfMemoryException, Dump file size, and GC Heap Size A 32bit .net application, running on a 32 bit machine, ran into an OutOfMemoryException. I then took a full memory dump, and although using WinDbg I can verify that a lot of memory is being used, I wonder why we get OOMEs, although the GC Heap Size, according to WinDbg's output to "!eeheap -gc", is only around 1GB, so it looks like there's quite some space left up to the 1.5GB of .net. Here's are parts of the output: 0:000> !eeheap -gc Number of GC Heaps: 1 generation 0 starts at 0x6a12ffcc generation 1 starts at 0x6a12ffc0 generation 2 starts at 0x016a1000 ephemeral segment allocation context: (0x6a12ffd8, 0x6a12ffe4) segment begin allocated size 016a0000 016a1000 0269ff64 0x00ffef64(16772964) ... 69130000 69131000 6a12ffd8 0x00ffefd8(16773080) Large object heap starts at 0x026a1000 segment begin allocated size 026a0000 026a1000 03698a98 0x00ff7a98(16743064) ... 70020000 70021000 70a7d750 0x00a5c750(10864464) Total Size 0x3c67abb4(1013427124) ------------------------------ GC Heap Size 0x3c67abb4(1013427124) Is this to be expected? Where would the remaining ~500MBs be? Some more details: * *The dump file itself has a size of 2.007.000.476 Bytes. *The machine the software was run on had only 1GB of physical RAM, but virtual memory of that machine was setup to grow to up to 3GB (so that the app should be able to grow up to the 1.5GB maximum of 32bit .net applications). A: Most likely the process isn't 3GB aware. It is a per process setting. Also if you want to see total memory usage, you can use !heap -s. This will give you a summary of what each heap is doing and the amount of memory it used. This will show you fragmentation issues as well. Combine this with the managed heap, and it should give you an idea of total memory usage. A: A dump size of nearly 2 Gb indicates that the user address space of the process is full. Memory is filled not only by .Net memory allocations, but also native (C/C++) allocations, jitted code, binaries, stacks, ... With Windbg, check the virtual space usage with !address -summary. To get a global view, you can also use DebugDiag to analyze the dump.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I disable and enable macros on the fly? I would like to test an Excel VBA app I made. However the VBA code messes around with the visibility of cells and that's a pest when editing the sheet. Is there an option is enable and disable macro's on the fly without having to Close the sheet Change the macro settings Reopen the sheet Close the sheet Change the macro settings. etc. A: To disable macros on the fly, use "Application.EnableEvents = False" via the Immediate window in the VBA editor (and "Application.EnableEvents = True" to turn them back on). A: You can also hold down SHIFT when you open a document to disable macros. A: As of Excel 2010* there's actually an option on the "Developer" tab which allows you to disable macros as easy as ABC. Design Mode lets you do just that! *Maybe even earlier versions. A: As far as I know, you can't enable / disable macros from an opened workbook on the fly. Yet, you shouldn't have to because macros are only triggered thanks to a user click. The only case I would see is for the Event Procedures (Worksheet_Change or else). You could then create procedures to activate / deactivate events and call them from buttons in your worksbook: Sub enableEvents() Application.EnableEvents = True End Sub Sub disableEvents() Application.EnableEvents = False End Sub You can also try these tips from Chris Pearson website using global vars you would change depending on your needs: Public AbortChangeEvent As Boolean And check if afterwards: Private Sub Worksheet_Change(ByVal Target As Range) If AbortChangeEvent = True Then Exit Sub End If ' ' rest of code here ' End Sub A: I often fire Macros when opening a workbook but sometimes I don't want the Macro to fire so I can work on the code. So what I put a Macro in a separate workbook that does the following: * *Disables macros *Opens the workbook in question *Enables macros *Then closes the original workbook *Leaves the second workbook open Here's the code: Sub OpenClose() 'Opens Workbook below with Macors disabled 'After it is open Macros are enabled 'This Workbook then closes without saving changes, leaving only the workbook below open '************************************************************ 'User only needs to change the workbook name on the next line WorkbookToOpenNoMacros = "Gaby.xlsm" '************************************************************ Dim wb As Workbook Set wb = Application.ThisWorkbook Application.EnableEvents = False Application.Workbooks.Open (ActiveWorkbook.Path & "\" & WorkbookToOpenNoMacros) Application.EnableEvents = True wb.Saved = True wb.Close SaveChanges:=False End Sub A: I have Office 2013 and I found a button on the VBA window that did this for me very easily. There's a play, pause and stop button on the toolbar. In Excel, they are actually called, Run Macro, Break and Reset. Click the Break button (pause) and any running macros should stop running. I only tested it on one macro but seems reasonable to presume that this will work in general. Also, I believe those buttons were there for many versions of Excel, so it's worth checking earlier versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to go from last row to first row direstly in uitableview? iam making one application.In that iam using UITableview.In that i places one button at the last row of the tableview.How we go to first row when we click on that button.So please tell me how to solve this one. A: Use this: NSIndexPath *topIndexPath; topIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [tableView scrollToRowAtIndexPath:topIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
{ "language": "en", "url": "https://stackoverflow.com/questions/7579868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting the second element in tuples I have a list of tuples that look like this. [ [(1,True),(2,True)] , [(3,False),(4,False),(5,False)] ] My goal is so get [1,2,3,4,5] of out that mess. I tried to use map and filter to remove all the Bools but filter also removed the first element in the tuple. If I can remove the Bools in each tuple then I can maybe use a loop to assign fst of each tuple to a new empty list? A: f :: [[(a, b)]] -> [a] f = concatMap (map fst) Then f [ [(1,True),(2,True)] , [(3,False),(4,False),(5,False)] ] is [1,2,3,4,5]. A: Or with list comprehensions: f xss = [fst x | xs <- xss, x <- xs] A: Try this (edited, thanks to Michael Kohl's and pat's comments): fun :: [[(a,b)]] -> [a] fun = map fst . concat Then in GHC: *Main> let l = [ [(1,True),(2,True)] , [(3,False),(4,False),(5,False)] ] [[(1,True),(2,True)],[(3,False),(4,False),(5,False)]] *Main> fun l [1,2,3,4,5] A: foldl1 (\acc x -> acc ++ x) [a | b <- lst, let a = map fst b]
{ "language": "en", "url": "https://stackoverflow.com/questions/7579869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Umbraco contour on azure fails when form is submitted I have installed my Umbraco site on Azure and this is working beautifully. I installed Contour on my Umbrcaco system which I did manually in order to successfully install the database. The whole form admin seems fine and the form I have created displays fine until I submit it, I get the following error: Tables without a clustered index are not supported in this version of SQL Server. Please create a clustered index and try again. I have searched high and low and can't find a solution to this problem. Can anyone help? A: Unfortunately... this is, indeed, a limitation of SQL-Azure. You'll need to do what it says and create a clustered index on each table. Details are here: http://msdn.microsoft.com/en-us/library/windowsazure/ee336245.aspx#cir
{ "language": "en", "url": "https://stackoverflow.com/questions/7579879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event: 'prePersist' I created an EJB Session facade in my Netbeans 7 for saving my entity. I have a manytoone mapping between my Insurance and RatePlan Class. public class Insurance{ @ManyToOne(optional=false) @JoinColumn(name="PLAN_ID") private RatePlan plan; } public class RatePlan{ @OneToMany(mappedBy="plan") private Set<Insurance> insuranceItems; } When I tried saving in my database using my EJB Session Bean, I am encountering below error. Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details. What I did was to turn off my Bean validation in my Persistence.xml file. I would like to know what Bean validation error has occurred but I dont know how or where to find it or how to configure and catch it. My EJB facade is a simple class like tis. public class InsuranceFacade{ public void saveInsurance(Insurance insurance){ em.persist(insurance); } } Any hints? A: I got the same problem, but after hours looking for the answer, Finally I Found it.... You should edit your AbstractFacade.java class and add this code public void create(T entity) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity); if(constraintViolations.size() > 0){ Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator(); while(iterator.hasNext()){ ConstraintViolation<T> cv = iterator.next(); System.err.println(cv.getRootBeanClass().getName()+"."+cv.getPropertyPath() + " " +cv.getMessage()); JsfUtil.addErrorMessage(cv.getRootBeanClass().getSimpleName()+"."+cv.getPropertyPath() + " " +cv.getMessage()); } }else{ getEntityManager().persist(entity); } } Now this method will alert you which property and why it fails the validation. I hope this works for you, as it does for me. A: catch (EJBException e) { @SuppressWarnings("ThrowableResultIgnored") Exception cause = e.getCausedByException(); if (cause instanceof ConstraintViolationException) { @SuppressWarnings("ThrowableResultIgnored") ConstraintViolationException cve = (ConstraintViolationException) e.getCausedByException(); for (Iterator<ConstraintViolation<?>> it = cve.getConstraintViolations().iterator(); it.hasNext();) { ConstraintViolation<? extends Object> v = it.next(); System.err.println(v); System.err.println("==>>"+v.getMessage()); } } Assert.fail("ejb exception"); } A: I would like to know what Bean validation error has occurred but I dont know how or where to find it or how to configure and catch it. To know what specific constraint violations have occurred, you could just inspect the exception caught. ConstraintViolationException.getConstraintViolations() returns a Set of ConstraintViolations which you can iterate and inspect. A: Catch the following exception where you persisting the entity. In my case its in the EJB add method. where I am doing em.persist(). Then check the server log, you will see which attribute having constrain violation. catch (ConstraintViolationException e) { log.log(Level.SEVERE,"Exception: "); e.getConstraintViolations().forEach(err->log.log(Level.SEVERE,err.toString())); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Static Alternative in PHP for Parse error: syntax error, unexpected T_STATIC in I was testing my PHP application on localhost with Xamppp and everything was just fine, but when I exported it to a real server, it does not work anymore. I found out that it is because my server does not support late static binding. My server has version 5.2.17. I get this error. <b>Parse error</b>: syntax error, unexpected T_STATIC in <b>/home/storage/f/9d/09/meuplacar/public_html/filme/work/class_lib.php</b> on line <b>555</b><br /> I just use the static keyword in a Util class I built. What would you suggest for me to change this kind of methods: Util class Util { private static $initialized = false; private static function initialize() { if (self::$initialized) return; self::$initialized = true; } public static function getHoursAndMinutesFromTime($time) { self::initialize(); $pieces = explode (":", $time); $output = ""; $output = $pieces[0] . ":" . $pieces[1]; return $output; } } And for a Unique Facade Instance Singleton abstract class Singleton { protected static $_instance = NULL; /** * Prevent direct object creation */ final private function __construct() { } /** * Prevent object cloning */ final private function __clone() { } /** * Returns new or existing Singleton instance * @return Singleton */ final public static function getInstance(){ if(null !== static::$_instance){ return static::$_instance; } static::$_instance = new static(); return static::$_instance; } } class Facade extends Singleton { public function retrieveAllWorkdays() { $array = DB::selectAllWorkdays(); return Util::constructWorkdaysArray($array); } A: Late static bindings only are available in php 5.3.0 and later: http://php.net/manual/en/language.oop5.late-static-bindings.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7579887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check the content in ajax call Is it possbile to check whether the content is loaded fully in the ajax call made and after that show some div. Till the content is not loaded fully the div should not shown and after the content is come then the div has to be shown using jquery? A: the answer is based on total assumptions, also define an error callback $.ajax({ url: "/path/to/server", type: 'POST', data: data, success: function(data){ <-- the success is called upon successful completion //do something with data $("#divID").html(data); $("#divID").show(); <-- assumed the div was hidden initially }, error:function(jxhr){ if(typeof(console)!='undefined'){ console.log(jxhr.status+"--"+jxhr.responseText); } } }); A: Use jQuery ajax call success callback. It will fires only after finishing the request: $.ajax({ type: "GET", url: "some.html", success: function(data){ // show my div here $('#mydivid').html(data).show(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7579889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }