text
stringlengths
8
267k
meta
dict
Q: Why does my function get called twice in jQuery? I have the following jQuery $('img[title*=\"Show\"]').click(function() { //$e.preventDefault(); var position = $('img[title*=\"Show\"]').parent().position(); $('#popover').css('top', position.top + $('img[title*=\"Show\"]').parent().height() + 150); console.log(position); $('#popover').fadeToggle('fast'); if ($('img[title*=\"Show\"]').hasClass('active')) { $(this).removeClass('active'); } else { $('img[title*=\"Show\"]').addClass('active'); } }); I have two images with the title "Show Options." For some reason whenever I click on any of these images, it gets printed TWICE. When I only have 1 image, it only gets printed once. Why is this? A: instead of $('img[title*=\"Show\"]') inside click function use $(this) if doesn't works use: $('img[title*=\"Show\"]').click(function(e) { e.stopImmediatePropagation(); //other code }); A: Use the following code $('img[title*="Show"]').click(function (evt) { $('#popover').hide(); $('img[title*="Show"]').removeClass("active"); $(this).addClass("active"); var p = $(this).parent(); $('#popover').css('top', p.position().top + p.height() + 150).fadeToggle('fast'); }); A: You can use event.stopPropogation so that event is not bubbled further. Maybe your function is being triggered from two different events and other one also get triggered while bubbling.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use Visual Studio 2010 with the Visual C++ 2008 compiler? I want to use Visual Studio 2010 with the 9.0 compiler, how can I do this? I need this so I can use DarkGDK, however I do not want to switch the IDE. A: It's right there in your project properties, "Platform Toolset" defaults to "v100". Just change that to "v90" and you are done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: int(int(-2)/unsigned(2)) = 2147483647 no warning I have a code similar to this: template<typename Ta, typename Tb> Ta doStuff(Ta a, Tb b) { ... return a/b; } As the title says such code would return wrong values with Ta=int Tb=unsigned. Is there a way to get a warning by g++ for this case ? A: Yes. Use -Wsign-conversion option: [nawaz@./]$ g++ filename.cpp -Wsign-conversion A: Try with: g++ -Wall code.cpp -o output
{ "language": "en", "url": "https://stackoverflow.com/questions/7621622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting file from static method error: Access to the path ... is denied My host swears the ASPNet account has full access to the folder some photos reside in. I'm trying to delete a photo, here's the C#: public static bool Delete(string pathAndFilename) { var path = HttpContext.Current.Server.MapPath(pathAndFilename); File.Delete(path); } (in the full code, there's a try catch in there, and bool return values) Update: this is happening on local development box too now. Here's what I have been able to try. I put the current user into the ViewBag, and show it on the page. ViewBag.Account = HttpContext.User.Identity.Name; On the dev box, it shows my currently logged in user account, which has full control of every file and folder in the project. I checked open files, the photo I'm trying to delete wasn't open. Will try to capture more detailed exceptions. Thanks for the ideas so far! A: IUSR? That should be the NETWORK SERVICE or the ASPNET account (depending on the version of IIS) edit: also there is no reason to give IUSR full access. It only needs read access. A: If you use a fully-qualified path ("C:\foo") or if the string isn't recognizable as a path, it'll throw an HttpException. It would be helpful if you described exactly what you're seeing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement jquery ajax call client->server method in mvc3? Q1: Can somebody provide code example for jquery ajax to server method call in mvc3? Q1a: Does the server return have to be a Json result returned from server side? What are my options with the returned data from the server side method (json, just return a string, etc,)? -- Something like this... -- script called from razor view: $("#textbox1).change(function() { $.ajax( {url: '/controller/action', data: { val1: $("#textbox1").val(), val12: ("#textbox2").val()}, success: function(data){ $("#SumResult").val(data); }}) }); -- Server method within same controller: public ActionResult <or> String (int val1, int val2) { return (i != null && j != null) ? (i + j).ToString() : ""; } A: Below article should give you an idea : http://tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views Q1a: Does the server return have to be a Json result returned from server side? No, you can pretty much return anything from server (in ASP.NET MVC world, from controller method). If you return JSON, it is pretty much convenient for you to work with it inside your JavaScript code. What are my options with the returned data from the server side method (json, just return a string, etc,)? Some of them are : * *XML *JSON *Html Assuming that your controller supposed to return ActionResult, some of that you can return are as follows : * *Content *Json
{ "language": "en", "url": "https://stackoverflow.com/questions/7621624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multi-server file storage and sharing causes website to hang - other websites on same server remain accessible I'm trying to make a system where files are stored on Main Servers, and if a user chooses, these files can be copied over to Backup Servers to prevent data loss at a HDD crash but it's not going as planned. When files are copied from their Main Server to a Backup Server the entire website hangs. No one can visit the website anymore until all transfers are complete. What's weird is that other websites, running on the same lighttpd server, remain accessible and even phpmyadmin keeps on trucking. STEP 1: -First, a "job" gets created in mysql table "redundfilesjobs" for a file that needs more backup servers than it currently has. -Then, an available backup server gets assigned to said job STEP 2: -After a user approves all the jobs that have a server assigned at once, each job gets copied to "redundfiles" with the field "processed" set to 0 after which the "sendfilestoservers" function is immediatly called -The sendfilestoservers function is built so it can accept both a pre-defined job for sending, as well as send all files with the field "processed" set to 0 -In this case, it gets called with a pre-defined job ID that needs to be processed sendfilestoservers($lastid); The function: <?php function sendfilestoservers($specificjob){ if($specificjob != ''){ $result = mysql_query("SELECT * FROM redundfiles WHERE processed=0 and id=$specificjob"); } else{ $result = mysql_query("SELECT * FROM redundfiles WHERE processed=0"); } while($row = mysql_fetch_array($result)) { $fileid=$row['fileID']; $result2 = mysql_query("SELECT files.name, files.subfolder, mainservers.path, mainservers.ftpaddress FROM files LEFT JOIN mainservers ON files.serverID = mainservers.id WHERE files.id=$fileid"); while($row2 = mysql_fetch_array($result2)) { $serverid = $row['serverID']; $result3 = mysql_query("SELECT * FROM redundservers WHERE id=$serverid"); while($row3 = mysql_fetch_array($result3)) { file_get_contents($row3['sendfileaddress'].'?f='.$row2['name']."&fo=$row2[subfolder]&ftpaddress=$row2[ftpaddress]&mspath=$row2[path]"); $sql = "UPDATE redundfiles SET processed=1 WHERE id='".$row['id']."'"; mysql_query($sql) or die(mysql_error()); } } } } ?> //As you can see it calls the assigned backup servers' address (example: http://user:[email protected]/get.php ) for receiving files, and sends with it directives: file name, the folder it's in on the main server, the ftp address for the main server, and also the path on the main server where all files are stored (inside their respective subfolders) //The backup server is now going to processed all those GET values, and ends up retrieving the file from the main server over FTP using linux' wget Config on backup server X <?php $filename = $_GET['f']; //Filename $subfolder = $_GET['fo']; //Folder file is stored in $mainserverID = $_GET['ms']; //Main server the file resides on $mainserverpath = $_GET['mspath']; //Path on the main server where all the files are stored $mainserverftpaddress = $_GET['ftpaddress']; //Main server's FTP address or IP, as it may differ from the web address. $dlto = "/var/www/serverX.XXX.XXX/"; //This backup server's main path. This needs to be changed on every backup server. $dltodir = "files"; //Folder files are stored in (follows $dlto) $serverID = $_GET['s']; //Backup-servers ID as it's stored in the main servers database, some other scripts use this. function execOutput($command) { $output = array($command); exec($command.' 2>&1', $output); return implode("\n", $output); } ?> "get.php" script on backup server X <?php include("config.php"); if (file_exists($dltodir.'/'.$subfolder.'/'.$filename)) { } else { exec('mkdir '.$dlto.$dltodir.'/'.$subfolder); exec('chmod 777 '.$dlto.$dltodir.'/'.$subfolder); exec('wget ftp://user:pass@'.$mainserverftpaddress.'/'.$mainserverpath.'/'.$subfolder.'/'.$filename.' -P '.$dlto.$dltodir.'/'.$subfolder); } ?> //And then we go back to Step 2 for the next approved file. The first steps (creating the job in "redundfilesjobs" and copying the job to "redundfiles") go fast and I don't notice them causing hang ups. But for some reason the actual sending (or rather, having the backup server retrieve it) just makes the website freeze up. I hope I provided all the info required for everyone to understand how the system is supposed to work. Can anyone tell me why the entire website hangs and becomes unaccessible for everyone until all files are copied? A: I think I may have traced the problem back to my php-fpm configuration. Although I'm still not 100% sure, it seems to be working now. Worth a try if someone experiences similar problems; I had: pm = dynamic pm.max_children = 2 pm.start_servers = 1 pm.min_spare_servers = 1 pm.max_spare_servers = 1 I changed to; pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 The previous config had problems with file_get_contents() for some weird reason.. I used the following script to test it; <?php //phpinfo(); if(isset($_GET["loop"])) $loop = $_GET["loop"]; if(isset($_GET["show"])) $show = true; if(isset($_GET["s"])) { if($_GET["s"] == "ser") $address = "http://www.this-server.com/some_file.php"; elseif($_GET["s"] == "com") $address = "http://www.external-server.com/some_file.php"; }else die("s not set"); if(!isset($loop)||!is_numeric($loop)) echo file_get_contents($address); else { $count = 1; $success = 0; while(($count-1) < $loop) { $got = file_get_contents($address); if(!is_bool($got) && $got !== false) { if(isset($show)) echo $count." : ".$got."<br/>"; $success++; } $count++; } echo "We had $success successful file_get_contents.<br/>"; } ?> If I went to script.php?s=serv and spammed F5 loads of times, the php-fpm process belonging to the current website would hang. script.php?s=com worked fine, however. What also worked fine, is going on the second server and doing it the other way around. What also worked fine is running the loop (script.php?s=ser&loop=50&show) rather than spamming F5. That's what I find especially odd. Seems liek it's not the number of requests it has problems with. And also not the file_get_contents() itself (because it works as long as the file requested is not on the same server, even when spamming F5). Conclusion; With the old config, spamming F5 on a script containing file_get_contents() with a call to a file on the same server, causes the php-fpm process to hang. I'm kinda baffled by this...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does the 'hash' method do in Objective-C Occasionally, when I am looking down the list of selectors that a object responds to, I see hash come up. For a while now, I have wondered what it meant, but I never came around to finding out. I would really appreciate it if you could tell me what the selector does and common uses for doing so. A: It computes a hash of the object, which is especially useful in HashTables like when the object is used as a key for an NSDictionary. An object hash has to have the following properties: * *Two objects of the same class that are to be considered equal should return the same hash *Two objects with a diffent hash will never be considered as equal *Two objects with the same hash are not necessary equal to each other; anyway, the more unique the hash is, the better the performance for NSDictionary lookup will be. *If should also be computable as fast as possible to avoid performance issues in dictionaries For more info, read the NSObject Protocol documentation where this hash method is defined. For example the hash function for a string could be the number of characters of this string, or the sum of the ascii codes of its character, or anything similar. When you search for a given key in an NSDictionary, one solution would be to compare the searched key with all other keys in the dictionary, which would need to loop thru all the keys and call isEqual on each key, and that will take a long time if the dictionary have a lot of entries. So instead, Cocoa will compute the hash of the searched key, and compare it with all the (pre-computed) hashes of the keys in the dictionary. This is much more efficient because it will only need to make comparisons between NSUInteger values, even if the keys of the NSDictionary are NSStrings or other objects, so this is really faster. Once it has found the keys that have the same hash as the hash of the searched key, it can then loop thru all the keys with this hash and compare them with the searched key by calling isEqual, but at this stage there will be much less keys to loop thru (and even possibly only one if the hash of the key is really unique) A: It's used for implementing efficient hash tables in associative array data types such as NSDictionary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Advice on Rails and CI, how often does this run exactly? or what is common practice First off, is autotest and cruisecontrol performing the same sort of CI tasks? I want to setup something that will run my unit tests, and also integration tests on my local MBP computer i.e. I don't have a seperate computer for this yet. Is autotest something that runs everytime you change a file while cruisecontrol something that runs at a more periodic basis like once every checkin or something? Does it put a big strain on the computer? A: Autotest and cruisecontrol are 2 different tools in may opinion. Autotest help you running the necessary tests each time you change something in your application. That works nicely in your local environment, so you get feedback automatically without having to remember to run the tests are having changed source code (or test code). Cruicecontrol is (similar to Hudson / Jenkins / Bamboo / TeamCity / ...) a Continuous Integration Server, which runs defined build jobs when you define it. The following are reasonable alternatives: * *Run on each checkin / commit == therefore continuous *Run an hourly build, to get regular feedback. *Run a (big) nightly build that does a lot of checking, quality assurance, ... It normally gets all its contents (sources, build scripts, configuration, ...) from a source control system like Subversion, Git, ... It is normally used in a smaller or larger team to help integrate the work of different people. So if you work only on your machine, and do mostly unit tests, autotest should be sufficient. Else you should take in consideration using a CI server (locally), which has of course more overhead, needs more resources. I do not know what the overhead of cruise control is, but running Hudson locally is a bigger Java program with 500 MB to 1 GB memory hunger. Autotest has nearly no overhead, it just automates what you would elsewhere do manually. I don't think you want to run your integration tests automatically on each change, perhaps a set of Rake tasks integrated in the CI Server and started manually will do the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Software protection / code obfuscation that does not trigger antivirus false positives I'm looking for software protection and/or code obfuscation software like Oreans Themida, VSProtect, ASPRotect and similar. However, antivirus false positives is a deal-breaker for me. I cannot inconvenience or scare away our legitimate users. And unfortunately it seems all of the three products mentioned above suffer from this problem. My 32-bit native (not .NET) Windows application written in Delphi right now uses custom license managing code, and it works well, however since no code obfuscation is used, cracks are created within hours after each release. So, I'm looking for a product that adds at least some level of protection against crackers and does not create false-positives with antiviruses. My top priority is non-evasiveness and stability, lack of bugs and antivirus false alarm issues introduced into my software. Level of anti-cracking protection is secondary to that. A: You'll have to roll your own. The false-positives come from "signatures" matching known malware. For example, if some malware uses upx to compress, and a scanner finds upx compiled into your app, you may be mis-identified. You could get a false-positive just because a scanner saw that you are using Delphi (or any other compiler, for that matter). But the more obscure, the higher confidence that the scanner thinks: "I've found something UNIQUE in here", and cross-references with its catalog of known malware. ] If airport security worked like the anti-malware companies, I'd be shot on sight in the airport because I'm a male with brown hair, brown eyes. If the scanner is lazy enough, you can be flagged for the installer that you use, 3rd-party components that you use, resource strings, "random chance", something to do with the code signing certificate, or the compiler that you use. Someone will make malware with FireMonkey. Some anti-malware (perhaps more than one) will take note of this. For some period of time, it will be trouble for FireMonkey apps. Here is an interesting discussion: Accidentally created a virus? A: Arxan guardIt is meant to work with visual C++ applications, but an enterprising Delphi developer might be able to use it to guard their products. I know of one very popular commercial application written in Delphi that uses it, but you have to write some tools yourself to convert the Delphi map files and other debug info, into the Visual C++ formats. If you wish to roll your own, be aware that the task is to be smarter than the hackers, and to build more layers of counter-protections that rely upon each other in some difficult to determine manner, in order to resist crackers successfully. My personal feeling is that you won't get those people to give you money anyways, so spending your time to keep them from using your software is merely cutting off your nose to spite your face. But if it's your hard work up there on the internet in cracked form, then by all means, keep trying to outdo them. Note that if you get into advanced techniques, like self-modifying code, you will almost certainly get flagged by some anti-malware detection software, and will need to request to be white-listed. If you are not prepared to go as far as self-modifying code, then there may be zero point in even trying. I am unaware of anything that resists straight offline decompiling techniques that does not require self-modifying, just-in-time-repair-and-damage techniques. Plain old exe decryption techniques that are done once at startup are also extremely easy to bypass and remove completely, once the unencrypted exe is fully loaded in memory. A: I believe you could take a look at one called The Enigma Protector The developer is very aware of issues with False Positives and actively engages with AV companies on this issue. Here is what the developer has said about this in one of his forum posts "Starting with Enigma Protector 3.0 no false detections will be appeared with protected files!" Link to forum post I have been using this protection since I switched from Ice License a few years ago and have only ever had one problem with a false positive detection. I informed the developer and he contacted Avast right away for me. It was resolved on the very next AV detections update. The protection has alot of features and a very helpful help file. It uses a marker system for virtualization and when the code in these markers is run it will use a special language known only to the protection system called PCODE on an internal virtual processor. It has it's own API's and plugins can be written for it. It also includes a Virtual Box for files and the registry, but now I could go on forever. Chris A: I think you should look at this differently. We use Oreans and had similar issues but skirted around them by signing the executables. The antivirus software take a little longer to look at your application but most will still accept it as virus free if it is digitally signed. The reason that I am saying this is that protection systems change as do antivirus systems. You could find a system today that successfully passes the antivirus test and tomorrow, when someone releases some spyware encrypted by the same product yours will be marked as a virus. Update - There are a couple of isolated ones that still complain but the majority accept the signed one as valid (we get 6 out of 43 flags whereas without signing we had more than half complain) A: Yes, there are solutions available. (Disclaimer: I work for a software copy-protection company Wibu-Systems) and I can assure you that CodeMeter doesn't trigger anti-virus systems, nor does it require admin privileges to install. I can also tell you that any home-grown solution will probably be cracked pretty quickly--we have spent years (and so have the other vendors in this space like Arxan, Safe-Net, and Keylok) developing methods to confuse and confound would-be crackers. Most crackers just use a debugger to set a breakpoint at the license-checking routine (error message or dialog that is presented to the user) and then patch around the assembly-language code at the authentication check (look for something like compare EAX to EBX and change the code to always return true). So they don't need to try to de-obfuscate your code etc. That's why most commercially-available solutions use encryption rather than some kind of authentication/validation checking--encryption can't be patched around. But even an encrypted executable can be memory dumped and rebuilt unless you are pretty sophisticated about how your re-arrange the PE file format and handle key storage and key exchange. Given that the cost of a commercial-system with all its strengths and benefits (license management, flexibility, cross-platform support, etc) can be quite low, why roll your own? Most people don't write their own installers, since you can use MSFT or InstallShield or NSIS--why write your own licensing and protection solution? A: I guess you won't get 100% assurance, but I never had problems with Armadillo. Secure your exe and sign it with a valid certificate. A: This is a tough one as always. I would say that you should start looking for a product that is applied at compile time rather than after. Packers that pack binaries will always produce a suspicious result since they act much like a virus would. I believe many of the game protecting schemes like Sonys SecuROM does this, or at least are starting to do so. But one could argue, that while you're safe on the false positives side of things, the crackers already know how to defeat these mainstream products. So you need to find that good up-and-coming ringer product. A: Try using a hex editor to edit out the headers like 'UPX', etc. The binary doesn't need them, just the tool that unpacks them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you add indexes to your Mongoid database in Padrino? I need to be able to add indexes to my Mongoid database in a Padrino project. I saw that they added rake tasks for this here: https://github.com/padrino/padrino-framework/commit/ec8a267f477ac4dc88a66c84fffb17ac26190a22 And it seems that they should be accessed by doing this, but I get an error: $ padrino-gen orm::mongoid --help => Problem loading ./config/boot.rb => Invalid option :index provided to relation :features. Valid options are: as, autosave, dependent, foreign_key, order, class_name, extend, inverse_class_name, inverse_of, name, relation, validate. /Users/jeremysmith/.rvm/gems/ruby-1.9.2-p290/gems/mongoid-2.2.1/lib/mongoid/relations/options.rb:41:in `block in validate!' Any idea of how to run a rake task to add indexes in Padrino? Thanks! A: When you generated your Padrino project, did you select mongoid as the persistence engine? Hint: easy to check by looking at the .components file in your project root. If you did, you should be able to access the rake tasks just using padrino rake <namespace>:<task>. See here: http://www.padrinorb.com/guides/rake-tasks#orm . Running a rake task to create an index should be just: padrino rake mongoid:create_indexes I would check padrino rake -T to see the list of available tasks as well. A: bundle exec padrino rake mi:create_indexes (not mongoid:create_indexes as you will see elsewhere online) This seems to be the new name for this rake task in Padrino 0.10.5 and Mongoid 2.3.4
{ "language": "en", "url": "https://stackoverflow.com/questions/7621641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need suggestion in creating an AlertDialog in Android I have the following code called when a button is pressed in my activity. AlertDialog.Builder alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Alert 1"); alertDialog.setMessage("This is an alert"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); I have added imports these two : import android.app.AlertDialog; import android.app.AlertDialog.Builder; But still get following errors : Description Resource Path Location Type The constructor AlertDialog.Builder(new View.OnClickListener(){}) is undefined MobileTrackerActivity.java /MobileTracker/src/com/example/mobiletracker line 77 Java Problem The method setButton(String, new DialogInterface.OnClickListener(){}) is undefined for the type AlertDialog.Builder MobileTrackerActivity.java /MobileTracker/src/com/example/mobiletracker line 80 Java Problem Type mismatch: cannot convert from AlertDialog to AlertDialog.Builder MobileTrackerActivity.java /MobileTracker/src/com/example/mobiletracker line 77 Java Problem Can anybody give any solution to me please? I am very new to Java. A: Create the AlertDilog this way : AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle("Alert 1"); alertDialog.setMessage("This is an alert"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { return; } }); AlertDialog alert = alertDialog.create(); alert.show(); A: If you look at this page: http://developer.android.com/guide/topics/ui/dialogs.html and the error message you get you just need to make this change: AlertDialog alertDialog = new AlertDialog.Builder(this).create();
{ "language": "en", "url": "https://stackoverflow.com/questions/7621650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load category specific to device I have an iPhone app that I'd like to make universal, most views can be kept the same, but there are some minor modifications that need to be made for the iPad. Is it possible to load a category depending on what device the user is using? Or is there a better way of doing this? A generic way (rather than specifically checking each time I create a new instance of a class, and choosing between 2 classes) A: You could do this with some method swizzling at runtime. As a simple example, if you want to have a device-dependent drawRect: method in your UIView subclass, you could write two methods and decide which to use when the class is initialized: #import <objc/runtime.h> + (void)initialize { Class c = self; SEL originalSelector = @selector(drawRect:); SEL newSelector = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? @selector(drawRect_iPad:) : @selector(drawRect_iPhone:); Method origMethod = class_getInstanceMethod(c, originalSelector); Method newMethod = class_getInstanceMethod(c, newSelector); if (class_addMethod(c, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) { class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); } else { method_exchangeImplementations(origMethod, newMethod); } } - (void)drawRect_iPhone:(CGRect)rect { [[UIColor greenColor] set]; UIRectFill(self.bounds); } - (void)drawRect_iPad:(CGRect)rect { [[UIColor redColor] set]; UIRectFill(self.bounds); } - (void)drawRect:(CGRect)rect { //won't be used } This should result in a red view on the iPad and a green view on the iPhone. A: Look into the UI_USER_INTERFACE_IDIOM() macro, this will allow you to branch your code based on the device type. You may have to create a helper class or abstract superclass which returns the appropriate instance if you want to keep each file iPhone or iPad only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Custom Gallery Widget crashes with java.lang.OutOfMemoryError: bitmap size exceeds VM budget When scrolling back and forth a bunch of times on the image gallery my app crashes with: java.lang.OutOfMemoryError: bitmap size exceeds VM budget I need the gallery to show two images vertically: * *The top one will be a selection from a pre-defined group of images in the res/drawable folder. *The bottom image will be a green check mark if they answered this particular image correct (this is the submit your score page of the game) or a red circle with a line through it if they get it wrong. Here is my code that extends the BaseAdapter: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; public ImageAdapter(Context c) { mContext = c; TypedArray attr = mContext.obtainStyledAttributes(R.styleable.SubmitScoreGallery); mGalleryItemBackground = attr.getResourceId( R.styleable.SubmitScoreGallery_android_galleryItemBackground, 0); attr.recycle(); } @Override public int getCount() { return numQuestions; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //Setup a LinearLayout to display the second image LinearLayout lLayout = new LinearLayout(this.mContext); lLayout.setOrientation(LinearLayout.VERTICAL); //Create the ImageView ImageView imageView = new ImageView(this.mContext); imageView.setImageResource(imageList.get(randOrder.get(position))); imageView.setLayoutParams(new Gallery.LayoutParams(gDispW, gDispH)); imageView.setScaleType(ImageView.ScaleType.FIT_XY); imageView.setBackgroundResource(mGalleryItemBackground); lLayout.addView(imageView); //Create the right/wrong image ImageView imageViewBottom = new ImageView(lLayout.getContext()); if (score.getScoreAtIndex(position)== 1){ imageViewBottom.setImageResource(R.drawable.green_checkmark); } else{ imageViewBottom.setImageResource(R.drawable.incorrect_circle); } imageViewBottom.setLayoutParams(new Gallery.LayoutParams(gDispW, gDispH)); imageViewBottom.setPadding(gDispW/3, 0, gDispW/3, gDispH/2); imageViewBottom.setScaleType(ImageView.ScaleType.CENTER_INSIDE); //imageViewBottom.setScaleType(ImageView.ScaleType.CENTER_INSIDE); lLayout.addView(imageViewBottom); return lLayout; } } randOrder is an array that holds the order of the images The gallery holds 5, 10 or 15 images depending on how many questions the user chooses. I can get it to crash consistently with the 15 images. Is there a better way to do this? What am I doing wrong? Thank you, Neil A: On getView method, you create an ImageView every time. You can use convertView like this: ImageView imageView; // if it's not recycled, initialize some attributes if (convertView == null) { imageView = new ImageView(mContext); } else { imageView = (ImageView) convertView; } Moreover, you can use resampling on your bitmaps. A: Comment 19 of this post: code.google.com Issue 8488 fixed the issue. All I had to do was create the folder res/drawable-nodpi and put the images that I am calling in there. For some reason if you store your images in res/drawable the attr.recycle() doesn't work right. Anyone know why? I also implemented Tim's suggestion and it seems to have sped up the scrolling back and forth in the gallery. Thank you! EDIT: The above answer worked for a myTouch 4g but the program still crashed with a G2. So I took Tim's advice and started to look at re-sampling images. I ended up using Fedor's answer from this post: Strange out of memory issue while loading an image to a Bitmap object and I haven't seen the out of memory issues on the G2 since.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matrix Multiplication in Python Changes the Result Dimension I have 1X2 matrix, Mu_I.transpose(), and a 2x2 matrix, Covariance_I_Inverse. The result of multiplication should be a 1x2 matrix, but my output is a 2x2 matrix. Why? How can I get a 1x2 Matrix? >>> Mu_I.transpose() [[ 10.02010924 9.99184818]] >>> Mu_I.transpose().shape (1, 2) >>> Covariance_I_Inverse [[ 0.72006911 0. ], [ 0. 0.77689697]] >>> Covariance_I_Inverse.shape (2, 2) >>> (Mu_I.transpose()*Covariance_I_Inverse) [[ 7.21517113 0. ], [ 0. 7.76263658]] >>> (Mu_I.transpose()*Covariance_I_Inverse).shape (2, 2) A: I'm guessing those variables are numpy.array, but not numpy.matrix. For numpy.array, * is defined as element-wise multiplication. In that case use numpy.dot(). That will give you matrix multiplication. Or simply use numpy.matrix and * operator will be matrix multiplication.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Element of Matrix is the Memory addres and not the value of element I have a matrix homework. When I run the program, in the console It always returns by the memory address and not by the values. I am European, I used the German locale. I've thought that maybe the localization is the problem, so I've changed to US, but It doesn't solves my problem. In console: [[D@459189e1, [D@55f33675] [[D@527c6768, [D@65690726] Here my code: import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class Inverse2x2Matrix { public static double[][] inverse2x2Matrix(double[][] A) { double det = A[0][0] * A[1][1] - A[0][1] * A[1][0]; double m00 = -1 * A[1][1] / det; double m01 = A[0][1] / det; double m10 = A[1][0] / det; double m11 = -1 * A[0][0] / det; double[][] B = { { m00, m01 }, { m10, m11 } }; return B; } public static void main(String[] args) { Locale.setDefault(Locale.US); System.out.println("Enter a, b, c, d: 0"); Scanner sc = new Scanner(System.in); String input=sc.next(); sc.close(); double[][] A = new double[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { A[i][j] = Double.parseDouble(input); } } System.out.println(Arrays.toString(A)); System.out.println(Arrays.toString(inverse2x2Matrix(A))); } double[][] C = {{1.0,2.0},{3.0,4.0}}; System.out.println(Arrays.toString(C)); System.out.println(Arrays.toString(inverse2x2Matrix(C))); } A: Use Arrays.deepToString to pretty-print the contents of an array recursively. Else, every element of the array is printed using its toString method, which indeed prints its type followed by its hashCode. A: A is array of array, so when you type Arrays.toString(A) it takes every inner array of A and call toString on it, which returns this address-like representation. You need to iterate through A manually: for (double[] ar : A) { System.out.println(Arrays.toString(ar)); } Or write helper method: private static void printArray(double[][] ar) { for (double[] inner : ar) { System.out.println(Arrays.toString(inner)); } } UPDATE JB Nizet's advice is much better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why isn't my div position getting dynamically calculated? I have the jQuery: $('img[title*=\"Show\"]').live('click', function(e) { //$e.preventDefault(); e.stopImmediatePropagation(); var position = $('img[title*=\"Show\"]').parent().position(); $('#popover').css('top', position.top + $('img[title*=\"Show\"]').parent().height()); console.log(position); $('#popover').fadeToggle('fast'); if ($('img[title*=\"Show\"]').hasClass('active')) { $(this).removeClass('active'); } else { $('img[title*=\"Show\"]').addClass('active'); } }); I have two images titled "Show Options." The popover div appears properly when I click on the first image. When I click on the 2nd image, the popover appears underneath the first image. I want it to appear underneath the 2nd image. Why is this? A: try using offset instead of position $(this).parent().offset(); you will also have to use "this" instead of the ID as it will always match the first pic A: I think you need to change the 3rd line to: Var position = $(this).parent().position(); When your event handler is called $(this) will refer to the element that was clicked on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I plug into socket.io's built in logging system to generate my own messages? socket.io seems to have a basically sensible logging system for all its internals. How do I get at that logging object myself so I can generate my own log messages at appropriate levels? It bugs me that my console.log() messages are un-timestamped, un-leveled, and ugly next to the socket.io messages. I've done a bunch of spelunking in the socket.io code and I'm just not savvy enough about node at this point to understand what the object hierarchies look like to know how to get at the object I want from my code. Longer term, I'm probably going to want a more robust logging system module (with the ability to log to files, auto-rotate, manage levels on a per-module basis, custom log levels, etc.). Winston looks sensible, but can I get socket.io to use it, too? It'd be nice to have everything in one place. A: While using socket.io, I was able to plug into the existing logger module like so: var express = require('express'), app = module.exports = express.createServer(), //just creating 'app' for io io = require('socket.io').listen(app), logger = io.log, // access the existing logger setup in socket.io util = require('util'); logger.info(util.format("Express server listening on port %d in %s mode", 8003, app.settings.env)); Configuring the logger is also very simple: io.configure('production', function(){ io.set('log level', 1); } A: Have you looked into using the logger middleware from Connect? It looks like someone already created a library for what you want called socket.IO-connect. I use something similar in my Express program: var connect = require('connect'); module.exports = connect.createServer( connect.logger({ format: ':response-time :method :url' }), connect.static(__dirname + '/public) );
{ "language": "en", "url": "https://stackoverflow.com/questions/7621662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: ode solver event location index in MATLAB Suppose I am trying to solve a system of differential equations using an ode solver in MATLAB. Suppose also that I have defined an events functions to locate three different events which are all terminal. I have noticed that on some occasions the ie quantity that is returned upon the location of one of the events (ie is the index of the event that stopped the solver, in my case it could be 1, 2 or 3) is not always a single number but a vector with two elements (usually these elements are identical) In those cases that ie is NOT scalar, is it ie(1) or ie(2) that stopped the solver? A: Actually, I noticed that this happens when the simulation stops due to a terminal event and then starts again from the same point (initial time and conditions) that stopped. Technically, due to arithmetic inaccuracies in the initial conditions MATLAB re-detects the same event that made it previously stop. MATLAB is incapable of distinguishing this, BUT it is programmed NOT to stop in terminal events that occur just after the first successful step (see odezero function for reference). It does record the event, though. Consequently, the next time that the ode stops due to a terminal event, the ie is appended with the new index and that's when (and why) ie is a vector with two elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: matlab to python: get matlab cell array values I am very new to matlab and python and need to use some values in python from the matlab cell array. I have a cell array of integers that after i execute this line of code and print the result, i get this: a = loadmat('file.mat') print a {'__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Wed Sep 21 15:30:15 2011', 'juncForward_c': array([[ [[ [[ ([[30]], **[[91], [87]]**, [[3]], [[2.2455372690184494, 3.6052402625905993, 5.5884470309828833]], [[14.0, 4.0, 15.4]], [[-1, -1, 2]], [[91, 89, 93], [88, 85, 86]], [[500, 500, 5]], [[1, 2, 3]], [[11.133333333333333]], **[[4]]**, [[1]], [[1]], [[1.0], [20.365168528421695]])]] [[ ([[30]], **[[99], [80]]**, [[3]], [[4.0376480381611373, 2.3561944901923448, 6.0857897473297058]], [[10.0, 15.4, 16.600000000000001]], [[-1, 1, 3]], [[98, 98, 100], [79, 81, 80]], [[500, 6, 33]], [[1, 2, 3]], **[[14]]**, [[2]], [[1]], [[1]], [[2.0], [6.6573267908372973]])]] and the print out continues on. Could someone explain to me how the cell array is arranged? (so how many dimensions is the above?) I then have a few questions: 1) Within this cell array, there are variables 'label' and 'coordinates' that are assigned to one array/cell (i dont know which is the actual term to use) -- the values in bold. I would like to write in Python to access this values. How should I go about it? 2) To test, I tried this -> juncInfoF = a.get('juncForward_c') and when i try to print juncInfoF, it prints 'None'. Why is that so? I am puzzled because previously when i tried this, it works. I could even do this -> print juncInfo[0][9][0][0]. but now I cannot even do any of the above. A: I imagine loadmat('file.mat') returns an instance of a shelve-class, that is inherited from the dict class. I assume you are using the loadmat function from scipy.io? from scipy.io import loadmat The scipy doc only mentions loadmat() returns a dictionary, but my guess is that the returned object a in your example is an open shelve-file, and you can no longer access its content when a is closed, which might happen for several reasons apart from calling a.close() mannually. To prevent this, copy all data into a real dictionary first, while loading this data: mat_dict = {} mat_dict.update(loadmat('file.mat')) Now you can retrieve all keys and values from mat_dict: a = mat_dict['juncForward_c'] print(a.shape) # should work now note that this is a valid solution as long as you are testing and figuring out what the mat_dict data is all about. In your script/model/function you would tipically load only the part of the shelve dict that you want, and then close the file explicitly: f = loadmat('file.mat') a = f['juncForward_c'] f.close() I don't know if the with statement works (shelve does not support it as yet), you'll have to test it, but it should handle closing even when an exception is thrown during loading of a: with loadmat('file.mat') as f: a = f['juncForward_c'] edit: subclass from numpy array to add additional attributes import numpy as np class MatArray(np.array): def __init__(self, filepath): f = loadmat(filepath) np.array.__init__(self, f['juncForward_c']) self.version = f['__version__'] self.header = f['__header__'] f.close() so now if you want your array resembling the matlab structure, you do: >>> a = MatArray('myfile.mat') >>> a.header 'MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Wed Sep 21 15:30:15 2011' >>> a.shape etc A: If in your mat file there are only cell arrays with list of integers or strings, I wrote a generic code for that. For example, in matlab you can do something like that: names = cell(1, N); indices = cell(1, N); for ind=1:N names{ind} = *some_value*; indices{ind} = *some_array*; save('names_and_indices.mat', 'names', 'indices'); Here you can find how to read this mat file in python.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: grails message.properties - how to debug I have entries added in message.properties to display customized error messages that totally work, e.g. address.street1.blank=Please provide a street address or P.O. Box I have other entries that all the sudden can't be found after the rename of a class, e.g.: billingshipping.creditCardNumber.blank=Please provide a credit card number The previous customized message worked fine before the refactor/rename of the class "Join" to "BillingShipping", when the error property was called: join.creditCardNumber.blank=Please provide a credit card number I did a clean, and I can also rename the above "address" error property to "addr" and resave the message.properties file, and sure enough I get the default grails error, instead of the custom message. Change it back again to "address", and I get the custom message, indicating that the file is getting used as expected. How do I debug further in this case, to figure out what's wrong? Thanks P.S. Note these error messages are for display on the same form, using the same controller. A: You have a typo. The class is called "BillingShipping" while the key is "billingshipping". Note the capitalization of the "s" in shipping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: An Int argument in the ArrayList, what is it? What is the difference between this: ArrayList<String> test = new ArrayList<String>(); and this: ArrayList<String> test = new ArrayList<String>(3); I just tested the Array and I really see no difference.. I always see people using a number there, what is it for ? A: Initial Capacity Generally used to create lists with some storage amount ahead of time so java doesn't have to do it for you when you add elements. Or if you know exactly how many entries it will have. To be clear, the list still doesn't contain any elements when it's created this way, but the space for those elements is reserved. A: It's the initial size of your list. If you don't give any argument, there will be a default intitial size. By the way, reading the Javadoc will answer all those questions. A: All the number does is set the initial capacity for the arraylist. The arraylist will expand as needed, but if you already know that you'll at least need X slots, you can put X in then parenthesis to allocate that number of slots right from the start. Refer to the constructor for ArrayLists here: http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html A: When you use the second code, It initially allocates 3 elements and the first will allocates 10 elements (capacity). Constructs an empty list with an initial capacity of ten. Read this
{ "language": "en", "url": "https://stackoverflow.com/questions/7621691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: observe bookmark added/updated/removed in android browser I am using Content-Observer to observe the Android-Boroswers browser.db which stores information about both history & bookmarks. My requirement is that i want to get notified only if a BOOKMARK is added/updated/removed & update my bookmarks list. But my listener gets fired even if a new page loads into the browser ( because this comes under history). Any way to resolve this ? or to observe changes for a single column. I dont want to unnecesary update my list on every event fired. Thanx in advance. A: Any way to resolve this ? Add to your WHERE clause a check to see if the BOOKMARK column is 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OCR library for Java: compiling tesseract on Windows 64-bit I'm using ImageJ for processing document images (business documents) and I am looking for a good OCR library to retrieve text from some regions. Currently I am using Asprise, but the results aren't very reliable. Certain characters often get confused (0 becomes O, 8 -> B, % -> 0, ...), then there is whitespace where it's not supposed to be and thus makes a lot of trouble postprocessing this data. The images have a resolution of 1240x1754, I haven't tried a higher resolution yet, but the smallest characters I'd like to detect are 15 pixels high, so I assume the quality of the image is sufficient. (by the way, I am performing the ocr on the original image, not the binary image) Looking at similar questions here, I noticed tesseract has often been recommeneded. Since it's written in c++ I am not sure how I can use it in Java and ImageJ. Using Asprise, which, as far I know, is also written in c++ and just offers a Java wrapper, I can perform ocr based on a BufferedImage. So I am assume I could do the same with tesseract. 1. How can I call tesseract functions from Java? UPDATE: I tried to use tesjeract, but when I am executing my application it crashes due to a UnsatisfiedLinkError: C:\Windows\System32\tessdll.dll: Can't find dependent libraries I was able to successfully compile tesjeract and tesseract 2.04 and placed tessdll.dll and tesjeract.dll in c:\windows\system32 . I am using this static block to load the libraries: static { System.loadLibrary("tessdll"); System.loadLibrary("tesjeract"); } In case it is relevant, I am using Windows 7 64-bit. 2. So how can I convert a BufferedImage into a format tesseract is able to work with? SOLVED This is the code, if anyone is interested: (originates from audiveris ) private ByteBuffer imageToTiffBuffer (BufferedImage image) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); // Take the first suitable TIFF writer ImageWriter writer = ImageIO.getImageWritersByFormatName("tiff").next(); writer.setOutput(ios); writer.write(image); ios.close(); // allocate() doesn't work ByteBuffer buf = ByteBuffer.allocateDirect(baos.size()); buf.put(baos.toByteArray()); return buf; } A: The bitness of the external libraries need to match up with your JVM. Since tesjeract is the lowest common denominator, you'll need to use the 32 bit JVM. A: You could look at audiveris, a Java OMR package that I believe uses Tesseract for the text portions of sheets. A: There are two Java wrappers for Tesseract 2.04 that you may want to take a look: Tess4J and Tesjeract.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Combining two lists in Scala From 2 lists of the form List[(Int, String): l1 = List((1,"a"),(3,"b")) l2 = List((3,"a"),(4,"c")) how can I combine the Integers where the Strings are the same to get this third list: l3 = List((4,"a"),(3,"b"),(4,"c")) Right now I'm traversing both of the lists and adding if the strings are the same, but I think there should be a simple solution with pattern matching. A: val l = l1 ::: l2 val m = Map[String, Int]() (m /: l) { case (map, (i, s)) => { map.updated(s, i + (map.get(s) getOrElse 0))} }.toList // Note: Tuples are reversed. But I suppose there is a more elegant way to do the updated part. A: How about, (l1 ++ l2).groupBy(_._2).mapValues(_.unzip._1.sum).toList.map(_.swap) Unpacking this a little on the REPL helps to show what's going on, scala> l1 ++ l2 res0: List[(Int, java.lang.String)] = List((1,a), (3,b), (3,a), (4,c)) scala> res0.groupBy(_._2) res1: ... = Map(c -> List((4,c)), a -> List((1,a), (3,a)), b -> List((3,b))) scala> res1.mapValues(_.unzip) res2: ... = Map(c -> (List(4),List(c)), a -> (List(1, 3),List(a, a)), b -> (List(3),List(b))) scala> res1.mapValues(_.unzip._1) res3: ... = Map(c -> List(4), a -> List(1, 3), b -> List(3)) scala> res1.mapValues(_.unzip._1.sum) res4: ... = Map(c -> 4, a -> 4, b -> 3) scala> res4.toList res5: List[(java.lang.String, Int)] = List((c,4), (a,4), (b,3)) scala> res5.map(_.swap) res6: List[(Int, java.lang.String)] = List((4,c), (4,a), (3,b)) A: With Scalaz, this is a snap. import scalaz._ import Scalaz._ val l3 = (l1.map(_.swap).toMap |+| l2.map(_.swap).toMap) toList The |+| method is exposed on all types T for which there exists an implementation of Semigroup[T]. And it just so happens that the semigroup for Map[String, Int] is exactly what you want. A: for ( (k,v) <- (l1++l2).groupBy(_._2).toList ) yield ( v.map(_._1).sum, k ) A: Note that with this solution, the lists are traversed twice. val l3 = (l1 zip l2).foldRight(List[(Int, String)]()) { case ((firstPair @ (firstNumber, firstWord), secondPair @ (secondNumber, secondWord)), result) => if (firstWord == secondWord) ((firstNumber + secondNumber), firstWord) :: result else firstPair :: secondPair :: result } A: Another opaque onetwo-liner of questionable efficiency yet indubitable efficacy: val lst = l1 ++ l2 lst.map(_._2).distinct.map(i => (lst.filter(_._2 == i).map(_._1).sum, i)) A: val a = List(1,1,1,0,0,2) val b = List(1,0,3,2) scala> List.concat(a,b) res31: List[Int] = List(1, 1, 1, 0, 0, 2, 1, 0, 3, 2) (or) scala> a.:::(b) res32: List[Int] = List(1, 0, 3, 2, 1, 1, 1, 0, 0, 2) (or) scala> a ::: b res28: List[Int] = List(1, 1, 1, 0, 0, 2, 1, 0, 3, 2) A: An alternative to Miles Sabin's answer using Scala 2.13's new groupMapReduce method which is (as its name suggests) an equivalent (more efficient) of a groupBy followed by mapValues and a reduce step: (l1 ::: l2).groupMapReduce(_._2)(_._1)(_ + _).toList.map(_.swap) // List[(Int, String)] = List((3,b), (4,a), (4,c)) This: * *prepends l1 to l2 *groups elements based on their second tuple part (group part of groupMapReduce) *maps grouped values to their first tuple part (map part of groupMapReduce) *reduces values (_ + _) by summing them (reduce part of groupMapReduce) *and finally swaps tuples' parts. This is an equivalent version performed in one pass (for the group/map/reduce part) through the List of: (l1 ::: l2).groupBy(_._2).mapValues(_.map(_._1).reduce(_ + _)).toList.map(_.swap)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Confused about Andengine Coordinate system(s) When I create a sprite at (0,0) and it is centered on the screen and I ask the camera what it's center is (getCenterX and getCenterY) it says (640,400). I am pretty new with Andengine so there's clearly something basic about coordinates that I am not understanding. A: Note that the accepted version is is not valid anymore. Now, AndEngine coordinates have changed to the bottom-left corner of the screen, like cocos-2d. A: If you're using the default camera, a Sprite placed at 0,0 would be at the top-left corner of the screen. If you've moved the camera, 0,0 could be at the 'centre' of the screen of course. Note: Scaling a sprite causes it to shrink towards it's centre (not it's top-left corner) - so a Sprite which is the whole size of the screen will appear in the centre when scaled-down (rather than shrink up into the top-left corner)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to prevent blur() running when clicking a link in jQuery? i have: <input type="text" /> and $('input').blur(function(){ alert('stay focused!'); }); I want to prevent the blur function running when I'm "blurring" by clicking on an anchor element. I.E. if i tab to another input, click somewhere on the page etc i want the blur to fire, but if i click a link, I don't want it to fire. Is this easily achievable, or do i need to hack about with delegates and semaphores? Thanks A: Delay the blur a bit. If the viewer clicks a link to another page, the page should change before this code gets a chance to run: $('input').blur(function(){ setTimeout(function() {alert('stay focused!');}, 1000); }); You can experiment with what delay value for the timeout seems appropriate. A: I had to solve this problem myself today, too. I found that the mousedown event fires before the blur event, so all you need to do is set a variable that indicates that a mousedown event occurred first, and then manage your blur event appropriately if so. var mousedownHappened = false; $('input').blur(function() { if(mousedownHappened) // cancel the blur event { alert('stay focused!'); $('input').focus(); mousedownHappened = false; } else // blur event is okay { // Do stuff... } }); $('a').mousedown(function() { mousedownHappened = true; }); Hope this helps you!! A: You can get this behavior by calling preventDefault() in the mousedown event of the control being clicked (that would otherwise take focus). For example: btn.addEventListener('mousedown', function (event) { event.preventDefault() }) btn.addEventListener('click', function(ev) { input.value += '@' input.setSelectionRange(ta.value.length, ta.value.length) }) See live example here. A: If you want to keep the cursor at its position in a contenteditable element, simply: $('button').mousedown(function(){return false;}); A: Some clarification that was too long to put in a comment. The click event represents both pressing the mouse button down, AND releasing it on a particular element. The blur event fires when an element loses focus, and an element can lose focus when the user "clicks" off of the element. But notice the behavior. An element gets blurred as soon as you press your mouse DOWN. You don't have to release. That is the reason why blur gets fired before click. A solution, depending on your circumstances, is to call preventDefault on mousedown and touchstart events. These events always (I can't find concrete documentation on this, but articles/SO posts/testing seem to confirm this) fire before blur. This is the basis of Jens Jensen's answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: How do I initialize the mutex locks and condition variables pthread_mutex_t qlock[5] = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qcond[5] = PTHREAD_COND_INITIALIZER; It is giving me error as follows... error: array must be initialized with a brace-enclosed initializer .. Please, can somebody debug this or tell me a way to solve it... A: This initializes a mutex: pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; This initializes an array: int array[5] = { 0, 1, 2, 3, 4 }; ...that should be enough to get you going. A: I'd suggest you reading a beginner book on C programming language. See for example a related SO question. BTW, at this level of C knowledge I would highly recommend you to stay away from multithreaded programming (at least with pthreads).
{ "language": "en", "url": "https://stackoverflow.com/questions/7621713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: using the Camera api with phonegap on symbian I can't figure out why this isn't working.. can't check this on the nokia simulator because it doesn't simulate a camera.. and the phone app either crashes or just don't bring any picture I tried both Base64 method and imageURI method (with different buttons on the html page) this is the javascript (the reason for the duplicate js for the camera is trying the different methods): function camera (){ $('#showpic').css('display','block').html("getting an image"); navigator.camera.getPicture(camerasuccess,camerafail,null); }; function camerasuccess(imageBASE) { $('#showpic').css('display','block').html("we have an image"); var imgsrc = "data:image/jpeg;base64,"+imageBASE[0]; $('#imageplace').html('<img src ="'+imgsrc+'"/>'); //var useimg = document.getElementById('useimage'); // //useimg.style.display = 'block'; //useimg.src = "data:image/jpeg;base64,"+imageBASE; } function camerafail(error) { $('#showpic').css('display','block').html("some error:"+error); }; function camera2(){ $('#showpic').css('display','block').html("getting an image"); navigator.camera.getPicture(camera2success,camerafail,null); }; function camera2success (imageURI){ $('#showpic').css('display','block').html("we have an image"); $('#debug').html(imageURI[0]); if (!imageURI[0]) { $('#debug').html("no imageURI here"); } $('#imageplace').html('<img src ="'+imageURI[0]+'"/>'); and this is the markup (here also the remains of the different approaches I took): <div id = "camera"> <input type = "button" id = "camera" value = "base"> <input type = "button" id = "camera2" value = "imageURi"></br> <span id = "showpic" style = "display:none;">showpic</span><br/> <span id = "debug"></span></br> <div id = "imageplace"></div></br> <img id = "useimage" style = "display:none; width:60px; height:60px " src = ''/> </div> another notice: if it has any meaning then you should know I don't use make to close the wgz file, just zip the www folder and change the ending to wgz, most js functions (including geolocation) work fine. A: I've got a similar problem. I am using a Nokia N8. It fires the getPicture method, and I can take a photo. However the only way to exit from the 'taking a photo' app is to click Back. This fires the success function, but no image data is returned. Looking at the API docs for Phonegap, it says that these are the supported platforms for the Camera API: * *Android *Blackberry WebWorks (OS 5.0 and higher) *iPhone *Windows Phone 7 ( Mango ) After much trial and error, this apparently only works if you expect the Camera API to return images as URIs (not the actual image data), and also set editable to true. Try something like this: navigator.camera.getPicture(camerasuccess, onFail, { quality: 20, allowEdit: true }); $('#imageplace').html('<img src ="'+imageBASE+'"/>');
{ "language": "en", "url": "https://stackoverflow.com/questions/7621717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check validaty of variables names dynamically generated by URI I am building router for my custom MVC project. In my router, for pretty URL names, I ran into problem. What is the best practice for dealing with dynamically generated variables names via URI? Example: http://knjiskicrv.comoj.com/book/id/2/ Will generate: $page = 'book'; $id = '2'; Now, problem may arise when someone deliberately start messing up with URI. Like: http://knjiskicrv.comoj.com/book/id+one/2/ I will get: $page = 'book'; $id one = '2'; Hope someone could give me some advice how to prevent and solve this? Thanks. A: I think you're asking about mitigating "Cross Site Scripting" (XSS) vulnerabilities. That's a big topic. And remember: there are LOTS of ways for a (potentially malicious) user to "deliberately start messing ... with the URI". Suggestion: start reading :) Here are some links: http://seancoates.com/blogs/xss-woes http://www.cgisecurity.com/xss-faq.html http://www.uri.edu/webservices/phpGuideline.html A: You could store those variables in an array, so you get $var['id one'] = '2'; Just my suggestion. A: First of all, input sanitize that url. Do not create dynamic variables from a spoofable input source. Well, you have to know, what to expect on the given page. What variables and what type of variables these hold. What if you have to display a set of categories and one of the categories' name is 'id' /products/monkeys/white/id/ - you are properly ...d Choose a different convention for processing your URI. Like divide the URI into area, section and page elements. http://www.oink.com/products/pigs/spottyones/angry/the_big_spotty_pig.html area = 'products' section = array('spottyones','angry') page = the_big_spotty_pig (this uniquely identifies the article, product etc.) When I have to use variables, these are mostly about ordering, page nr, etc. So these can be appended as query string parameters. UPDATE Sanitization: You have to set the rules for yourself. Let's say the URI can only contain certain characters. //Sanitization $uri = $_SERVER['REQUEST_URI']; // /products/monkey/angry/page.html //allow only characters, numbers, underline and dash if (!preg_match('~^[a-z0-9-_]$~isD',$uri)) $uri = '/'; //URI has been tampered with $uriparts = explode('/',$uri); /* array('products','monkey','angry','page.html') */ //Do whatever you want with the uri parts ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My application tries replace another my application My application tries replace another my application. I add aplication on git https://github.com/szalek/AndroidLevel1. When I install the application 'Vinyl' and next install the application 'TeamLeader1/'. I see message 'The application you are installing will replace another application. All previous user data will be saved' A: This is because both applications have the same package name. If the package name of the two applications are different, you won't get this message. In fact, if the package name in the Manifest file (in the <manifest> tag) matches the package name of another installed application, it will replace it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split a string into words by multiple delimiters I have some text (meaningful text or arithmetical expression) and I want to split it into words. If I had a single delimiter, I'd use: std::stringstream stringStream(inputString); std::string word; while(std::getline(stringStream, word, delimiter)) { wordVector.push_back(word); } How can I break the string into tokens with several delimiters? A: Assuming one of the delimiters is newline, the following reads the line and further splits it by the delimiters. For this example I've chosen the delimiters space, apostrophe, and semi-colon. std::stringstream stringStream(inputString); std::string line; while(std::getline(stringStream, line)) { std::size_t prev = 0, pos; while ((pos = line.find_first_of(" ';", prev)) != std::string::npos) { if (pos > prev) wordVector.push_back(line.substr(prev, pos-prev)); prev = pos+1; } if (prev < line.length()) wordVector.push_back(line.substr(prev, std::string::npos)); } A: I don't know why nobody pointed out the manual way, but here it is: const std::string delims(";,:. \n\t"); inline bool isDelim(char c) { for (int i = 0; i < delims.size(); ++i) if (delims[i] == c) return true; return false; } and in function: std::stringstream stringStream(inputString); std::string word; char c; while (stringStream) { word.clear(); // Read word while (!isDelim((c = stringStream.get()))) word.push_back(c); if (c != EOF) stringStream.unget(); wordVector.push_back(word); // Read delims while (isDelim((c = stringStream.get()))); if (c != EOF) stringStream.unget(); } This way you can do something useful with the delims if you want. A: And here, ages later, a solution using C++20: constexpr std::string_view words{"Hello-_-C++-_-20-_-!"}; constexpr std::string_view delimeters{"-_-"}; for (const std::string_view word : std::views::split(words, delimeters)) { std::cout << std::quoted(word) << ' '; } // outputs: Hello C++ 20! Required headers: #include <ranges> #include <string_view> Reference: https://en.cppreference.com/w/cpp/ranges/split_view A: If you have boost, you could use: #include <boost/algorithm/string.hpp> std::string inputString("One!Two,Three:Four"); std::string delimiters("|,:"); std::vector<std::string> parts; boost::split(parts, inputString, boost::is_any_of(delimiters)); A: If you interesting in how to do it yourself and not using boost. Assuming the delimiter string may be very long - let say M, checking for every char in your string if it is a delimiter, would cost O(M) each, so doing so in a loop for all chars in your original string, let say in length N, is O(M*N). I would use a dictionary (like a map - "delimiter" to "booleans" - but here I would use a simple boolean array that has true in index = ascii value for each delimiter). Now iterating on the string and check if the char is a delimiter is O(1), which eventually gives us O(N) overall. Here is my sample code: const int dictSize = 256; vector<string> tokenizeMyString(const string &s, const string &del) { static bool dict[dictSize] = { false}; vector<string> res; for (int i = 0; i < del.size(); ++i) { dict[del[i]] = true; } string token(""); for (auto &i : s) { if (dict[i]) { if (!token.empty()) { res.push_back(token); token.clear(); } } else { token += i; } } if (!token.empty()) { res.push_back(token); } return res; } int main() { string delString = "MyDog:Odie, MyCat:Garfield MyNumber:1001001"; //the delimiters are " " (space) and "," (comma) vector<string> res = tokenizeMyString(delString, " ,"); for (auto &i : res) { cout << "token: " << i << endl; } return 0; } Note: tokenizeMyString returns vector by value and create it on the stack first, so we're using here the power of the compiler >>> RVO - return value optimization :) A: Using std::regex A std::regex can do string splitting in a few lines: std::regex re("[\\|,:]"); std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last;//the '-1' is what makes the regex split (-1 := what was not matched) std::vector<std::string> tokens{first, last}; Try it yourself A: Using Eric Niebler's range-v3 library: https://godbolt.org/z/ZnxfSa #include <string> #include <iostream> #include "range/v3/all.hpp" int main() { std::string s = "user1:192.168.0.1|user2:192.168.0.2|user3:192.168.0.3"; auto words = s | ranges::view::split('|') | ranges::view::transform([](auto w){ return w | ranges::view::split(':'); }); ranges::for_each(words, [](auto i){ std::cout << i << "\n"; }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621727", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Get and set values of a form How can I get the values of all visible fields in a form (with several fields) and set them in a array or something else? After I would like to get these values from the array and set them to the visible fields in the same form (such as a clear and undo function of a form)? My form has several select-fields, text-fields, textarea-fields and hidden-fields. Thanks for your help! A: By looking up the answer in jquery api guide :) hehe http://api.jquery.com/serializeArray/ A: Have answered this question in the below link Submitting form data through a jQuery command . This will be useful. By visible fields do you mean the enabled fields? Look up the jquery api for the serialize method A: I could realize it with the jQuery data() method. After storing the form with this method you can extract the values. A: The easiest was to do this is to mark all elements in your form with a css class (the class doesn't need to exist in your style sheet). Ie put the class formfield on all of your form inputs. Then you can simply use the jquery class selector to select all of the inputs at once and do what you want to them e.g. $('.formfield').hide(); The above command will hide all of your form elements but you can use the $('.formfield') selector to do whatever you want to all of the form fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS - How to display data from plist when there is more than one key? I am able to get data from plist but it seems my cellForRowAtIndexPath is not getting called as none of NSLog printing anything from inside the method. here is my code :- - (void)viewDidLoad { NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"]; NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; self.drinks = [tempDict objectForKey:@"Root"]; NSLog(@"%@", self.drinks); NSLog(@"Number = %d", self.drinks.count); [super viewDidLoad]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; NSLog(@"I am inside cellForRowAtIndexPath"); UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. NSArray *allValues = [self.drinks valueForKey:@"name"]; NSLog(@"%d", allValues.count); cell.textLabel.text = [allValues objectAtIndex:indexPath.row]; return cell; } Here is my console output :- 2011-10-01 20:27:01.940 DrinkMixer[1832:b303] ( { directions = "Shake adahsdk adlkasd"; ingredients = "kslkds lkjsjlkd kjsljlakj aajdlkj"; name = "Fire Cracker"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Lemon Drop"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = Mojito; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "After Drink Mint"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Apple Martini"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Shockwave"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Beer"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Last Desire"; }, { directions = "abds fedfsdkkjkljlkj;j ok"; ingredients = "hasdhalsdlash asdhasldh kjdfkjshdj"; name = "Vodka"; } ) 2011-10-01 20:27:01.942 DrinkMixer[1832:b303] Number = 9 None of cellForRowAtIndexPath's NSLog get called. Can anyone please tell what is wrong with this code. Thanks. A: Odds are that you either have not implemented UITableViewDelegate in your header file, or your UITableView's datasource and delegate are not wired up in your nib file. I suggest checking out the datasource. UPDATE: The fact that the tableView:cellForRowAtIndexPath: isn't being called and the datasource is set correctly then it could be that the plist is loaded into self.drinks after the UITableView is already loaded. Proof could be to scroll the empty UITableView up and down and see if cells from off the screen start to appear. I suggest two things: * *call [super viewDidLoad]; at the beginning of your -(void)viewDidLoad *call for a reload your UITableView after the plist is loaded. Try: - (void)viewDidLoad { [super viewDidLoad]; NSString *path = [[NSBundle mainBundle] pathForResource:@"drinks" ofType:@"plist"]; NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; self.drinks = [tempDict objectForKey:@"Root"]; NSLog(@"%@", self.drinks); NSLog(@"Number = %d", self.drinks.count); [yourTableView reload]; } Lastly, the reason I worry about your datasource is because I think even an empty cell should call tableView:cellForRowAtIndexPath: Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arranging 3 letter words in a 2D matrix such that each row, column and diagonal forms a word You are given a dictionary of 3 letter words and have to find a matrix of 3x3 such that each row, column and diagonal forms a word in the dictionary. The words in the dictionary are sorted and you can assume O(1) time for retrieving a word from the dictionary. This has been asked as a Facebook interview question. A: My approach would be to filter the dictionary first to create two new dictionaries: The first contains all single letter prefixes of words (of which there are probably 26), and the second contains all double letter prefixes of words (of which there are fewer than 26^2 since no word starts with BB, for example). * *Choose a word from the dictionary, call it X. This will be the first row of the matrix. *Check that X1, X2, X3 are all valid single letter prefixes using that handy list you made. If they are, go on to step 3; otherwise go back to step 1. *Choose a word from the dictionary, call it Y. This will be the second row of the matrix. *Check that X1 Y1, X2 Y2, X3 Y3 are all valid double letter prefixes using that handy list you made. If they are, go on to step 5; otherwise go back to step 3. If this was the last word in the dictionary, then go all the way back to step 1. *Choose a word from the dictionary, call it Z. This will be the third row of the matrix. *Check that X1 Y1 Z1, X2 Y2 Z2, X3 Y3 Z3 are all words in the dictionary. If they are, congrats, you've done it! Otherwise go back to step 5. If this was the last word in the dictionary, then go all the way back to step 3. I coded this up in Maple and it works reasonably well. I left it running to find all such matrices and it turns out there are enough to crash Maple due to memory overflow. A: Your comment suggest you are also looking for backtracking solution, which will be not efficient, but solves this. Pseudo-Code: solve(dictionary,matrix): if matrix is full: if validate(dictionary,matrix) == true: return true else: return false for each word in dictionary: dictionary -= word matrix.add(word) if solve(dictionary,matrix) == true: return true else: dictionary += word matrix.removeLast() return false //no solution for this matrix. In the above pseudo-code, matrix.add() adds the given word in the first non-occupied line. matrix.remove() removes the last occupied line, and validate() checks if the solution is a legal one. Activation: solve(dictionary,empty_matrix), if the algorithm yields true, there is a solution and the input matrix will contain it, else it will yield false. The above pseudo-code runs in exponential time! it is very non-efficient. However, since this problem resembles(*) the crossword problem, which is NP-Complete, it might be your best shot. (*)The original Crossword-Problem doesn't have the diagonal condition that this problem has, and is of course more general: nxm matrix, not only 3x3. Though the problems are similar, a reduction doesn't pop to my head, and I will be glad to see one if exist. A: * *You find every unique set of 3 words. *You get all 6 possible matrices for those 3 words. *You do a dictionary check for the 5 words that could be created from those matrices (3 columns and 2 diagonals). Some JavaScript to illustrate. //setup a test dictionary var dict = [ "MAD", "FAD", "CAT", "ADD", "DOG", "MOD", "FAM", "ADA", "DDD", "FDD" ]; for(var i=0; i<dict.length; i++) dict[dict[i]]=true; // functions function find(dict) { for(var x=0; x<dict.length; x++) { for(var y=x+1; y<dict.length; y++) { for(var z=y+1; z<dict.length; z++) { var a=dict[x]; var b=dict[y]; var c=dict[z]; if(valid(dict,a,b,c)) return [a,b,c]; if(valid(dict,a,c,b)) return [a,c,b]; if(valid(dict,b,a,c)) return [b,a,c]; if(valid(dict,b,c,a)) return [b,c,a]; if(valid(dict,c,a,b)) return [c,a,b]; if(valid(dict,c,b,a)) return [c,b,a]; } } } return null; } function valid(dict, row1, row2, row3) { var words = []; words.push(row1.charAt(0)+row2.charAt(0)+row3.charAt(0)); words.push(row1.charAt(1)+row2.charAt(1)+row3.charAt(1)); words.push(row1.charAt(2)+row2.charAt(2)+row3.charAt(2)); words.push(row1.charAt(0)+row2.charAt(1)+row3.charAt(2)); words.push(row3.charAt(0)+row2.charAt(1)+row1.charAt(2)); for(var x=0; x<words.length; x++) if(dict[words[x]] == null) return false; return true; } //test find(dict); A: I was not necessarily looking for a backtracking solution. It just struck to me that back tracking can be used, but the solution with that is a bit complicated. However we can use branch and bound and pruning to cut short the brute force technique. Instead of searching for all possible combinations in the matrix, first we will select one string as the topmost row. Using the first character we find a suitable contender for the 1st column. Now using the 2 and 3 characters of the column string, we will find suitable words that can be fitted in the second and third row. To efficiently find words beginning with a particular character we will use radix sort so that all words beginning with a particular character are stored in the same list. This when we have chosen the the second and third row of the matrix, we have a complete matrix.\ We will check whether the matrix is valid, by checking the 2nd and 3rd column and the diagonals form words that fall in the dictionary. As and when we find that the matrix is valid we can stop. This helps in cutting down some of the possible combinations. However I feel this can be further optimized by considering another row or column, but then it would be a bit complicated. I am posting a working code below. Please don't mind the naming of the functions, since I am an amateur coder, I generally do not give very appropriate names and some part of the code is hard coded for 3 letter words. #include<iostream> #include<string> #include<algorithm> #include<fstream> #include<vector> #include<list> #include<set> using namespace std; // This will contain the list of the words read from the // input file list<string> words[26]; // This will contain the output matrix string out[3]; // This function finds whether the string exits // in the given dictionary, it searches based on the // first character of the string bool findString(string in) { list<string> strings = words[(int)(in[0]-'a')]; list<string>:: iterator p; p = find(strings.begin(),strings.end(),in); if(p!=strings.end()) return true; } // Since we have already chosen valid strings for all the rows // and first column we just need to check the diagnol and the // 2 and 3rd column bool checkMatrix() { // Diagnol 1 string d1; d1.push_back(out[0][0]); d1.push_back(out[1][1]); d1.push_back(out[2][2]); if(!(findString(d1))) return false; // Diagnol 2 string d2; d2.push_back(out[0][0]); d2.push_back(out[1][1]); d2.push_back(out[2][2]); if(!(findString(d2))) return false; // Column 2 string c2; c2.push_back(out[0][1]); c2.push_back(out[1][1]); c2.push_back(out[2][1]); if(!(findString(c2))) return false; // Column 3 string c3; c3.push_back(out[0][2]); c3.push_back(out[1][2]); c3.push_back(out[2][2]); if(!(findString(c3))) return false; else return true; // If all match then return true } // It finds all the strings begining with a particular character list<string> findAll(int i) { // It will contain the possible strings list<string> possible; list<string>:: iterator it; it = words[i].begin(); while(it!=words[i].end()) { possible.push_back(*it); it++; } return possible; } // It is the function which is called on each string in the dictionary bool findMatrix(string in) { // contains the current set of strings set<string> current; // set the first row as the input string out[0]=in; current.insert(in); // find out the character for the column char first = out[0][0]; // find possible strings for the column list<string> col1 = findAll((int)(first-'a')); list<string>::iterator it; for(it = col1.begin();it!=col1.end();it++) { // If this string is not in the current set if(current.find(*it) == current.end()) { // Insert the string in the set of current strings current.insert(*it); // The characters for second and third rows char second = (*it)[1]; char third = (*it)[2]; // find the possible row contenders using the column string list<string> secondRow = findAll((int)(second-'a')); list<string> thirdRow = findAll((int)(third-'a')); // Iterators list<string>::iterator it1; list<string>::iterator it2; for(it1= secondRow.begin();it1!=secondRow.end();it1++) { // If this string is not in the current set if(current.find(*it1) == current.end()) { // Use it as the string for row 2 and insert in the current set current.insert(*it1); for(it2 = thirdRow.begin();it2!=thirdRow.end();it2++) { // If this string is not in the current set if(current.find(*it2) == current.end()) { // Insert it in the current set and use it as Row 3 current.insert(*it2); out[1]=*it1; out[2]=*it2; // Check ifthe matrix is a valid matrix bool result = checkMatrix(); // if yes the return true if(result == true) return result; // If not then remove the row 3 string from current set current.erase(*it2); } } // Remove the row 2 string from current set current.erase(*it1); } } // Remove the row 1 string from current set current.erase(*it); } } // If we come out of these 3 loops then it means there was no // possible match for this string return false; } int main() { const char* file = "input.txt"; ifstream inFile(file); string word; // Read the words and store them in array of lists // Basically radix sort them based on their first character // so all the words with 'a' appear in the same list // i.e. words[0] if(inFile.is_open()) { while(inFile.good()) { inFile >> word; if(word[0] >= 'a' && word[0] <= 'z') { int index1 = word[0]-'a'; words[index1].push_back(word); } } } else cout<<"The file could not be opened"<<endl; // Call the findMatrix function for each string in the list and // stop when a true value is returned int i; for(i=0;i < 26;i++) { it = words[i].begin(); while(it!=words[i].end()) { if(findMatrix(*it)) { // Output the matrix for(int j=0;j<3;j++) cout<<out[j]<<endl; // break out of both the loops i=27; break; } it++; } } // If i ==26 then the loop ran the whole time and no break was // called which means no match was found if(i==26) cout<<"Matrix does not exist"<<endl; system("pause"); return 0; } I have tested the code on a small set of strings and it worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: JDBC and MySQL, how to persist java.util.Date to a DATETIME column? I'm struggling to understand how to get it to work. I have a prepared statment, and I want to persist a java.util.date. It doesn't work. I tried to cast it to java.sql.Date, and it still doesn't work. what's the issue with java date framework, it's really not straight forward. A: This will do it: int dateColumnId = 0; // or whatever the value needs to be. java.util.Date incomingValue = new java.util.Date(System.currentTimeMillis()); java.sql.Date databaseValue = new java.sql.Date(incomingValue.getTime()); ps.setDate(dateColumnId, databaseValue); A: Maybe you can try this: java.util.Date now = new java.util.Date(); java.sql.Date date = new java.sql.Date(now.getTime()); pstmt.setDate(columnIndex,date); A: You should use java.sql.Timestamp to store a java.util.Date in a DATETIME field. If you check the javadocs of both classes (click the above links!), you'll see that the Timestamp has a constructor taking the time in millis and that Date has a getter returning the time in millis. Do the math: preparedStatement.setTimestamp(index, new Timestamp(date.getTime())); // ... You should not use java.sql.Date as it represents only the date portion, not the time portion. With this, you would end up with 00:00:00 as time in the DATETIME field. For your information only, since Timestamp is a subclass of java.util.Date, you could just upcast it whenever you obtain it from the ResultSet. Date date = resultSet.getTimestamp("columnname"); // ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7621736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Make child div match height of parent div, and make padding apply to a border in a div I have two questions applying to my website. Please view the source to help answer these two questions. * *I want the border inside the div "nav-cont-seperator" to be shifted down 10px. I can't get padding to fix this problem, probably because borders ignore padding. *My second question is, how do I make that vertical border go to the bottom of the page (make the div match the height of its parent), minus 10px? A: * *If I understand you correctly, you need a margin-top: 10px; on that div. Containers in HTML respect the box model (you can see that in firebug, for instance), meaning that the size of the element is given by: margin + border + padding. Padding applies to the inner part of a border, margin to the outside. *I'm not sure there's a clear way of doing that with pure HTML/CSS. Let me ask you another question... are you sure you need that div? Couldn't that separator be the right-side border of the left menu div? That might solve your problem and clear up some markup. Anyway, if you're using jQuery, the answer here: how to size a div's height to its container height, using CSS? might be of help!
{ "language": "en", "url": "https://stackoverflow.com/questions/7621737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VB.Net form as part of desktop I've spent a while searching around and I can't find a solution to this: I have a transparent, borderless form that displays a clock. I can load this just fine, but I want the clock to be part of the desktop, so it cannot take focus, is behind other applications, and is not hidden with Win+D (similar to applications like RainMeter). I need the solution to work with VB.Net (I'm using 2010) Thanks in anticipation A: Take a look at the following codeproject article: Application Desktop Toolbars It seems to do what you require. This article is about Application Desktop Toolbars, which are applications that can align to the screen much like the taskbar. The article will develop a base class for developing such apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XCode 4 Interface Builder: How to access a drawn object I'm very new to iPhone development. I drew a View using the Interface Builder in XCode 4. Currently the only thing inside is a Label (taken from the Object Library in the Interface Builder (So this is a UILabel, right?) ). I've set the tag of it to 6543 as recognizable test-value. Now, I'm trying to write a method which prints out the tag. My problem is that I can't access the Label that I drew in the Interface Builder. I know I can get the tag from an id, doing this: int t = [myId tag]; So, I think the question is: How to get an id of the Label I drew? And when that works, how to edit the text of the Label? I think that when I know how to do these two things, I will be able to find out myself everything else that I want to do in my application. I'm searching for about three hours, but I think I don't know the right terms to find any relevant info. Many thanks. A: You need to create an outlet in your viewcontroller class and link this to the label. This is a fundamental principle of using interface builder. Xcode 4 can do this automatically for you by using the "assistant" editor ( the little chap with the bow tie) and control-dragging from the label to your class's .h file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 1px shared :hover border on two elements Two inline-block elements next to each other. .e{border:1px #ccc solid} .e:hover{border-color:#555} What I'd like is to reduce the 1px+1px border between them to a shared 1px border. To illustrate. --------- | | | --------- Select first element. +++++----- + + | +++++----- Select second element. -----+++++ | + + -----+++++ It's simple to reduce the 2px border to 1px by setting either border-right or border-left to 0, but how to keep the 1px shared border when either element is selected? Without JavaScript. A: You could give them a -1px left margin to get their borders overlapping and then undo that margin on the first one. Then adjust the z-index on hover (and don't forget position: relative to make the z-index work). Something like this: .e { border: 1px #ccc solid; position: relative; margin-left: -1px; } .e:first-child { margin-left: 0; } .e:hover { border-color: #555; z-index: 5; } Demo: http://jsfiddle.net/ambiguous/XTzqx/ You might need to play with the :first-child a bit depending on how your HTML is structured; a couple other options if :first-child or another pseudo-class won't work: * *Wrap it all in a <div> with padding-left: 1px to kludge around the margin-left: -1px . *Add an extra class to the first one that has margin-left: 0. A: Make the :hover state have a 2px border and give it -1px margin on both sides. Make exceptions for :first-child and last-child assuming you don't have to care about every browser out there… I'm looking at you IE6/7
{ "language": "en", "url": "https://stackoverflow.com/questions/7621749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I retrieve Haystack SearchQuery parameters I am looking for a way to serialize a Haystack search query (not the query results) so that I can reconstruct it later. Is there a way to do this without having to intercept the parameters from off of the request object? For context, I want users to be able to subscribe to the results of a particular search, including any new results that may pop up over time. Edit: I settled on storing the search with: filter = queryset.query.query_filter and then loading this back in using: SearchQuerySet().raw_search(filter) Though I suspect this will tie me to whichever particular search back-end I'm using now. Is this true? Is there a better way? A: You should have the query in your request.GET. Then it should be fairly easy to construct a RSS Feed using that query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange issues with drop down list of Combobox Once again I can't find a neat solution for a simple UI problem in WPF. I want the combo box drop down list to appear whenever combo box gets focus. So I wrote this in the got focus event: private void comboBoxAC_Cat_GotFocus(object sender, RoutedEventArgs e) { comboBoxAC_Cat.IsDropDownOpen = true; } But now the problem is that once the drop down list opens, the application is kind of stuck in it. It can not come out of the drop down list no matter what I do, whether I press enter or anything. I tried registering to lost focus or other events but nothing seems to work. Here is a list of my event handlers in the application which become useless once I get inside the drop down list. private void Grid_PreviewKeyDown(object sender, KeyEventArgs e) { var uie = e.OriginalSource as UIElement; if (e.Source is Button) return; if (e.Key == Key.Enter) { e.Handled = true; uie.MoveFocus( new TraversalRequrest( FocusNavigationDiection.Next)); } } private void comboBoxAC_Cat_LostFocus(object sender, RoutedEventArgs e) { (sender as ComboBox).IsDropDownOpen = false; } Can any one help me out with this please? My Basic requirement is simple: Drop Down list should open as soon as Combobox is focused using tab or mouse. Then the user should be able to select the items and once he presses enter selecting a item from drop down list, it should close and focus should move to next ui element. Now is it hard to achieve??? I thought that was exactly the functionality of a combobox A: I don't understand, If I use exactly this code below private bool returnedFocus = false; private void myComboBox_GotFocus(object sender, RoutedEventArgs e) { if (e.OriginalSource.GetType() != typeof(ComboBoxItem) && !returnedFocus) { cmb.IsDropDownOpen = true; } } private void myComboBox_LostFocus(object sender, RoutedEventArgs e) { if (e.OriginalSource.GetType() != typeof(ComboBoxItem)) { ComboBox cb = (ComboBox)sender; returnedFocus = cb.IsDropDownOpen; } } I get exactly what i think you want, my combobox drop down opens when control get focus and if i choose a listitem pressing enter or through mouse click contol loses focus Isn't that what you wanted?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What's the appropriate way to colorize a grayscale image with transparency in Java? I'm making an avatar generator where the avatar components are from PNG files with transparency. The files are things like body_1.png or legs_5.png. The transparency is around the parts but not within them and the images are all grayscale. The parts are layering fine and I can get a grayscale avatar. I would like to be able to colorize these parts dynamically, but so far I'm not having good luck. I've tried converting the pixel data from RGB to HSL and using the original pixel's L value, while supplying the new color's H value, but the results are not great. I've looked at Colorize grayscale image but I can't seem to make what he's saying work in Java. I end up with an image that has fairly bright, neon colors everywhere. What I would like is for transparency to remain, while colorizing the grayscale part. The black outlines should still be black and the white highlight areas should still be white (I think). Does anyone have a good way to do this? EDIT: Here's an image I might be trying to color: Again, I want to maintain the brightness levels of the grayscale image (so the outlines stay dark, the gradients are visible, and white patches are white). I've been able to get a LookupOp working somewhat based on Colorizing images in Java but the colors always look drab and dark. Here's an example of my output: The color that was being used is this one (note the brightness difference): http://www.color-hex.com/color/b124e7 This is my lookupOp protected LookupOp createColorizeOp(short R1, short G1, short B1) { short[] alpha = new short[256]; short[] red = new short[256]; short[] green = new short[256]; short[] blue = new short[256]; //int Y = 0.3*R + 0.59*G + 0.11*B for (short i = 0; i < 30; i++) { alpha[i] = i; red[i] = i; green[i] = i; blue[i] = i; } for (short i = 30; i < 256; i++) { alpha[i] = i; red[i] = (short)Math.round((R1 + i*.3)/2); green[i] = (short)Math.round((G1 + i*.59)/2); blue[i] = (short)Math.round((B1 + i*.11)/2); } short[][] data = new short[][] { red, green, blue, alpha }; LookupTable lookupTable = new ShortLookupTable(0, data); return new LookupOp(lookupTable, null); } EDIT 2: I changed my LookupOp to use the following and got much nicer looking colors: red[i] = (short)((R1)*(float)i/255.0); green[i] = (short)((G1)*(float)i/255.0); blue[i] = (short)((B1)*(float)i/255.0); A: It seems what will work for you is something like this: for each pixel if pixel is white, black or transparent then leave it alone else apply desired H and S and make grayscale value the L convert new HSL back to RGB Edit: after seeing your images I have a couple of comments: It seems you want to special treat darker tones, since you are not colorizing anything below 30. Following the same logic, shouldn't you also exempt from colorizing the higher values? That will prevent the whites and near-whites from getting tinted with color. You should not be setting the alpha values along with RGB. The alpha value from the original image should always be preserved. Your lookup table algorithm should only affect RGB. While you say that you tried HSL, that is not in the code that you posted. You should do your colorizing in HSL, then convert the resulting colors to RGB for your lookup table as that will preserve the original brightness of the grayscale. Your lookup table creation could be something like this: short H = ??; // your favorite hue short S = ??; // your favorite saturation for (short i = 0; i < 256; i++) { if (i < 30 || i > 226) { red[i] = green[i] = blue[i] = i; // don't do alpha here } else { HSL_to_RGB(H, S, i, red[i], green[i], blue[i]) } } Note: you have to provide the HSL to RGB conversion function. See my answer on Colorize grayscale image for links to source code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: JQuery not sliding folder I am trying to get a iPhone looking folder menu bar. When i click each item (info tab_(number), it should open the appropriate "infotab_(number)_s" div. _s standing for "show". When one is open and the user click another item on the menu bar, it should close and open the one they clicked. My script doesn't open them, maybe I wrote something wrong. Here is my fiddle: http://jsfiddle.net/7FkqH/ So basically if I click the first li with id of infotab_one, It should slide down, info tab_one_s. If I click info tab_two, it should close infotab_one_s and open infotab_two_s. If that doesn't make sense I will clarify if needed. A: Here's a fiddle, i think this is what you intended. $('.infotab:visible').slideUp('fast'); In the code above you had sideDown and a callback function. The first time you click on a #nav_login_navigation li there's no visible .infotab's hence $('.infotab:visible').slideDown('fast', function() { will not run because no visible divs with class .infotab were found. Since you want previous visible divs to disappear you want slideUp instead and not slideDown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual studio 2005 debugging is very slow on windows7 When i debug apps on windows7 using VS 2005, it's very slow. just general slowness. works fine on xp. running outside of the debugger is normal. Even when i start apps outside the debugger then attach and debug it is normal. im running VS 2005 in Vista compatibility mode. Any idea what i can do to prevent slowness when debugging? A: Seems like the problem happens periodically and is related to the amount and location of breakpoints set in the debugger. The problem can be worked around by attaching to the process after starting it. For a complete solution, probably need vs2008.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery tmpl display loading image on images I have a template like so <script id="itemtemplate" type="text/x-jquery-tmpl"> <img id="photo${id}" src="${$item.image(filename)}" /> </script> which works nicely with displaying images but between the page loading and the image actually being displayed, I would like to have an ajax-loading animated gif. So my initial template would look like so <script id="itemtemplate" type="text/x-jquery-tmpl"> <img id="photo${id}" src="../../media/images/loadingsm.gif" /> </script> Now when the template gets fired, the src is replaced with ${$item.image(filename)}
{ "language": "en", "url": "https://stackoverflow.com/questions/7621788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parsing xml with jquery with conditional for attributes I was tryng to parse this xml: http://henriquebarone.animatubo.com/spider/jquery/teste.xml Writing this code: $(document).ready(function(){ $.ajax({ type: "GET", url: "teste.sif", dataType: "xml", success: Parser }); }); function Parser(sif) { $(sif).find('canvas').each(function(){ canvas_name = $(this).find('name').text(); $('<title>'+canvas_name+'</title>').appendTo('head'); canvas_width = $(this).attr('width'); canvas_height = $(this).attr('height'); $('<div id="canvas" style="width:'+canvas_width+'px; height:'+canvas_height+'px; border: solid 1px black; margin: 20px auto"></div>').appendTo('body'); $(this).find('layer').each(function(){ layer_type = $(this).attr('type'); if ( layer_type == 'import' ) { $(this).find('param').each(function(){ param_name = $(this).attr('name'); if ( param_name == 'filename' ) { file_name = $(this).find('string').text(); $('<div class="import" style="width:50px; height:50px; backgound-img: url('+file_name+')"').appendTo('#canvas'); } }); } }); }); } For each <layer> tag with the attribute type="import", I want to get its child <param> with the attribute name="filename", from which I want the text of the <string> tag. A: $(sif).find('layer[type="import"] param[name="filename"] string') should find what you want. I made a jsFiddle with an example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to apply Toggle method for another method? I have a script with jquery, and it is running but not as expected, I do not know where the location is wrong. <img onclick="$(this).click('toggle', function(){ $(this).animate({width : '1024px', height : '500px'}); },function(){ $(this).animate({width : '100px', height : '100px'}); });" class="magnify" src="a.jpg" border="1" alt="cantik_1" width="200" height="auto" /> A: try this <script language="javascript"> $(document).ready(function(){ $("#img1").toggle(function(){ $(this).animate({width : '1024px', height : '500px'}); },function(){ $(this).animate({width : '100px', height : '100px'}); }); }); </script> <img id="img1" class="magnify" src="a.jpg" border="1" alt="cantik_1" width="200" height="auto" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7621795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I sort an array of ints in cocoa? I'm brand new to programming on the Mac (i.e. xcode and cocoa) and I'm trying to simply perform a bubble sort and am having a lot of difficulty with this. The goal of this is to filter an image using a median filter by using a 9 pixel kernel. I take in the grey scale values of all nine pixels and then I'm trying to put them in a nine point array and sort the array to extract the median value of the nine (so it doesn't matter if I use ascending or descending). I've been trying to store the pixel values (which are ints) into a NSMutableArray but I really have no idea how to go about doing this or how to then sort them when the array is populated. // Perform median filter on all images in the stack for (x = 0; x < [curPix pwidth]; x++){ for (y = 0; y < [curPix pheight]; y++){ float value; int tLeft, tMid, tRight, cLeft, index, cRight, bLeft, bMid, bRight; // takes in pixel placement value = tLeft = tMid = tRight = cLeft = index = cRight = bLeft = bMid = bRight = 0; curPos = y * [curPix pwidth] + x; if (x != 0 && y != 0 && x != ([curPix pwidth]-1) && y != ([curPix pheight]-1)){ //Make kernel for median filter index = fImage[curPos]; // index pixel tLeft = fImage[index - [curPix pwidth] - 1]; // top left tMid = fImage[index - [curPix pwidth]]; // top middle tRight = fImage[index - [curPix pwidth] + 1]; // top right cLeft = fImage[index - 1]; // center left cRight = fImage[index + 1]; // center right bLeft = fImage[index + [curPix pwidth] - 1]; // bottom left bMid = fImage[index + [curPix pwidth]]; // bottom middle bRight = fImage[index + [curPix pwidth] + 1]; // bottom right // Need to make array, populate with pixels (above), and sort. // Once sorted, take median value, save it as 'value', and store it as new pixel value fImage[curPos] = (int) value; // return value to index } else { fImage[curPos] = fImage[curPos]; } } } A: How do I sort an array of ints in cocoa? int is a C type, so, the same way as in C. Mac OS X comes with a number of sort functions in the standard library. qsort, which is Quicksort, is defined by C; the others come, I think, from BSD. They're all under qsort's manpage. Each of the functions takes an array of pointer-sized elements, so you'll want to use long (or, for more portability, intptr_t), not int, for the elements. Make a C array of such elements, fill it out manually, then sort with one of these functions and find the median. A: To fill them into an NS(Mutable)Array you need to wrap your ints in instances of NSNumber, e.g.: NSMutableArray *myArray = [NSMutableArray array]; [myArray addObject:[NSNumber numberWithInt:42]]; There are various methods to sort the resulting array, to get you started: [myArray sortUsingSelector:@selector(compare:)]; Fortunately, this doesn't use BubbleSort. A: To begin with I would steer away from bubble sorts unless you are sorting a small sample. Bubble sort is very slow. Not being a cocoa expert I can't really help you very much other than suggesting you look into the built in array sorting routines. This is for the iphone but might help: http://www.iphonedevsdk.com/forum/iphone-sdk-development/61615-how-do-i-sort-30-000-objects.html Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fire window.onresize event? I am trying to fire the resize event on window programmatically: var evt = document.createEvent('HTMLEvents'); evt.initEvent('resize', true, false); window.dispatchEvent(evt); That unfortunately does not work. I am trying to make ExtJS library to do recalculations, and it uses DOM Level 3 events so I cannot just call window.onresize();. A: In case createEvent might get deprecated in favor of CustomEvent, here's a similar snippet using the CustomEvent API: var ev = new CustomEvent('resize'); //instantiate the resize event ev.initEvent('resize'); window.dispatchEvent(ev); // fire 'resize' event! A: Just in case anyone else needs this, in Extjs 4.1 you can do something typically inelegant... Ext.ComponentQuery.query('viewport')[0].doLayout(); No need for an id on the viewport - the .query('viewport') part is using the viewport's alias config. A: You are creating the wrong event. Resize is a UIEvent, read the specs here You need to do this: var evt = document.createEvent('UIEvents'); evt.initUIEvent('resize', true, false,window,0); window.dispatchEvent(evt); See it in action here: http://jsfiddle.net/9hsBA/
{ "language": "en", "url": "https://stackoverflow.com/questions/7621803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Destroy jScrollPane How to remove jScrollPane using destroy. Please can you give a simple example for the following code: $(document).ready(function() { $(".div1").jScrollPane(); }); <div class="div1">Some text...</div> A: To destroy an instance of jscrollpane (v2): var element = $('.div1').jScrollPane({}); var api = element.data('jsp'); api.destroy(); A: The old jScrollPaneRemove() function looked something like this: $.fn.jScrollPaneRemove = function() { $(this).each(function() { $this = $(this); var $c = $this.parent(); if ($c.is('.jScrollPaneContainer')) { $this.css( { 'top':'', 'height':'', 'width':'', 'padding':'', 'overflow':'', 'position':'' } ); $this.attr('style', $this.data('originalStyleTag')); $c.after($this).remove(); } }); } As you can see this removes the css, or rather sets it to nothing, and resets the style tag to the original styles. The problem is that originalStyleTag is also removed, but it used to look something like this: $this.data('originalStyleTag', $this.attr('style')); So it's basicly a way to store the old styles before jScrollPane is activated and reapplying them when jScrollPane is removed. A lot has changed in the new version, and I don't know if this method still works, but it looks like the way to do it is to store the old styles before running jScrollPane, zero out any css set by jScrollPane, and set the css bak to the old styles to make it like it was before jScrollPane. Sounds like a lot to do, and I would seriously consider trying jQuery's remove, empty, detach or anything else on the different containers assocciated with jScrollPane, and if all else fails try to make the above function work in your script. All you really need to do is get the old styles in a data array before running jScrollpane, and then see if the old remove function still works. A: You need to call jScrollPaneRemove() on the container i.e. $('.myownscrollpane').jScrollPaneRemove();
{ "language": "en", "url": "https://stackoverflow.com/questions/7621805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: An error occurred during the compilation of a resource required to service this request What this means? Server Error in '/' Application. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: The compiler failed with error code -1073741502. Show Detailed Compiler Output: c:\windows\system32\inetsrv> "C:\Windows\Microsoft.NET\Framework64\v3.5\csc.exe" /t:library /utf8output /R:"C:\Windows\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\b5d50123\4baf1c64_5780cc01\Tooltip.DLL" /R:"C:\Windows\assembly\GAC_64\System.Web\2.0.0.0__b03f5f7f11d50a3a\System.Web.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.IdentityModel\3.0.0.0__b77a5c561934e089\System.IdentityModel.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\f75ac7b7\30b20097_5480cc01\AjaxControlToolkit.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\853f18ae\b26243f5_d1d5cb01\Masterworks.Controls.Web.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\e43c5d29\51c72b28_6c74cb01\Iesi.Collections.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\911b5b42\18ea1580_6a5ecb01\Masterworks.SqlLocalization.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\a8b3bdef\4ebfce7e_6a5ecb01\Masterworks.Cryptography.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\c2317027\e86fb4e0_d341cb01\Microsoft.Practices.Web.UI.WebControls.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Xml.Linq\3.5.0.0__b77a5c561934e089\System.Xml.Linq.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\48bac770\1e6c3a24_5880cc01\FoodOrder.Shell.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\d06c67e9\efbee87f_6a5ecb01\Masterworks.Controls.Web.SecurityControls.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Web.Services\2.0.0.0__b03f5f7f11d50a3a\System.Web.Services.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.WorkflowServices\3.5.0.0__31bf3856ad364e35\System.WorkflowServices.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_GlobalResources.xw29jesx.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\53cb1bdc\1860c5e0_d341cb01\Microsoft.Practices.ObjectBuilder.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\1be16282\5915bd22_5880cc01\FoodOrder.Core.DLL" /R:"C:\Windows\assembly\GAC_64\System.EnterpriseServices\2.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.ServiceModel.Web\3.5.0.0__31bf3856ad364e35\System.ServiceModel.Web.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_global.asax.u95mrm-a.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\a1f2870f\1ecff82b_da21cb01\CSSFriendly.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\6d6af5ce\851e6028_6c74cb01\NHibernate.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\4ada28a5\5b97a426_5880cc01\FoodOrder.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\64acacfd\041c067a_6c5ecb01\Masterworks.WebControlCaptcha.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\34f09ef4\a0b2a524_5880cc01\FoodOrder.Notifications.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\02ba03eb\95a66223_5880cc01\FoodOrder.Data.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_Web_swohbrqr.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\24789032\78d4bce0_d341cb01\Microsoft.Practices.EnterpriseLibrary.Common.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\715b874b\ae4aa563_8186cb01\DayPilot.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\mscorlib.dll" /R:"C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Drawing\2.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\19b1cd66\ba096a28_6c74cb01\Castle.DynamicProxy2.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\aaf304a9\71a232e1_d341cb01\ManagedFusion.Rewriter.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\78131b2d\8b852f5f_695ecb01\Masterworks.Buttons.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\b24420c4\dbd4fc7e_6a5ecb01\Masterworks.ConfirmButtons.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\de089f2d\3d9d9f14_d544cb01\FredCK.FCKeditorV2.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\c9f50bf2\43a75d21_5880cc01\ProjectBase.Data.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\60b92aa4\cdb55928_6c74cb01\log4net.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\a1581848\8e7dcf0b_7ad6cb01\Masterworks.Controls.Web.Validators.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Core\3.5.0.0__b77a5c561934e089\System.Core.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\11e54d93\e5ef9b28_6c74cb01\Antlr3.Runtime.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\a645b2ed\98baed28_6c74cb01\FluentNHibernate.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\f900ae16\b247c823_5880cc01\FoodOrder.Lib.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Web.Extensions.Design\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.Design.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\3e6c6fbf\ed7db520_5880cc01\ProjectBase.Utils.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Design\2.0.0.0__b03f5f7f11d50a3a\System.Design.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\1d165978\15481a25_5880cc01\FoodOrder.RestaurantModule.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\2b037192\e32e44e1_d341cb01\PostBackRitalin.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Web.Extensions\3.5.0.0__31bf3856ad364e35\System.Web.Extensions.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\c47bde74\1f6ad8c0_3984cb01\NHibernate.Linq.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\344c2531\5b4ffb28_6c74cb01\Castle.Core.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.ServiceModel\3.0.0.0__b77a5c561934e089\System.ServiceModel.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\0f060aeb\8eeca628_6c74cb01\NHibernate.ByteCode.Castle.DLL" /R:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\assembly\dl3\699a6c99\5909df08_7ad6cb01\Masterworks.Utilities.DnsQuery.DLL" /R:"C:\Windows\assembly\GAC_MSIL\System.Data.DataSetExtensions\3.5.0.0__b77a5c561934e089\System.Data.DataSetExtensions.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Xml\2.0.0.0__b77a5c561934e089\System.Xml.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Windows.Forms\2.0.0.0__b77a5c561934e089\System.Windows.Forms.dll" /R:"C:\Windows\assembly\GAC_MSIL\System.Runtime.Serialization\3.0.0.0__b77a5c561934e089\System.Runtime.Serialization.dll" /out:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_Web_search.master.7371103c.wkrdmiw6.dll" /D:DEBUG /debug+ /optimize- /win32res:"C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\7oevkkzx.res" /w:4 /nowarn:1659;1699;1701 /warnaserror- "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_Web_search.master.7371103c.wkrdmiw6.0.cs" "C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\85135762\a89acdb6\App_Web_search.master.7371103c.wkrdmiw6.1.cs" Version Information: Microsoft .NET Framework Version:2.0.50727.5446; ASP.NET Version:2.0.50727.5420 A: I faced the same error, it got resolved by below steps: 1) Remove ASP.Net Temporary files (C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files) 2)Clean and rebuild the solution. Make sure you set the StartUp Project in your project in solution explorer. A: In my case, I just restart application pool (stop and start). And it works! A: I had created a new Web API project in Visual Studio 2017 and published to an IIS-hosted server which only supports C#6 and .NET Framework 4.5.1. The project had the Nuget package Microsoft.Net.Compilers at version 2.6.1 which in its description says: Referencing this package will cause the project to be built using the specific version of the C# and Visual Basic compilers contained in the package, as opposed to any system installed version. This package can be used to compile code targeting any platform, but can only be run using the desktop .NET 4.6+ Full Framework. I suppose I could have tried downgrading the Nuget package alone but I chose to create the project in Visual Studio 2015 instead, which used version 1.0.0 of this package, among changes to other Nuget packages, resulting in a successful build on the server. A: It means you tried opening a web page and when asp.net tried to compile on the fly as it does it couldn't build the solution. You have a build error or you need to rebuild the solution. Open the solution in Visual Studio and try to build it. If it has compile errors fix them until you can build it then try to browse to it again. A: You have to right click on c:\windows\Temp and modify the authorizations of the IIS_IUSRS account by adding Modify, read execute, write... A: Right click on Solution Explorer -> Clean Solution Then Rebuild Solution A: I got this error when I upgraded NuGet packages. I had to manually remove the packages folder and then manually select Restore NuGet Packages for the solution. Then everything started working again. A: Check your web.config like namespace "...."
{ "language": "en", "url": "https://stackoverflow.com/questions/7621809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Hibernate parent/child relationship. Why is object saved twice? I am looking into Hibernate's parent/child relationships. I have 3 entities Employee Customers and Orders. Their relationship is Employee 1 <-> N Orders Customer 1 <-> N Orders I want to be able to save/update/delete Customer objects and Employees and Orders but I want to use some interface so that the calling code does not deal with any Hibernate or JPA stuff. E.g. I tried something like the following: class Utils{ public static void saveObject(Object o){ logger.debug(o.toString()); Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); session.save(o); tx.commit(); session.close(); } } and in the calling code I do: Employee employee = new Employee(); //set data on employee Customer customer = new Customer(); //set data on customer Order order = new Order(); //set data on order employee.addOrder(order);//this adds order to its list, order gets a reference of employee as parent customer.addOrder(order);//this adds order to its list, order gets a reference of customer as parent Utils.saveObject(customer); Utils.saveObject(employee); Now I noticed that with this code, 2 records of employee are created instead of 1. If I only do: Utils.saveObject(customer); Only 1 (correctly) record is created. Why does this happen? Does this happens because the same Order object is saved by both Customer and Employee? And the cascade="all" makes this side-effect? Now if I do not use the DBUtils method and do directly: Session session = DBUtil.getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); session.save(employee); session.save(customer); tx.commit(); session.close(); Again, it works as expected. I.e. only 1 employee record is created. What am I doing something wrong here? UPDATE: Hibernate mappings: <hibernate-mapping> <class name="database.entities.Associate" table="EMPLOYEE"> <id name="assosiateId" type="java.lang.Long"> <column name="EMPLOYEEID" /> <generator class="identity" /> </id> <property name="firstName" type="java.lang.String" not-null="true"> <column name="FIRSTNAME" /> </property> <property name="lastName" type="java.lang.String" not-null="true"> <column name="LASTNAME" /> </property> <property name="userName" type="java.lang.String" not-null="true"> <column name="USERNAME" /> </property> <property name="password" type="java.lang.String" not-null="true"> <column name="PASSWORD" /> </property> <set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true"> <key> <column name="EMPLOYEEID" /> </key> <one-to-many class="database.entities.Order" /> </set> </class> </hibernate-mapping> <hibernate-mapping> <class name="database.entities.Customer" table="CUSTOMER"> <id name="customerId" type="java.lang.Long"> <column name="CUSTOMERID" /> <generator class="identity" /> </id> <property name="customerName" type="java.lang.String"> <column name="CUSTOMERNAME" /> </property> <set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true"> <key> <column name="CUSTOMERID" /> </key> <one-to-many class="database.entities.Order" /> </set> </class> </hibernate-mapping> <hibernate-mapping> <class name="database.entities.Order" table="ORDERS"> <id name="orderId" type="java.lang.Long"> <column name="ORDERID" /> <generator class="identity" /> </id> <property name="orderDate" type="java.util.Date"> <column name="ORDERDATE" /> </property> <property name="quantity" type="java.lang.Integer"> <column name="QUANTITY" /> </property> <property name="quantityMargin" type="java.lang.Long"> <column name="QUANTITYMARGIN" /> </property> <property name="port" type="java.lang.String"> <column name="PORT" /> </property> <property name="orderState" type="java.lang.String"> <column name="ORDERSTATE" /> </property> <many-to-one name="customer" class="database.entities.Customer" cascade="all" fetch="join"> <column name="CUSTOMERID" /> </many-to-one> <many-to-one name="associate" column="EMPLOYEEID" class="database.entities.Employee" cascade="all" fetch="join"> </many-to-one> </class> </hibernate-mapping> UDATE 2: class Employee{ //Various members Set<Order> orders = new HashSet<Order>(); public void addOrder(Order order){ order.setEmployee(this); orders.add(order); } } Also: class Customer{ //Various members Set<Order> orders = new HashSet<Order>(); public void addOrder(Order order){ order.setCustomer(this); orders.add(order); } } A: It seems to me that in the DBUtils code, you are wrapping both saves in an outer transaction, whereas in the Utils code, you have them in two completely separate transactions without an outer one. Depending on your cascading, Hibernate has to figure out which objects need to be saved. When you run the Utils code, with two separate transactions, it will save the Order first. Since you're cascading all, this means it will save the Order first, then the Customer. However, you've created the SAME Order for both the Customer and Employee. Therefore, the Employee also gets saved in the first transaction (due to cascading). The second transaction, since it is separate, will not be aware of this and save another Employee. On the other hand, if you wrap them in an outer transaction, Hibernate can figure out the identities of all the objects and save them properly. A: try saving only Order instead of saving Employee and Customer separately. With your existing cascade=all setting both parent object will get saved without creating any duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web Printing Multiple Printers I'm building a web application that is primarily ASP.NET MVC / Javascript. The application needs to be able to print certain content to a label printer and other content to a standard printer. I'd prefer for the user to be able to select a default printer for each one rather than having to always explicitly select a printer. Is there a way to save and reload some sort of default printer settings for multiple printers in such an application. I am also open to using Silverlight for the p;rinting features if there is no way to do it via javascript. A: Not via JavaScript, no; JS uses the browser's built-in print mechanism, which in turn defers to the OS's default print mechanism. A: I know its been 6 years since this question was posted but since it wasn't answered here is what I believe is the best way to solve this issue. You still cannot manipulate printers from a web browser, but there is a great choice out there called QZ Tray You have to install a program that will communicate between javascript from your application and your configured printers, allowing you to send RAW printing commands and also HTML to any printer. You can also print to multiple printers at once and save all printer configuration and parameters inside your web app, so you have full control over your printers. A: Browsers do not allow javascript (or any script) to access information about the available set of printers or offer any means to select even a "prefered" printer. Simliarly Silverlight does not support access to infomation about the set of printers available and does not allow printing API to select a specific printer to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JavaMonkey Canvas I've been trying to get Java monkey engine-3 to render to a canvas/panel object so it can be embedded in a GUI. I'm sure this must be possible but searching around every program i can find just extends the simpleapplication class. Any advice on how to do this? Even just a link to some good examples or documentation would be nice. I don't really need anything as powerful as Java monkey to render out a few cubes spheres and the like in 3D so if anyone wants to suggest a more appropriate, simpler alternative that would be nice too. A: There's a tutorial in their documentation: http://jmonkeyengine.org/wiki/doku.php/jme3:advanced:swing_canvas
{ "language": "en", "url": "https://stackoverflow.com/questions/7621815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ 'AND' evaluation - standard guaranteed? Possible Duplicate: Safety concerns about short circuit evaluation What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false? E.g.: Foo* p; //.... if ( p && p->f() ) { //do something } is the f() guaranteed not to be called if p == NULL? Also, is the order of evaluation guaranteed to be the order of appearence in the clause? Might the optimizer change something like: int x; Foo* p; //... if ( p->doSomethingReallyExpensive() && x == 3 ) { //.... } to a form where it evaluates x==3 first? Or will it always execute the really expensive function first? I know that on most compilers (probably all) evaluation stops after the first false is encountered, but what does the standard say about it? A: What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false? Yes. That is called short-circuiting. Also, is the order of evaluation guaranteed to be the order of appearence in the clause? Yes. From left to right. The operand before which the expression short-circuited doesn't get evaluated. int a = 0; int b = 10; if ( a != 0 && (b=100)) {} cout << b << endl; //prints 10, not 100 In fact, the above two points are the keypoint in my solution here: * *Find maximum of three number in C without using conditional statement and ternary operator A: In the ANSI C standard 3.3.13: Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated. There is an equivalent statement in the C++ standard A: && (and ||) establish sequence points. So the expression on the left-hand side will get evaluated before the right-hand side. Also, yes, if the left-hand side is false/true (for &&/||), the right-hand side is not evaluated. A: What does the standard say about evaluating && expressions - does it guarantee that evaluation of parameters will stop at the first false? Also, is the order of evaluation guaranteed to be the order of appearence in the clause? 5.14/1. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false. This only works for the standard && operator, user defined overloads of operator && don't have this guarantee, they behave like regular function call semantics. Might the optimizer change something like: if ( p->doSomethingReallyExpensive() && x == 3 ) to a form where it evaluates x==3 first? An optimizer may decide to evaluate x == 3 first since it is an expression with no side-effects associated if x is not modified by p->doSomethingReallyExpensive(), or even evaluate it after p->doSomethingReallyExpensive() already returned false. However, the visible behavior is guaranteed to be the previously specified: Left to right evaluation and short-circuit. That means that while x == 3 may be evaluated first and return false the implementation still has to evaluate p->doSomethingReallyExpensive().
{ "language": "en", "url": "https://stackoverflow.com/questions/7621817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java regex patterns I need help with this matter. Look at the following regex: Pattern pattern = Pattern.compile("[A-Za-z]+(\\-[A-Za-z]+)"); Matcher matcher = pattern.matcher(s1); I want to look for words like this: "home-made", "aaaa-bbb" and not "aaa - bbb", but not "aaa--aa--aaa". Basically, I want the following: word - hyphen - word. It is working for everything, except this pattern will pass: "aaa--aaa--aaa" and shouldn't. What regex will work for this pattern? A: Can can remove the backslash from your expression: "[A-Za-z]+-[A-Za-z]+" The following code should work then Pattern pattern = Pattern.compile("[A-Za-z]+-[A-Za-z]+"); Matcher matcher = pattern.matcher("aaa-bbb"); match = matcher.matches(); Note that you can use Matcher.matches() instead of Matcher.find() in order to check the complete string for a match. If instead you want to look inside a string using Matcher.find() you can use the expression "(^|\\s)[A-Za-z]+-[A-Za-z]+(\\s|$)" but note that then only words separated by whitespace will be found (i.e. no words like aaa-bbb.). To capture also this case you can then use lookbehinds and lookaheads: "(?<![A-Za-z-])[A-Za-z]+-[A-Za-z]+(?![A-Za-z-])" which will read (?<![A-Za-z-]) // before the match there must not be and A-Z or - [A-Za-z]+ // the match itself consists of one or more A-Z - // followed by a - [A-Za-z]+ // followed by one or more A-Z (?![A-Za-z-]) // but afterwards not by any A-Z or - An example: Pattern pattern = Pattern.compile("(?<![A-Za-z-])[A-Za-z]+-[A-Za-z]+(?![A-Za-z-])"); Matcher matcher = pattern.matcher("It is home-made."); if (matcher.find()) { System.out.println(matcher.group()); // => home-made } A: Actually I can't reproduce the problem mentioned with your expression, if I use single words in the String. As cleared up with the discussion in the comments though, the String s contains a whole sentence to be first tokenised in words and then matched or not. import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegExp { private static void match(String s) { Pattern pattern = Pattern.compile("[A-Za-z]+(\\-[A-Za-z]+)"); Matcher matcher = pattern.matcher(s); if (matcher.matches()) { System.out.println("'" + s + "' match"); } else { System.out.println("'" + s + "' doesn't match"); } } /** * @param args */ public static void main(String[] args) { match(" -home-made"); match("home-made"); match("aaaa-bbb"); match("aaa - bbb"); match("aaa--aa--aaa"); match("home--home-home"); } } The output is: ' -home-made' doesn't match 'home-made' match 'aaaa-bbb' match 'aaa - bbb' doesn't match 'aaa--aa--aaa' doesn't match 'home--home-home' doesn't match
{ "language": "en", "url": "https://stackoverflow.com/questions/7621821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access local files through Google chrome extension? I need to load a list of names into my google chrome extension from a local file, How can this be done? what if the file is shipped with the extension itself? A: If this file is shipped with your extension then you can just load it with XMLHttpRequest inside background page (use relative paths, with / being extension root folder). You can also make your file to be javascript (var config=[...]) and just load it with <script> into background page. A: Say your json file is names.json in the following folder -- manifest.json -- config |-- names.json In manifest.json add path to the resource "web_accessible_resources": [ "config/names.json" ] Use fectch() API to access the resource const url = chrome.runtime.getURL('./config/names.json'); fetch(url) .then( function(response) { if (response.status !== 200) { console.log('Looks like there was a problem. Status Code: ' + response.status); return; } // Examine the text in the response response.json().then(function(data) { console.log(data); }); } ) .catch(function(err) { console.log('Fetch Error :-S', err); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Framework for CSS in Rails 3.1 Which framework do you use in Rails 3.1? I basically want to have a standard set of mixins like gradient and rounded corner etc, but maybe there are other advantages of certain frameworks that I am not aware of. Can you please recommend a framework to use with Rails 3.1 to cover most of what I will need to simplify and standardize my stylesheet development A: Bourbon - a set of Sass mixins using SCSS syntax, is a popular (500+ watchers) tool made by thoughtbot. The purpose of Bourbon Sass Mixins is to provide a comprehensive library of sass mixins that are designed to be as vanilla as possible, meaning they should not deter from the original CSS syntax. The mixins contain vendor specific prefixes for all CSS3 properties for support amongst modern browsers. The prefixes also ensure graceful degradation for older browsers that support only CSS3 prefixed properties. Bourbon uses SCSS syntax. It can help with use: * *Animation *Background-image *Border Radius *Box Shadow *Box Sizing and other See the readme on the official page on github A: I think that any current CSS framework can accomplish what you want. Have you give LESS a look? I believe it meets all your criteria. I haven't personally tried out compass, but it's been generating alot of buzz, so it is certainly worth a look. Twitter also released Bootstrap which I've been trying out and I've been fairly impressed so far! A: For me, a framework doesn't seem to be to be considered here. You can easaly do it yourself. For my part, I use sass and I write a _macros.scss with all the appropriate mixins and default variables, and I put an @import "macros" at the beginning of each main scss files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Architecture more suitable for web apps than MVC? I've been learning Zend and its MVC application structure for my new job, and found that working with it just bothered me for reasons I couldn't quite put my finger on. Then during the course of my studies I came across articles such as MVC: No Silver Bullet and this podcast on the topic of MVC and web applications. The guy in the podcast made a very good case against MVC as a web application architecture and nailed a lot of what was bugging me on the head. However, the question remains, if MVC isn't really a good fit for web applications, what is? A: From my experience, the benefits you get from an MVC architecture far outweighs its costs and apparent overhead when developing for the web. For someone starting out with a complex MVC framework, it can be a little daunting to make the extra effort of separating the three layers, and getting a good feel as to what belongs where (some things are obvious, others can be quite border-line and tend to be good topics of discussion). I think this cost pays for itself in the long run, especially if you're expecting your application to grow or to be maintained over a reasonable period of time. I've had situations where the cost of creating a new API to allow other clients to connect to an existing web application was extremely low, due to good separation of the layers: the business logic wasn't at all connected to the presentation, so it was cake. In the current MVC framework eco-system I believe your mileage may vary greatly, since the principles are common, but there are alot of differences between, for instance, Zend, Django, RoR and SpringMVC. If there are truly other good alternatives to this paradigm out there... I'm quite interested in the answers! Sorry for the slight wall of text! A: It all depends on your coding style. Here's the secret: It is impossible to write classical MVC in PHP. Any framework which claims you can is lying to you. The reality is that frameworks themselves cannot even implement MVC -- your code can. But that's not as good a marketing pitch, I guess. To implement a classical MVC it would require for you to have persistent Models to begin with. Additionally, Model should inform View about the changes (observer pattern), which too is impossible in your vanilla PHP page (you can do something close to classical MVC, if you use sockets, but that's impractical for real website). In web development you actually have 4 other MVC-inspired solutions: * *Model2 MVC: View is requesting data from the Model and then deciding how to render it and which templates to use. Controller is responsible for changing the state of both View and Model. *MVVM: Controller is swapped out for a ViewModel, which is responsible for the translation between View's expectations and Models's logic. View requests data from controller, which translates the request so that Model can understand it. Most often you would use this when you have no control over either views or the model layer. *MVP (what php frameworks call "MVC"): Presenter requests information from Model, collects it, modifies it, and passes it to the passive View. To explore this pattern, I would recommend for you begin with this publication. It will explain it in detail. *HMVC (or PAC): differs from Model2 with ability of a controller to execute sub-controllers. Each with own triad of M, V and C. You gain modularity and maintainability, but pay with some hit in performance. Anyway. The bottom line is: you haven't really used MVC. But if you are sick of all the MVC-like structures, you can look into: * *event driven architectures *n-Tier architecture And then there is always the DCI paradigm, but it has some issues when applied to PHP (you cannot cast to a class in PHP .. not without ugly hacks). A: I think it would depend on what you're trying to do, personally. Magenta uses MVC pretty successfully, and it makes it fairly easy to add new functionality or modify existing. Of course if you're trying to make something fairly simple, going with an MVC architecture could be overkill. A: It's all preference. I have worked with old structures like XTemplates and Smarty and have now moved on to Codeigniter and Kohona. I like them very much and they work very well for everything I do on the web. For phone applications I can set up controllers for the functions that are needed to do it's data pulls as well. Working both in the Linux world and Windows World, for building ASP.NET Web Sites I don't see other way of building websites beside using MVC. Web Applications Projects in Visual Studio are still used but I prefer not to anymore. MVC Projects via Visual Studio is so easy to use and set up. You can right click on your controller methods and create views automatically. In every structure there is a good and bad but it's up to the developer to use whatever meets their needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: How would you receive a file sent with 'sendfile'? I'm trying to implement a basic file server. I have been trying to use the sendfile command found here: http://linux.die.net/man/2/sendfile I'm using TCP. I can have it send fine, but its sending in binary and I'm not sure if thats the hang up. I am trying to receive the file with recv, but it isn't coming through correctly. Is there a special way to receive a binary file, and put it into a string? EDIT: Asked to supply some code, here it is: SENDFILE Call (from Server process) FILE * file = fopen(filename,"rb"); if ( file != NULL) { /*FILE EXISITS*/ //Get file size (which is why we opened in binary) fseek(file, 0L, SEEK_END); int sz = ftell(file); fseek(file,0L,SEEK_SET); //Send the file sendfile(fd,(int)file,0,sz); //Cleanup fclose(file); } RECIEVE Call (from Client process, even more basic than a loop, just want a single letter) //recieve file char fileBuffer[1000]; recv(sockfd,fileBuffer,1,0); fprintf(stderr,"\nContents:\n"); fprintf(stderr,"%c",fileBuffer[0]); EDIT: wrote some code for checking return values. sendfile is giving errno 9 - bad file number. Which im assuming is at my second file descriptor in the call (the one for the file i'm sending). I cast it as an int because sendfile was complaining it wasn't an int. How should I use send file given the file pointer code I have used above in th sendfile call? A: You cannot use sendfile() with a FILE*, you need a file descriptor as given by open(), close() and friends. You cannot just cast a FILE* into an int and thinking it would work. Maybe you should read the sendfile() manpage for more information. A: There is no special way. You just receive with read() or recv(). Probably, you've got your receiving code wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Facebook iOS Application Cannot Log In On Device This is a very frustrating issue. The DemoApp project from the iOS SDK from Facebook works just fine on the simulator but when I put it on the device it won't get past the log in page. The only changes made to the code were: 1) Replaced the appID in the view controller 2) Replaced the appID in the Info plist The application compiles and opens on the device. The login button switches to a Facebook titled window with a Cancel button in the upper right corner. The window has a large blue Log In button at the bottom. Clicking on the Log In button redirects to the same window. This is the only Facebook iOS app on the device. I deleted the others. Also, the fbDidNotLogin() method is never called. There have been several other posts about this issue but the solutions didn't seem to work in this case. Is this enough information to see what is happening? Do I need to build the application for a different target? This is very confusing. Thanks for your help! A: Found it! In Facebook.m is the following line of code: [self authorizeWithFBAppAuth:YES safariAuth:YES]; The iOS SDK will try to use the Facebook application on the device. Setting authorizeWithFBAppAuth to NO will launch Safari and that works. A: 1) Replaced the appID in the view controller 2) Replaced the appID in the Info plist You should set "iOS Bundle ID" in application settings too. this is checked before authorization. hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7621841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't get UILabel to show properly on top of UITableView I am struggling to achieve what I thought was nothing but a 1' coding but apparently adding a UILabel above my UITableView in a UITableViewController is not a piece of cake...? Here is the code (yes basic, I know): UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 310, 20)]; [[self tableView] addSubview:label]; The result can be seen in the screenshot below, the label on the top right is just half displayed, saying "Balance..." Please note that if I try to change CGRect origin.y or size.height the UILabel is not displayed at all. I also tried adding the following, with no change in result: [[self tableView] bringSubviewToFront:balanceLabel]; I don't care if the UILabel is scrolled up when scrolling up the UITableView, I want it to stick with the first section header. I know this can be achieved in other ways, using a custom UIView for the header, changing to UIViewController or using a .xib, but really I would like to understand why this happens. Thanks for any help. F. A: It does look like the header is hiding your label, maybe you could try setting the header background to clearColor. Since you have no control on the table view loop I suspect that after your addSubView somewhere the table builds its own header and does another addSubView.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using JQuery for CSS vs Stylesheet Because I like keeping all source code in one file (per class), I decided to add all style and CSS using JQuery objects, i.e: jquery : $('<div/>', { id:'Object', css:{ height:'100%', width:'69%', color:'white', fontWeight:'bold', textAlign:'center', backgroundColor:'#02297f', marginLeft:'.5%', 'float':'left', overflow:'auto', borderRadius:'5px' }, html : 'My JQuery Object' }), Now I know there is probably going to be some sort of performance impact, but my question is how much? Does anyone else do it this way? Am I overlooking a potential problem? I like it this way because I can just use objects rather than having to cross examine a stylesheet and it keeps it better organized. EDIT: This is for a Javascript application, not a web page. So disabling the Javascript will kill the webpage anyway. A: There is certainly a performance impact. The script is only run when all the page is loaded, so it will give you problems when the page is first displayed. Apart from that, you got no styling at all when you run a browser where javascript is disabled. But most of all, it is a Bad Idea. CSS is for styling, for the looks of your page. HTML is for structure, and Javascript is for logic, interactivity. I think you shouldn't use the .css method at all. If you need to toggle styles in Javascript, use classes instead, which can then be styled using style sheets. But this method of yours takes it a step further even. I think it's even worse than putting all the css in inline style attributes. I hope you are just asking this question to see how people respond. It must not be serious. :s A: Your are doing it wrong. CSS must stay in *.css files and Javascript in the *.js files. There is this thing known as 3 layers of Web: * *content ( HTML ) *presentation ( CSS ) *behavior ( JS ) First of all, yes, if you use JS to generate html and style it, this would have a huge impact on performance. But even ignoring it : you would make the code virtually unmaintainable. If you want to have better organized stylesheets, then invest some time in expanding your knowledge in CSS, and looks at practices behind OOCSS. A: Thats a TERRIBLE IDEA! Use instead http://xcss.antpaw.org/ A: I agree with the way you're doing it. I essentially use it myself. I am developing a html5 game and in that context what you are doing makes sense. In games, user events and system events constantly change the screen. You can only realistically deal with this via just-in-time styling. So using .css() is a great way to do this. I think in a game that sprites are so distinct that they require their own style object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: C# Garbage collection Say we have: public void foo() { someRefType test = new someRefType (); test = new someRefType (); } What does the garbage collector do with the first heap object? Is it immediately garbage collected before the new assignment? What is the general mechanism? A: No, there is nothing that says that the object is immediately collected. In fact, it is quite unlikely that it is. It will be collected eventually by the garbage collector, but you can't know exactly when. You can force a collection by calling GC.Collect, although this is normally not recommended. Exactly how the garbage collection works is a fairly large subject, but there is great documentation you can read on MSDN. A: What does the garbage collector do with the first heap object? Who knows? It's not deterministic. Think of it like this: on a system with infinite memory, the garbage collector doesn't have to do anything. And you might think that's a bad example, but that's what the garbage collector is simulating for you: a system with infinite memory. Because on a system with sufficiently more memory available than required by your program, the garbage collector never has to run. Consequently, your program can not make any assumptions about when memory will (if ever) be collected. So, the answer to your question is: we don't know. Is it immediately garbage collected before the new assignment? No. The garbage collector is not deterministic. You have no idea when it will collect and release garbage. You can not make any assumptions about when garbage will be collected or when finalizers will run. In fact, it's very unlikely it's collected so quickly (that would make collections happen too frequently). Additionally, on a system with sufficient memory, the garbage collector never has to run. What is the general mechanism? That's a fairly broad question. But the underlying principle is very simple: a garbage collector simulates a machine with infinite memory. To do this, it somehow keeps track of memory and is able to determine when memory is garbage. When it sees fit, due to its need to simulate infinite memory, it will from time to time collect this garbage and make it available for allocation again. A: There are numerous different strategies for garbage collection and they have gotten more sophisticated and more efficient over the years. There's lots of excellent resources in the literature and on the web that talk about them. But I also find sometimes an imperfect and colorful metaphor gives me an intuition that helps me get started. So allow me to try: .NET has a so-called "generational" garbage collector and I think of it as behaving I lot like I do myself. I let dirty clothes and mail ("C# objects") pile up all over my living room floor ("memory") over a period of several days and when I find that I can't see the carpet any more ("memory full") I spend some time cleaning up ("garbage collecting") the living room ("generation 0"), throwing away the objects that aren't needed any more ("no longer reachable") and moving the remaining ones to my bedroom ("generation 1"). Quite often this buys me some time and I don't need to do any more work. But when my bedroom fills up I do something similar, throwing away some objects and moving the others to my basement ("generation 2"). Occasionally even the basement fills up and then I have I real problem and need to do some major spring cleaning ("full collection"). Applying this metaphor to your example, we might guess that the first piece of trash ("heap object") just sits around until I get around to picking it up ("run the generation 0 collector") which happens when I feel like it, when the floor gets completely covered, or maybe never :-) A: To see when the objects are being deleted, you can override the finalize method in your class to print when and what objects are being deleted, like in this sample below: class MyClass { private int _id; public MyClass(int id) { _id = id; } ~MyClass() { Console.WriteLine("Object " + _id + " deleted at " + DateTime.Now + " ."); } } class Program { static void Main(string[] args) { MyClass p1 = new MyClass(1); p1 = new MyClass(2); Console.ReadKey(); } } To force the garbage collector to free this objects faster, you could add a field to them as a long array, something like private int []memory; and in the constructor: memory=new int[10000000].
{ "language": "en", "url": "https://stackoverflow.com/questions/7621848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the best way to build php from source CentOS I am building php from source on a new CentOS box and as usual I have to wrangle up all the various configuration options I might need. This gets tricky because there are various extensions that I want and certain options that I always for get to put in the .configure script. Not only that but PHP 5.3 has has different defaults for various options. Is there an interactive or annotated version of the configure script somewhere or a good set of defaults to reference? Thanks! A: Grab the existing PHP SRPM, update the spec with the new version, release, and tarball, and rebuild.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reusing jQuery Code ? I have some jQuery Code, which I am planning to use in many pages in my asp.net web form application. Example: Create User using jQuery dialog box code. In Asp.net we employ a user control to reuse the same piece of code over and over. Any ideas on how can I reuse jQuery code? A: Typically you put the code in an external .js file and use <script src="my/path/to/jsfile.js" type="text/javascript"></script> in every page you are using the javascript in. (or you can place it in your master template). (moved from comment due to the fact that this... is not a comment :P) A: Typically, when I work with more complex applications there are a few common patterns I usually follow with my jQuery code. To handle the problem with scattered JavaScript code all over the code base I try to package as much as possible in jQuery plugins and put some effort into making them as generic as possible. You can find a lot of tips on designing jQuery plugins from this NDC 2011 talk. When designing more JavaScript framework like applications with less jQuery and more plain old JavaScript, I try to partition my code in different files by feature. I use a packaging tool like AjaxMin to merge and minify the framework into as single deliverable JavaScript-file. A: I'm not sure I get it either: if you mean that your experience with jQuery is that it's run at document ready, it might just be the examples you've found. In that case, dotweb's comment provides the answer. If you mean you're not sure how to get that code into other pages without dumping it into a script tag via copy/paste, Joseph has the answer. For the sake of contributing something new, here's a fairly typical way of doing it which takes into account both of the above: Create (and include, as per Joseph) one or more external JS files that constitute what you think of as the JS components of your application. "myApp.js" or whatever. Inside this file, you can use an object to store all of your functions (as per dotweb). This gives it a safe namespace and provides a quasi-global way to access functions and variables. Not actually 'global' in the document sense of the word, but within a scope that you can easily work with and call from anywhere else in your application. So, your contents might look something like: var myApp = myApp || {}; // create a new empty object if that variable name is available myApp.divHider = function() { $('div').hide(); } myApp.backColor = function(color) { $('body').css('background', color); } // document ready function, which is where you might be accustomed to seeing scripts executed. Doesn't HAVE to be in this file; could be anywhere that makes sense $(function() { myApp.divHider(); // hide all divs on document ready. Just a silly example });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: template specialization for all subclasses I would like to define a C++ template specialization that applies to all subclasses of a given base class. Is this possible? In particular, I'd like to do this for STL's hash<>. hash<> is defined as an empty parametrized template, and a family of specializations for specific types: template<class _Key> struct hash { }; template<> struct hash<char> { size_t operator()(char __x) const { return __x; } }; template<> struct hash<int> { size_t operator()(int __x) const { return __x; } }; ... I would like to define something like this: template<class Base> struct hash { size_t operator()(const Base& b) const { return b.my_hash(); } }; class Sub : public Base { public: size_t my_hash() const { ... } }; and be able to use it like this: hash_multiset<Sub> set_of_sub; set_of_sub.insert(sub); However, my hash template conflicts with the generic one from STL. Is there a way (perhaps using traits) to define a template specialization that applies to all subclasses of a given base class (without modifying the STL definitions)? Note that I know I can do this with some extra template parameters whenever this hash specialization is needed, but I'd like to avoid this if possible: template<> struct hash<Base> { size_t operator()(const Base& b) const { return b.my_hash(); } }; .... // similar specialization of equal_to is needed here... I'm glossing over that... hash_multiset<Sub, hash<Base>, equal_to<Base> > set_of_sub; set_of_sub.insert(sub); A: Since C++ 11 you can use SFINAE together with standard library enable_if and is_base_of to solve the problem. A: C++20 makes a cleaner solution possible - basically equivalent to enable_if, which even (optionally) works with CRTP #include <concepts> #include <functional> #include <unordered_set> // just for demo in main() template <class T> class Base {}; class Derived final : public Base<Derived> {}; template<class T> requires std::derived_from<T, Base<T>> struct std::hash<T> { // constexpr is optional constexpr size_t operator() (const T& value) const noexcept { return 0xDEADBEEF; // FIXME: do something better :) } }; int main() { // If operator() weren't constexpr, this couldn't be a *static* assert static_assert(std::hash<Derived>()(Derived {}) == 0xDEADBEEF); std::unordered_set<Derived> usageTest; return 0; } A: The solution is to use SFINAE to decide whether or not to allow your specialisation depending on the class inheritance structure. In Boost you can use enable_if and is_base_of to implement this. * *http://www.boost.org/doc/libs/1_47_0/libs/utility/enable_if.html *http://www.boost.org/doc/libs/1_47_0/libs/type_traits/doc/html/boost_typetraits/reference/is_base_of.html A: This was the best I could do: template<> struct hash<Sub> : hash<Base> { }; I'm a little worried that I didn't have to make operator() virtual, though. A: I don't think it is possible, because the way to do template specialization based on something more complex than just matching the type is C++ SFINAE, which requires second (dummy) template argument. Unfortunatelly, std::hash takes only one template argument and it is not allowed to create another version of std::hash with two template arguments. Therefore, the if you aren't satisfied with Jayen's solution, you can create your own hash type: #include <iostream> #include <type_traits> using namespace std; class ParentClass {}; class ChildClass : public ParentClass {}; // SFINAE, if T is not a child of ParentClass, substitution will fail // You can create specializations for the general case, for another base classes, etc. template<typename T, typename=typename enable_if<is_base_of<ParentClass, T>::value, T>::type> struct your_hash { size_t operator()(const T& value) { return 42; } }; int main() { ParentClass pc; ChildClass cc; cout<<your_hash<ParentClass>()(pc)<<"\n"; cout<<your_hash<ChildClass>()(cc)<<"\n"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Approach for file Uploads to service from Web Server I have to create service that can get files from any authorized source and save them on file server. Then return back response with url for that resource. The issue is that the service could be accessible from any web site or app. In case of Web site, what would be the best way to get file from a user and stream it to the service? Or do i have to save it to the web server first and then replay the stream to the service? I am thinking of creating Httphandler to channel traffic from web server (the instant file upload request is initiated by user) to the service. Would that be the best approach, or what would? A: I have just implemented file transfer service for our internal use. It was a trivial service to implement that with WCF RESTFul way. What you need to do is to implement streaming over Http. Actually, I have chosen new WCF Web Api to achieve this feature. But if you are familiar with that, here you can see a good example on how you can implement this : http://blogs.msdn.com/b/gblock/archive/2010/11/24/streaming-over-http-with-wcf.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7621857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does my table tr td:hover only work for the th header row?, not for any other rows? I have this code in jsfiddle and I would like the rows to highlight when I hover over them. I have tried the usual technique that works for me, but on this one, it only highlights the th header row, and not the table rows. View the code in JSFiddle. Basically, I've tried the usual: table tr:hover{background-color: yellow;} But this only highlights the table tr th Row only, and not the rows of the table, I have no idea why it's doing this. Check out the code in JSFiddle. A: I'm not sure either why it doesn't work as it is, but removing td in #main_content table tr td seems to do the job. So change #main_content table tr td { color: #666; border-right: 1px solid #eee; background-color: #fafafa; } to #main_content table tr { color: #666; border-right: 1px solid #eee; background-color: #fafafa; } A: You need to modify the CSS code, as so: #main_content table tr:hover td { color: #666; border-right: 1px solid #eee; background-color: #ffcc11; } the :hover is the main thing. Hope this helps A: That's because your td's background color is overriding the tr's background color. So, you need to change the following #main_content table tr td { color: #666; border-right: 1px solid #eee; background-color: #fafafa; } to #main_content table tr td { color: #666; border-right: 1px solid #eee; } #main_content table tr // apply the color to the tr instead of the td this way it can get overridden { background-color: #fafafa; } A: In CSS, change #main_content table tr td { color: #666; border-right: 1px solid #eee; background-color: #fafafa; } to #main_content table tr { color: #666; border-right: 1px solid #eee; background-color: #fafafa; } as seen in http://jsfiddle.net/jhuntdog/NPrSU/12/embedded/result/
{ "language": "en", "url": "https://stackoverflow.com/questions/7621864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing (ID) argument from aspx page to javascript function which updates ID somewhere else on the page So imagine I have a table which is a list of videos, with associated descriptions and links. On the page there is only ever one video shown. When a link is clicked, I want that click to take the ID of the corresponding video and pass it to the video player div, updating whatever video is displayed, ready for play. VidName | Description | Watch ...and repeat...generated from a foreach in C# I believe I will need to use .bind( 'click', [eventData,] handler(eventObject) ) but I am not sure what to put for the second argument - I know I want the ID, but from where? Does the 'Watch' text HAVE to made into a (submit) button or something? Intinctively I think this is quite simple...sorry for the dumb question if it is one! :) A: so why dont you just use the onclick event on the link? <a id="1" href="javascript:void(0)" onclick="DoSomething(this.id)">Simple's</a> A: The way i usually do it is something like this: <sometag data-id="id-for-the-data"></sometag> <script> function onSometagClick() { $(this).prop('data-id'); // read the id so we can us it } $(function(){ $(document.body).delegate('sometag','click',onSometagClick); //handle clicks on all 'sometag' ellements }); </script> If you want a less generic answer, please supply some markup :) The reason i don't use the id attribute is threefold. 1: to separate the markup/DOM from the actual data 2: id attributes are not allowed to start with a number, and my data id's are almost always numbers from a database somewhere. 3: if i need to reference the same data more than once on a page the id attribute is no good since it needs to be unique
{ "language": "en", "url": "https://stackoverflow.com/questions/7621867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use of __attribute__'s in ARC-managed Code When ARC came to Objective-C, I did my best to read through the Objective-C Automatic Reference Counting (ARC) guide posted on the Clang project website to get a better hang of what it was about. What I found there (and no where else) was mention of using __attribute__ declarations to signify to ARC whether certain code autoreleases its return value, for instance (__attribute__((ns_returns_autoreleased))), or whether it 'consumes' a parameter (__attribute((ns_consumed)), and so on. However, it seems that the guide gives very little word on the actual level of necessity these declarations hold. Excluding them seems to make no difference, neither when running the static analyzer nor when running the project itself. Do these even make a difference? Is there any advantage to labeling a method with __attribute__((objc_method_family(new)))? No article I've found on ARC makes mention of these specifiers at all; perhaps an ARC guru can give word on what these are used for. (Personally, I include all relevant specifiers just in case, but find that they make code obfuscated and messy.) A: These attributes are expressly for abnormal cases, such as: A function or method parameter of retainable object pointer type may be marked as consumed, signifying that the callee expects to take ownership of a +1 retain count. A function or method which returns a retainable object pointer type may be marked as returning a retained value, signifying that the caller expects to take ownership of a +1 retain count. You don't normally do these things, so you don't normally use these attributes. With no attributes, the normal behavior—the NARC rule, or perhaps under ARC I should say CAN—is what the compiler implements and expects. There are two reasons to use these attributes: * *In order to violate the CAN rule; that is, to have a method not so named that returns a reference, or a method so named that doesn't. The attribute documents the violation in the method's prototype, and may even be necessary to implement it, if the implementation uses ARC. *Working with Core Foundation types, including Core Graphics types. These aren't ARCed, so you need to use the bridging attributes to aid conversion to and from “retainable object pointer” types. A: That's not necessary in most of the cases, since LLVM & Clang knows ObjC naming conventions. So if you follow the standard naming conventions of Cocoa, LLVM automagically assumes the corresponding family/return memory policy to follow. Namely, if you declare a method named initWith... it will automatically consider it as the "init" family of methods, no need to specify __attribute__((objc_method_family(init))), Clang automatically detect it; same for the new family, etc. In fact, you only need to use the __attribute__ specifiers when Clang can't guess such cases, which in practice rarely occurs (in practice I never had to use it), or only if you don't respect naming conventions: Quoting Clang Language Extensions Documentation: Many methods in Objective-C have conventional meanings determined by their selectors. For the purposes of static analysis, it is sometimes useful to be able to mark a method as having a particular conventional meaning despite not having the right selector, or as not having the conventional meaning that its selector would suggest. For these use cases, we provide an attribute to specifically describe the method family that a method belongs to. So as soon as you respect the naming conventions (which you should always do) you won't have anything do to. A: You should definitely stick to naming conventions wherever possible. * *It's clearer to read. *Attributes can introduce build errors if there is a conflict. *ARC semantics combined with attributes are relatively fragile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where does Windows PowerShell set $profile? I would like to move my default "My Documents\WindowsPowerShell" folder. However, when I try this, PowerShell of course can't find $profile. Is there a file or something that I can edit to point PowerShell to a different startup folder? A: What I can suggest is that you dot source the file having the content of your profile in the file $profile.AllUsersAllHosts $profile.AllUsersAllHosts is something like C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 Related question: Is it possible to change the default value of $profile to a new value? A: You could use junction.exe from Sysinternals to make the WindowsPowershell directory a symbolic link to another location (but not a network drive). You could do this if you wanted to store the profile scripts at C:\POSH junction.exe "$HOME\Documents\WindowsPowerShell" 'C:\POSH' A: As far as i know you can't do that. The user profile location is always under 'My Documents\WindowsPowerShell' and your only option is to relocate your documents folder (folder redirection). A: By default $Profile/$Home/$PSModulePath are all within the registry... normally under * *HKEY_CURRENT_USER\Volatile Environment for User environment variables *HKEY_CURRENT_USER\Environment for System environment variables *HKEY_CURRENT_USER\Software\Microsoft\Windows\Explorer\User Shell Folders and elsewhere!
{ "language": "en", "url": "https://stackoverflow.com/questions/7621872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: how to enable java file in realm to all users i have a web service that i want to enable for use to all users (web service is written as java class). I use realm to configure my website security. How can i enable this resource in web.xml? thanks A: This allows everyone (without login) to access the resource (there is no auth-constraint tag): <security-constraint> <web-resource-collection> <web-resource-name>MyWebService</web-resource-name> <url-pattern>/public/webservice</url-pattern> </web-resource-collection> </security-constraint> This allows the logged in users (which has at least one role from the security-role list) to access the resource: <security-constraint> <web-resource-collection> <web-resource-name>MyWebService</web-resource-name> <url-pattern>/public/webservice</url-pattern> </web-resource-collection> <auth-constraint> <role-name>*</role-name> </auth-constraint> </security-constraint> <security-role> <role-name>user</role-name> <role-name>admin</role-name> <role-name>manager</role-name> </security-role>
{ "language": "en", "url": "https://stackoverflow.com/questions/7621876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing data to file but file still contain NULL Related to my previous post but its not a duplicate of that.Now I have tried something and Here I am asking you about the logical error in code. /*u_int8_t ....etc are alias for uint8_t...etc so don't bother about them*/ void crypt(u_int8_t *key, u_int32_t keylen, u_int8_t *data, u_int32_t datalen) { FILE *fp,*fq; fp=fopen("key","w"); fputs((char *)key,fp); fq=fopen("file.txt","w"); d=0; while(data[d]) { fputc((int)data[d],fq); d++; } fputc('\0',fq); fclose(fp); fclose(fq) } Output : udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat key kaheudit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.txt udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ Key gets printed to file but not the data. Now when I slightly modify the code : void crypt(u_int8_t *key, u_int32_t keylen, u_int8_t *data, u_int32_t datalen) { int d,k; FILE *fp,*fq; fp=fopen("key","w"); fputs((char *)key,fp); fq=fopen("file.txt","w"); for (d=0, k=0; d < datalen; ++d, k = (k+1)%keylen) { data[d] ^= key[k]; fputc(data[d],fq); } fclose(fp); fclose(fq); } Now key as well as data gets printed...although data is not exactly correct(but it is able to be written down into the file) udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat key kaheudit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.txt kthpOWWkahe;c��"�he kajcudit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ The call to the crypt function is as follows - bool espcrypto(esp_private *epriv, sendip_data *data, sendip_data *pack) { u_int32_t keylen; u_int8_t *key; static u_int8_t fakekey; struct ip_esp_hdr *esp = (struct ip_esp_hdr *)pack->data; if (!epriv->keylen) { /* This isn't going to be very productive... */ key = &fakekey; keylen = 1; } else { key = (u_int8_t *)epriv->key; keylen = epriv->keylen; } /* Encrypt everything past the ESP header */ crypt(key, keylen, (u_int8_t *)esp->enc_data, pack->alloc_len + data->alloc_len - sizeof(struct ip_esp_hdr)); return TRUE; } The following packet describe what data I actually need to write down to the file... udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ sendip -v -p ipv6 -dabcd -6s ::1 -p esp -es 0x20 -eq 0x40 -ek "kahe" -ec crypt.so -p tcp -ts 21 -td 21 ::2 Added 43 options Initializing module ipv6 Initializing module esp Initializing module tcp Finalizing module tcp Finalizing module esp Finalizing module ipv6 Final packet data: 60 00 00 00 `... 00 24 32 20 .$2 00 00 00 00 .... 00 00 00 00 .... 00 00 00 00 .... 00 00 00 01 .... 00 00 00 00 .... 00 00 00 00 .... 00 00 00 00 .... 00 00 00 02 .... 00 00 00 20 ... 00 00 00 40 ...@ 6B 74 68 70 kthp /*data portion starts from here*/ 4F 57 1F 57 OW.W 6B 61 68 65 kahe 3B 63 97 9A ;c.. 22 C0 68 65 ".he 0A 03 0B 01 .... 6B 61 6A 63 kajc /*data portion ends here*/ Freeing module ipv6 Freeing module esp Freeing module tcp Please help me.... I haven't receiver any satisfactory implementation on my previous post still so trying my own hand.Really need it .. A: You're using string semantics to handle binary data. That's not going to work. If you look closely you'll see that the first character in your file.txt example output is k, which is also the first character of the key. That means your data is starting with a NUL byte and the while loop will instantly exit. First of all you need to open the files in binary mode: fp=fopen("key","wb"); fq=fopen("file.txt","wb"); To write the key use fwrite(key, keylen, 1, fp); and then use the for loop in your second example to write the data. I can't see anything wrong with that one, your problem might simply have been the binary vs text mode. Edit: Try using hexdump -C file.txt to view your file instead of cat. A: Here while(data[d]) { fputc((int)data[d],fq); d++; } data[d] is 0 (as it is binary data), so it will leave the loop "too" soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display intent chooser when long click listview item? I have a list view that contains some data, I want to share it by through intent chooser. I found long click on a listview item will trigger context menu event, and the common way to use a context menu is the build a menu in onCreateContextMenu() and then get line index from menuInfo in onContextItemSelected(). But in my case I want to display intent chooser directly when when I long click the list view item. Do I make myself understood? How can I archieve this? A: listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { return true; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7621892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get Missed call & SMS count I want to get the count of missed calls and unread messages in my application. and I'd like to open the relevant application when user click on the count. Now biggest problem is how to get the count? I searched online but couldn't find any solution. Thanks in advance. A: http://developer.android.com/reference/android/provider/CallLog.Calls.html Take a look at this CallLog class. All you need is to query the phone for any calls then extract missed one (оr do this when you are querying the phone, in the selection arguments). The same applies for the messages. SMS are stored in the Content provider under "content://sms/" Then just get the count of rows in the Cursor that is return by the query. :) I hope this helps. For missed calls: String[] projection = { CallLog.Calls.CACHED_NAME, CallLog.Calls.CACHED_NUMBER_LABEL, CallLog.Calls.TYPE }; String where = CallLog.Calls.TYPE + "=" + CallLog.Calls.MISSED_TYPE; Cursor c = this.getContentResolver().query( CallLog.Calls.CONTENT_URI, selection, where, null, null ); c.moveToFirst(); Log.d("CALL", ""+c.getCount()); //do some other operation if (c.getCount() == SOME_VALUE_TO_START_APP_ONE) //...etc etc In the where clause you set condition for selection of data. In our case we need everything which type equals CallLog.Calls.MISSED_TYPE. We select project the Name of the caller and his number, ofcourse you can specify more information to be queried like type of number like mobile, home, work. The expression is equivalent to SQL query, something like: SELECT CACHED_NAME, CACHED_NUMBER_LABEL, TYPE FROM CONTENT_URI WHERE TYPE=MISSED_TYPE This requires permissions to be added to the Manifest <uses-permission android:name="android.permission.READ_LOGS"></uses-permission> <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> For querying SMS ContentProvider: Uri sms_content = Uri.parse("content://sms"); Cursor c = this.getContentResolver().query(sms_content, null,null, null, null); c.moveToFirst(); Log.d("SMS COUNT", "" + c.getCount()); //do some other operation // Here proceed with the what you wanted if (c.getCount() == SOME_VALUE_TO_START_APP_ONE)//...etc etc You can go deeper in the content tree like specifying the type of sms, like: content://sms/sent or content://sms/inbox and add projection and selection for the second argument of the query() method like, name, person, status of the message (like the Calls example). This requires permission: <uses-permission android:name="android.permission.READ_SMS"></uses-permission> A: As I don't have enough reputation to answer @Prasad question comment about ERROR -> getContentResolver() is undefined for the type new Runnable(){} getContentResolver() is part of application context, so if you are using a BroadcastReceiver use context in onReceive() function like this @Override public void onReceive(Context context, Intent intent) { context.getContentResolver() } If you are using the code above inside an Activity, then you can use getApplicationContext().getContentResolver() also make sure to use [Ctrl + Shift + O (O not zero)] to organize imports Key Shortcut for Eclipse Imports
{ "language": "en", "url": "https://stackoverflow.com/questions/7621893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android MarketPlace: reserve namespace I have heard the best way to stop someone stealing/publishing your signed .apk before you publish it yourself to the Google Android markeyplace is to upload a dummy release .apk with the same namespace /name, ahead of the publish date. I have done this but it is in an 'unpublished' state. Does anyone know if this is sufficient to stop anyone else using the same app name or namespace or will this only be the case if it is actually published? A: Just saving the apk is enough ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: logging module - globally I was wondering how to implement a global logger that could be used everywhere with your own settings: I currently have a custom logger class: class customLogger(logging.Logger): ... The class is in a separate file with some formatters and other stuff. The logger works perfectly on its own. I import this module in my main python file and create an object like this: self.log = logModule.customLogger(arguments) But obviously, I cannot access this object from other parts of my code. Am i using a wrong approach? Is there a better way to do this? A: Since I haven't found a satisfactory answer, I would like to elaborate on the answer to the question a little bit in order to give some insight into the workings and intents of the logging library, that comes with Python's standard library. In contrast to the approach of the OP (original poster) the library clearly separates the interface to the logger and configuration of the logger itself. The configuration of handlers is the prerogative of the application developer who uses your library. That means you should not create a custom logger class and configure the logger inside that class by adding any configuration or whatsoever. The logging library introduces four components: loggers, handlers, filters, and formatters. * *Loggers expose the interface that application code directly uses. *Handlers send the log records (created by loggers) to the appropriate destination. *Filters provide a finer grained facility for determining which log records to output. *Formatters specify the layout of log records in the final output. A common project structure looks like this: Project/ |-- .../ | |-- ... | |-- project/ | |-- package/ | | |-- __init__.py | | |-- module.py | | | |-- __init__.py | |-- project.py | |-- ... |-- ... Inside your code (like in module.py) you refer to the logger instance of your module to log the events at their specific levels. A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows: logger = logging.getLogger(__name__) The special variable __name__ refers to your module's name and looks something like project.package.module depending on your application's code structure. module.py (and any other class) could essentially look like this: import logging ... log = logging.getLogger(__name__) class ModuleClass: def do_something(self): log.debug('do_something() has been called!') The logger in each module will propagate any event to the parent logger which in return passes the information to its attached handler! Analogously to the python package/module structure, the parent logger is determined by the namespace using "dotted module names". That's why it makes sense to initialize the logger with the special __name__ variable (in the example above name matches the string "project.package.module"). There are two options to configure the logger globally: * *Instantiate a logger in project.py with the name __package__ which equals "project" in this example and is therefore the parent logger of the loggers of all submodules. It is only necessary to add an appropriate handler and formatter to this logger. *Set up a logger with a handler and formatter in the executing script (like main.py) with the name of the topmost package. When developing a library which uses logging, you should take care to document how the library uses logging - for example, the names of loggers used. The executing script, like main.py for example, might finally look something like this: import logging from project import App def setup_logger(): # create logger logger = logging.getLogger('project') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(level) # create formatter formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) if __name__ == '__main__' and __package__ is None: setup_logger() app = App() app.do_some_funny_stuff() The method call log.setLevel(...) specifies the lowest-severity log message a logger will handle but not necessarily output! It simply means the message is passed to the handler as long as the message's severity level is higher than (or equal to) the one that is set. But the handler is responsible for handling the log message (by printing or storing it for example). Hence the logging library offers a structured and modular approach which just needs to be exploited according to one's needs. Logging documentation A: You can just pass it a string with a common sub-string before the first period. The parts of the string separated by the period (".") can be used for different classes / modules / files / etc. Like so (specifically the logger = logging.getLogger(loggerName) part): def getLogger(name, logdir=LOGDIR_DEFAULT, level=logging.DEBUG, logformat=FORMAT): base = os.path.basename(__file__) loggerName = "%s.%s" % (base, name) logFileName = os.path.join(logdir, "%s.log" % loggerName) logger = logging.getLogger(loggerName) logger.setLevel(level) i = 0 while os.path.exists(logFileName) and not os.access(logFileName, os.R_OK | os.W_OK): i += 1 logFileName = "%s.%s.log" % (logFileName.replace(".log", ""), str(i).zfill((len(str(i)) + 1))) try: #fh = logging.FileHandler(logFileName) fh = RotatingFileHandler(filename=logFileName, mode="a", maxBytes=1310720, backupCount=50) except IOError, exc: errOut = "Unable to create/open log file \"%s\"." % logFileName if exc.errno is 13: # Permission denied exception errOut = "ERROR ** Permission Denied ** - %s" % errOut elif exc.errno is 2: # No such directory errOut = "ERROR ** No such directory \"%s\"** - %s" % (os.path.split(logFileName)[0], errOut) elif exc.errno is 24: # Too many open files errOut = "ERROR ** Too many open files ** - Check open file descriptors in /proc/<PID>/fd/ (PID: %s)" % os.getpid() else: errOut = "Unhandled Exception ** %s ** - %s" % (str(exc), errOut) raise LogException(errOut) else: formatter = logging.Formatter(logformat) fh.setLevel(level) fh.setFormatter(formatter) logger.addHandler(fh) return logger class MainThread: def __init__(self, cfgdefaults, configdir, pidfile, logdir, test=False): self.logdir = logdir logLevel = logging.DEBUG logPrefix = "MainThread_TEST" if self.test else "MainThread" try: self.logger = getLogger(logPrefix, self.logdir, logLevel, FORMAT) except LogException, exc: sys.stderr.write("%s\n" % exc) sys.stderr.flush() os._exit(0) else: self.logger.debug("-------------------- MainThread created. Starting __init__() --------------------") def run(self): self.logger.debug("Initializing ReportThreads..") for (group, cfg) in self.config.items(): self.logger.debug(" ------------------------------ GROUP '%s' CONFIG ------------------------------ " % group) for k2, v2 in cfg.items(): self.logger.debug("%s <==> %s: %s" % (group, k2, v2)) try: rt = ReportThread(self, group, cfg, self.logdir, self.test) except LogException, exc: sys.stderr.write("%s\n" % exc) sys.stderr.flush() self.logger.exception("Exception when creating ReportThread (%s)" % group) logging.shutdown() os._exit(1) else: self.threads.append(rt) self.logger.debug("Threads initialized.. \"%s\"" % ", ".join([t.name for t in self.threads])) for t in self.threads: t.Start() if not self.test: self.loop() class ReportThread: def __init__(self, mainThread, name, config, logdir, test): self.mainThread = mainThread self.name = name logLevel = logging.DEBUG self.logger = getLogger("MainThread%s.ReportThread_%s" % ("_TEST" if self.test else "", self.name), logdir, logLevel, FORMAT) self.logger.info("init database...") self.initDB() # etc.... if __name__ == "__main__": # ..... MainThread(cfgdefaults=options.cfgdefaults, configdir=options.configdir, pidfile=options.pidfile, logdir=options.logdir, test=options.test) A: Use logging.getLogger(name) to create a named global logger. main.py import log logger = log.setup_custom_logger('root') logger.debug('main message') import submodule log.py import logging def setup_custom_logger(name): formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.addHandler(handler) return logger submodule.py import logging logger = logging.getLogger('root') logger.debug('submodule message') Output 2011-10-01 20:08:40,049 - DEBUG - main - main message 2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message A: Create an instance of customLogger in your log module and use it as a singleton - just use the imported instance, rather than the class. A: The python logging module is already good enough as global logger, you might simply looking for this: main.py import logging logging.basicConfig(level = logging.DEBUG,format = '[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s') Put the codes above into your executing script, then you can use this logger with the same configs anywhere in your projects: module.py import logging logger = logging.getLogger(__name__) logger.info('hello world!') For more complicated configs you may use a config file logging.conf with logging logging.config.fileConfig("logging.conf")
{ "language": "en", "url": "https://stackoverflow.com/questions/7621897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "74" }
Q: How To Parse Date From any datetime format to dd/mm/yyyy? i want to parse any datetime format to dd/MM/yyyy format. here is my code // dates i am providing are // Sat, 01 Oct 2011 17:30:00 +0400 // and // Sat, 01 October 2011 12:21:23 EST Datetime dt = Convert.toDateTime(pubDate); which is giving me following exception The string was not recognized as a valid DateTime. There is an unknown word starting at index 32 any one guide me how can i parse any dateformat to a single one? any help would be appreciated. A: DateTime doesn't store dates in a "format" - it uses an internal representation. You need to parse a passed in string in order to get the correct value for the DateTime and when you want to display it you can then format it to whatever display. Your best bet is to use TryParseExact supplying it with the exact format string. You need to use the custom Date and Time format strings with it. Use the overload that takes a string[] of format strings - one for each date format. In regards to the EST portion - the framework doesn't have support for named timezones. You may want to write a wrapper that converts named timezones to their equivalent but parseable form. Untested (based on MSDN example): string[] formats= {"ddd, dd/MMM/yyyy hh:mm:ss K", "ddd, dd MMMM yyyy hh:mm:ss EST"}; DateTime dateValue; foreach (string dateString in dateStrings) { if (DateTime.TryParseExact(dateString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out dateValue)) Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue); else Console.WriteLine("Unable to convert '{0}' to a date.", dateString); } A: Remove the 'EST' from the string and it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add the path for publickey.xml file to the InputStream in android? Where to put the file publickey.xml? //how to place the path for publickeyfile.xml here? InputStream in = //the objectipnutstream that gets the inputstream ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in)); try { BigInteger m = (BigInteger) oin.readObject(); BigInteger e = (BigInteger) oin.readObject(); RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(keySpec); } catch (Exception e) { throw new RuntimeException("Spurious serialisation error", e); } finally { oin.close(); } A: * *create a res>raw folder in the project *put the publickeyfile.xml file in the new folder *"Inputstream is = myResources.openRawResource(R.raw.publickeyfile)" ...it should work
{ "language": "en", "url": "https://stackoverflow.com/questions/7621900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating mongodb references errors out due to field names I have a MongoDB collection and I'm trying to update all the entries in it to change the name of a field used to store a reference. The Query I'm using is db.products.find().forEeach(function(p) { p.newField = p.oldField; db.products.save(p); }); The problem is that p.oldField is a DBRef following the standard format of { "$ref": "collection", "$id": ObjectId("...")}. When I try to run the db.products.save(p); Mongo returns the following error: Sat Oct 1 13:00:57 uncaught exception: field names cannot start with $ [$db] I'm using version 1.8.2 of the MongoDB shell. I have seen this work on an older version of the shell (1.6.5), which is where I originally came up with this query. But I can't seem to make this work on newer versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: float to integer in python If I want to convert a float to an integer in Python, what function do I use? The problem is that I have to use a variable passed through the function math.fabs (Absolute Value) as an index for a list, so it has to be an int, while the function math.fabs returns a float. A: Use the int() constructor: >>> foo = 7.6 >>> int(foo) 7 Note that if you use the built-in abs() function with an integer argument, you'll get an integer result in the first place: >>> type(abs(-7)) <type 'int'> A: Probably you're looking for both round and int: >>> foo = 1.9 >>> int(foo) 1 >>> int(round(foo)) 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7621903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Emulating Django models ? (Simple implementation - Missing something) I am trying to emulate django models : In Django : from django.contrib.auth.models import User if User.objects.get(pk=1) == User.objects.get(username='root') print 'True' else: print 'False' # True is printed My implementation : class MyUser: def __init__(self, id): self.id = id class User: class objects: @staticmethod def get(**kwargs): return MyUser(1) if User.objects.get(pk=1) == User.objects.get(username='root') print 'True' else: print 'False' # False is printed How to correct my implementation to get 'True' ? How can I achieve the same effect ? What change shall I do ? A: The issue is simply that you haven't defined __eq__ on your class, so Python has no idea how to compare them. Something like this would work: class MyUser(object): def __init__(self, id): self.id = id def __eq__(self, other): return self.id == other.id A: This is because Django's Models implement a __eq__ method: def __eq__(self, other): return isinstance(other, self.__class__) and self._get_pk_val() == other._get_pk_val() You could implement a similar method on your MyUser class to achive a similar effect. See also: the documentation on __eq__.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What's a good resizable, random access, efficient byte vector class in Java? I'm trying to find a class for storing a vector of bytes in Java, which supports: random access (so I can get or set a byte anywhere), resizing (so I can either append stuff to the end or else manually change the size), reasonable efficiency (I might be storing megabytes of data in these things), all in memory (I don't have a file system). Any suggestions? So far the candidates are: * *byte[]. Not resizable. *java.util.Vector<Byte>. Evil. Also painfully inefficient. *java.io.ByteArrayOutputStream. Not random-access. *java.nio.ByteBuffer. Not resizable. *org.apache.commons.collections.primitives.ArrayByteList. Not resizable. Which is weird, because it'll automatically resize if you add stuff to it, you just can't change the size explicitly! *pure RAM implementation of java.nio.channels.FileChannel. Can't find one. (Remember I don't have a file system.) *Apache Commons VFS and the RAM filesystem. If I must I will, but I really like something lighter weight... This seems like such an odd omission that I'm sure I must have missed something somewhere. I just figure out what. What am I missing? A: I would consider a class that wraps lots of chunks of byte[] arrays as elements of an ArrayList or Vector. Make each chunk a multiple of e.g. 1024 bytes, so you accessor functions can take index >> 10 to access the right element of the ArrayList, and then index & 0x3ff to access the specific byte element of that array. This will avoid the wastage of treating each byte as a Byte object, at the expensive of wastage of whatever's left over at the end of the last chunk. A: In those cases, I simply initialize a reference to an array of reasonable length, and when it gets too small, create and copy it to a larger one by calling Arrays.copyOf(). e.g.: byte[] a = new byte[16]; if (condition) { a = Arrays.copyOf(a, a.length*2); } And we may wrap that in a class if needed... A: ArrayList is more efficient than Vector because it's not synchronized. To improve efficiency you can start with a decent initial capacity. See the constructor: ArrayList(int initialCapacity) I think the default is only 16, while you probably may need much bigger size. Despite what it seems, ArrayList is very efficient even with a million record! I wrote a small test program that adds a million record to an ArrayList, without declaring an initial capacity and on my Linux, 5 year old laptop (Core 2 T5200 cpu), it takes around 100 milliseconds only to fill the whole list. If I declare a 1 million bytes initial space it takes around 60-80 ms, but If I declare 10,000 items it can take around 130-160ms, so maybe is better to not declare anything unless you can make a really good guess of the space needed. About the concern for memory usage, it take around 8 Mb of memory, which I consider totally reasonable, unless you're writing phone software. import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.obliquid.util.StopWatch; public class ArrayListTest { public static void main(String args[]) { System.out.println("tot=" + Runtime.getRuntime().totalMemory() + " free=" + Runtime.getRuntime().freeMemory()); StopWatch watch = new StopWatch(); List<Byte> bytes = new ArrayList<Byte>(); for (int i = 0; i < 1000000; i++) { bytes.add((byte) (i % 256 - 128)); } System.out.println("Elapsed: " + watch.computeElapsedMillisSeconds()); System.out.println("tot=" + Runtime.getRuntime().totalMemory() + " free=" + Runtime.getRuntime().freeMemory()); } } As expected, Vector performs a little worse in the range of 160-200ms. Example output, without specifying a start size and with ArrayList implementation. tot=31522816 free=31023176 Elapsed: 74 tot=31522816 free=22537648
{ "language": "en", "url": "https://stackoverflow.com/questions/7621905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is the purpose of home/remote interfaces EJB 3.1 I have recently started reading about Java EE6 and in the examples I follow I need to make remote interface. What is the purpose of this? I also read about home interfaces, but I don't understand. I have never done enterprise programming before so I can't relate it to something else either. Could someone explain me these interfaces? A: Basically by declaring the @Local @Remote interfaces you specify which methods should be available for the remote clients and which for the local beans in the same JVM. Home interface is used to allow a remote client to create, find, and remove EJB objects. You can easily find that information on the official documentation pages, for example for EJBHome, or nice overview for local and remote here I highly recommend reading EJB book by Bill Burke, Richard Monson-Haefel for starters. A: Every Session bean has to implement Interface and Bean Class. When User requests then JNDI helps to lookup which Interface is required for that Request. When your EJBs are deployed in same EAR then you should prefer Local Interface. If EJBs are in same EAR then Remote Interface should be used. This Interface will call business logic which resides in Bean Class. Home Interface creates and finds EJB objects for Remote Interface. So first you should create Home Interface with create method and then Remote Interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send POST parameters in header()? I'm making a register page, signup.php, and basically what I want it to do is check for errors and if there are none, redirect to register.php. That is fine and whatnot, but register.php is the page where the actual account is made (e.g. mySQL query). Of course, in order to do that, I actually need the params gathered form signup.php. I was wondering if I could do something like this.. header("Location: register.php, TYPE: POST, PARAMS: {user,pass,email}") Obviously I can not use $_GET as I am transmitting sensitive data (e.g. passwords). Any ideas/suggestions? EDIT: Thank you all for your answers. I am now storing the parameters in a $_SESSION variable. A: I see no point in such redirect. Why not to post right away to register.php? And then check for errors and save data in database in the same register.php? without any redirects A: Even if this is possible, you will hit another brick wall - the implementation of redirects in the popular browsers. While the standard requires, that it asks the user if a post is redirected, all popular browsers simply interpret the redirect as a GET. In short: you can't redirect a POST that way, you'll have to find another way without a round trip to the client, or use GET. Also, you should be aware that unless your requests are done via https, both GET and POST will present the sensitive information to any listener, as POST simply buts the query string into the http request and not the url. Security wise, both are the same. A: You could store them in the $_SESSION and refer to those in the register.php page, doing some checking to make sure someone has actually filled out the information and didn't just navigate to it. A: No, you can't, and such data would be just as insecure to any determined attacker. Store the data in a session variable for use in the next page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting text from a html file? I have a web page which contains a bunch of text and I want to extract just the text from the page and write it to a file. I am trying to use BeautifulSoup but am not sure it easily does what I want. Here is the story: I believe that the text I want to extract lies between: <td colspan="2" class="msg_text_cell" style="text-align: justify; background-color: rgb(212, 225, 245); background-image: none; background-repeat: repeat-x;" rowspan="2" valign="top" width="100%"> and <p></p><div style="overflow: hidden; width: 550px; height: 48px;"> What I want to do is the select just the text lines between, but no including the above begin and end text. Note that the begin html above is on a line by itself but the end text sometimes occurs just after the last text I want but is not on a new line. I can not seem to see how to do what I want with BeautifulSoup, but probably it is my unfamiliarity getting in the way. Also, the text I want to extract occurs say 50 times in the page, so I want all such text separated by something like '+++++++++++++++++++++' to make it easier to read. Thanks much for your help. A: If ever you know a notch of Ruby, i can point you to Nokogiri which is an amazing gem for screen scraping. A: simply put you can loop over expected dom elements that contain the text you want and extract it that way ... using jquery something like $('td.msg_text_cell').each( function (idx,el) { idx would be the index in the array of jQuery objects found from the selector above getting all tds with a class of msg_text_cell ... }) you can do with native js also so don't think that i'm pushing jquery ... just a framework i'm more familiar with A: You can do it easily with BeautifulSoup from bs4 import BeautifulSoup as bs soup = "<td colspan=\"2\" class=\"msg_text_cell\" style=\"text-align: justify; background-color: rgb(212, 225, 245); background-image: none; background-repeat: repeat-x;\" rowspan=\"2\" valign=\"top\" width=\"100%\"> <p>The text</p><div style=\"overflow: hidden; width: 550px; height: 48px;\">" soup = bs(soup) soup.find('p') You can now found something like the text inside the tag Output: <p>The text</p> You can now add loop to modify the variable. Then you can save in a file. with open("data.csv","w") as tW: writer = csv.writer(tW,delimiter=",") writer.writerow(["Ptag"]) for i in soup: p = i.get_text() writer.writerow([p])
{ "language": "en", "url": "https://stackoverflow.com/questions/7621910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery live() and $this I'm having trouble with jQuery's live. The div one should slidedown when the div comment of the same container div is clicked on. What is happening is every div one is sliding down regardless of their containers. How do i fix this? I think it is the $this function but i don't know how to implement it. <script type="text/javascript"> $('.one').hide(); $('.comment').live('click',function() { if ($('.one').is(':hidden')) { $('.one').slideDown('slow'); } }); </script> <?php for($i=0;$i<11;$i++) { ?> <div class='container'> <a class='comment'>comment</a> <div class='one'> <textarea style='width:350px;height:100px'>Type text here</textarea> </div> </div> <?php } ?> A: In this case (from info provided) .live() is not neccessary, you can just use .click(). The body of your function can look like this... $one = $(this).next('.one'); //select the specific .one div you want if ($one.is(':hidden')) { $one.slideDown('slow'); } You want to target only the specific .one div you want to show... where currently you're targeting every .one div. A: Just use next() $('.one').hide(); $('.comment').live('click',function() { if ($(this).next('.one').is(':hidden')) { $(this).next('.one').slideDown('slow'); } }); jsFiddle A: Try: $('.comment').live('click',function() { $(this).siblings('.one').slideDown('slow'); }); A: <script type="text/javascript"> $('.one').hide(); $('.comment').live('click',function() { var sameone = $(this).next('.one'); if (sameone.is(':hidden')) { sameone.slideDown('slow'); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7621916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: @Scope("prototype") bean scope not creating new bean I want to use a annotated prototype bean in my controller. But spring is creating a singleton bean instead. Here is the code for that: @Component @Scope("prototype") public class LoginAction { private int counter; public LoginAction(){ System.out.println(" counter is:" + counter); } public String getStr() { return " counter is:"+(++counter); } } Controller code: @Controller public class HomeController { @Autowired private LoginAction loginAction; @RequestMapping(value="/view", method=RequestMethod.GET) public ModelAndView display(HttpServletRequest req){ ModelAndView mav = new ModelAndView("home"); mav.addObject("loginAction", loginAction); return mav; } public void setLoginAction(LoginAction loginAction) { this.loginAction = loginAction; } public LoginAction getLoginAction() { return loginAction; } } Velocity template: LoginAction counter: ${loginAction.str} Spring config.xml has component scanning enabled: <context:annotation-config /> <context:component-scan base-package="com.springheat" /> <mvc:annotation-driven /> I'm getting an incremented count each time. Can't figure out where am I going wrong! Update As suggested by @gkamal, I made HomeController webApplicationContext-aware and it solved the problem. updated code: @Controller public class HomeController { @Autowired private WebApplicationContext context; @RequestMapping(value="/view", method=RequestMethod.GET) public ModelAndView display(HttpServletRequest req){ ModelAndView mav = new ModelAndView("home"); mav.addObject("loginAction", getLoginAction()); return mav; } public LoginAction getLoginAction() { return (LoginAction) context.getBean("loginAction"); } } A: As mentioned by nicholas.hauschild injecting Spring context is not a good idea. In your case, @Scope("request") is enough to fix it. But let say you need several instances of LoginAction in controller method. In this case, I would recommend to create the bean of Supplier (Spring 4 solution): @Bean public Supplier<LoginAction> loginActionSupplier(LoginAction loginAction){ return () -> loginAction; } Then inject it into controller: @Controller public class HomeController { @Autowired private Supplier<LoginAction> loginActionSupplier; A: Since Spring 2.5 there's a very easy (and elegant) way to achieve that. You can just change the params proxyMode and value of the @Scope annotation. With this trick you can avoid to write extra code or to inject the ApplicationContext every time that you need a prototype inside a singleton bean. Example: @Service @Scope(value="prototype", proxyMode=ScopedProxyMode.TARGET_CLASS) public class LoginAction {} With the config above LoginAction (inside HomeController) is always a prototype even though the controller is a singleton. A: Using ApplicationContextAware is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory, which you can ask for a new instance of a LoginAction each time you need one. A: use request scope @Scope("request") to get bean for each request, or @Scope("session") to get bean for each session 'user' A: A protoype bean injected inside a singelton bean will behave like singelton untill expilictly called for creating a new instance by get bean. context.getBean("Your Bean") A: Scope prototype means that every time you ask spring (getBean or dependency injection) for an instance it will create a new instance and give a reference to that. In your example a new instance of LoginAction is created and injected into your HomeController . If you have another controller into which you inject LoginAction you will get a different instance. If you want a different instance for each call - then you need to call getBean each time - injecting into a singleton bean will not achieve that. A: Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is! A: @controller is a singleton object, and if inject a prototype bean to a singleton class will make the prototype bean also as singleton unless u specify using lookup-method property which actually create a new instance of prototype bean for every call you make. A: By default, Spring beans are singletons. The problem arises when we try to wire beans of different scopes. For example, a prototype bean into a singleton. This is known as the scoped bean injection problem. Another way to solve the problem is method injection with the @Lookup annotation. Here is a nice article on this issue of injecting prototype beans into a singleton instance with multiple solutions. https://www.baeldung.com/spring-inject-prototype-bean-into-singleton A: class with @Configuration @Bean @RequestScope //composed annotation for @Scope(value=...proxyMode=...) public LoginAction requestScopedBean() { return new LoginAction (); } @Controller public class HomeController { @Resource(name = "requestScopedBean") private LoginAction loginAction; //...your code here A: Your controller also need the @Scope("prototype") defined like this: @Controller @Scope("prototype") public class HomeController { ..... ..... ..... } A: @Component @Scope(value="prototype") public class TennisCoach implements Coach { // some code }
{ "language": "en", "url": "https://stackoverflow.com/questions/7621920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "158" }
Q: Fill an array with random numbers android/ java I'm having trouble doing the following and have no idea how to do it: I would like to fill an array generated with random numbers (1-40) and also make it so that the number doesn't repeat. Also, is there a way to make the array go to the next value on its own using. So let say I have test [1] = "3" and then test [2] = "6". Is there anyway to make it go to the next value instead of calling test [2]? Thanks a lot A: List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 40;) { int rand = ((int)(Math.random() * 40)) + 1; if(!list.contains(rand)) { list.add(rand); i++; } } or: List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 40; i++) list.add(i); Collections.shuffle(list);
{ "language": "en", "url": "https://stackoverflow.com/questions/7621928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InnoDB maximum key length This is a fairly straight forward question but I'm having a problem finding a clear answer googling around. On MySQL 5.1.53, using InnoDB, and a varchar(1024) field (I'm indexing Exchange 2010 Event IDs). I'm wondering what the maximum key length is when I index this field. I'm wondering if I should shorten the field and use something like an sha512 hash if the key length isn't long enough. A: The InnoDB internal maximum key length is 3500 bytes, but MySQL itself restricts this to 3072 bytes. This limit applies to the length of the combined index key in a multi-column index. And, as noted: An index key for a single-column index can be up to 767 bytes. The same length limit applies to any index key prefix. See Section 12.1.13, “CREATE INDEX Syntax”. http://dev.mysql.com/doc/refman/5.1/en/innodb-restrictions.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7621929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ stream polymorphy on stack? I would like to do something like this: std::wistream input = std::wifstream(text); if (!input) input = std::wistringstream(text); // read from input i.e. have text either interpreted as a filename, or, if no such file exists, use its contents instead of the file's contents. I could of course use std::wistream * input and then new and delete for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety). Is there another way of doing this on the stack? A: You could abstract the logic that works with std::wistream& input into a function of its own, and then call it with a std::wifstream or std::wistringstream as appropiate. A: I could of course use std::wistream * input and then new and delete for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety). This is what std::unique_ptr is for. Just use std::unique_ptr<std::istream>. A: Is there another way of doing this on the stack? No way. As the copy-assignment is disabled for all stream classes in C++, you cannot use it.That immediately implies that what you want is not possible. A: Have you considered auto_ptr or unique_ptr to manage the wistream pointer? http://www.cplusplus.com/reference/std/memory/auto_ptr/
{ "language": "en", "url": "https://stackoverflow.com/questions/7621944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could I block access from visitors from certain countries to a file on my site (xyz.com/thisFile.php)? I need to block visitors from certain countries from uploading images - but they should be able to access the site. For e.g. I've a site xyz.com. The way I have it set up currently, all visitors from blacklisted countries are unable to access the site itself, and are greeted with a 403. This isn't a good solution, of course, so I want to set it up such that these users can still access and play around with the site, but NOT be able to upload images (which is through clicking on xyz.com/upload/ which is an alias for xyz.com/upload_file.php). Every other user from other whitelisted countries should obviously be able to use all of the site's functionalities, save for users from blacklisted countries, who should not be able to upload their images. How could I ensure this is the case through .htaccess? I am currently on Cloudflare, and the relevant text in .htaccess is as follows: SetEnvIf CF-IPCountry AA UnwantedCountry=1 SetEnvIf CF-IPCountry BB UnwantedCountry=1 SetEnvIf CF-IPCountry CC UnwantedCountry=1 Order allow,deny Deny from env=UnwantedCountry Allow from all Thanks. A: Change those lines of code in your question with this: <Files "upload_file.php"> SetEnvIf CF-IPCountry AA UnwantedCountry=1 SetEnvIf CF-IPCountry BB UnwantedCountry=1 SetEnvIf CF-IPCountry CC UnwantedCountry=1 Order allow,deny Allow from all Deny from env=UnwantedCountry </Files> This will restrict access to those countries only to the file upload_file.php. A: Does it have to be an alias? Could you just create an upload/ folder, and put the .htaccess in there? It might require changing some of the upload_file.php logic, but that seems like the easiest fix to me. A: I think .htaccess files can be put into /any/ subdirectory. Move your file uploading code into a directory and put .htaccess controls there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7621945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why did this source code allocate 16 bytes? (gdb) disas /m main Dump of assembler code for function main(): 2 { 0x080483f4 <+0>: push %ebp 0x080483f5 <+1>: mov %esp,%ebp 0x080483f7 <+3>: sub $0x10,%esp 3 int a = 1; 0x080483fa <+6>: movl $0x1,-0x4(%ebp) 4 int b = 10; 0x08048401 <+13>: movl $0xa,-0x8(%ebp) 5 int c; 6 c = a + b; 0x08048408 <+20>: mov -0x8(%ebp),%eax 0x0804840b <+23>: mov -0x4(%ebp),%edx 0x0804840e <+26>: lea (%edx,%eax,1),%eax 0x08048411 <+29>: mov %eax,-0xc(%ebp) 7 return 0; 0x08048414 <+32>: mov $0x0,%eax 8 } 0x08048419 <+37>: leave Notce the 3rd assembler instruction, it allocated 16 bytes instead of the expected 12 bytes. Why is that? I thought the 3rd line is allocating automatic variables... Even if I removed the assignment, the allocation is still 16 bytes. Thanks. Edit // no header. nothing int main() { int a = 1; int b = 10; int c; c = a + b; return 0; } g++ -g -o demo demo.cpp Follow up... I read a couple more threads on stack alignment (sorry, I am now studying computer arch and organization class...so I am not familiar with this at all) Stack Allocation Padding and Alignment I am supposed it's the compiler's setting. So default, the minimum is 16-byte. If we have int a = 1; int b = 10; int c = 10; int d = 10; // -- int e = 10; Up to int d, we would have exactly 16-bytes, and the allocation is still 0x10. But when we give another delectation, int e = 10, esp is now allocated 32 bytes (0x20). This shows me that esp, the stack pointer, is only used for automatic variables. Follow-up 2 Call stack and Stack frame Each stack frame Storage space for all the automatic variables for the newly called function. The line number of the calling function to return to when the called function returns. The arguments, or parameters, of the called function. But after we allocated int a through int d, it already took us 16 bytes. Main has no function parameters, so that's zero. But the line to return, where did this information go? A: I although I haven't seen the source code for main() yet, I believe this is due to stack alignment. Under your settings, the stack probably needs to be aligned to 8 bytes. Therefore esp is being incremented by 16 bytes rather than 12 bytes. (even though 12 bytes is enough to hold all the variables) On other systems (with SSE or AVX), the stack will need to be aligned to 16 or 32 bytes. A: Nothing mistical - first four bytes are allocated for return code :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7621948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jquery-ui accordion issue: animation freezes + content not showing when clicking I was trying jQueryUI accordion. I created a test site, copied the code and put things in place. It works fine. Then I tried to put it in my website. In my website, I have two menu. One is horizontal, on the top. The other is vertical, to the left. I intend to apply accordion to the vertical menu. The vertical menu will also change when different item in the top horizontal menu is clicked. First thing I did was testing it on my homepage, just to see if there is any conflicts with my current design. The code for the vertical menu is like this: <!-- leftFrame begin --> <div id="leftFrame"> <div id="accordion"> <h3><a href="#section1">Section 1</a></h3> <div> <p>homepage11111111</p> </div> <h3><a href="#section2">Section 2</a></h3> <div> <p>homepage22222222</p> </div> <h3><a href="#section3">Section 3</a></h3> <div> <p>homepage33333333</p> <ul> <li>List item</li> <li>List item</li> <li>List item</li> <li>List item</li> </ul> <a href="#othercontent">Link to other content</a> </div> </div> </div> <!-- leftFrame end --> <script type="text/javascript"> $(document).ready(function(){ $( "#accordion" ).accordion({ autoHeight: false, navigation: true }); }); </script> Here came the problem. The first penal was expanded as default. When I clicked on a different panel, the content under that panel was not shown. It just expanded a little bit and froze there. The first panel did not collapse either. All panels became not click-able. Like the screenshot below: Interesting thing was, if I put the accordion part in a seperate leftmenu.html file and use "$('#leftFrame').load(leftmenu.html)" to load it into the "leftFrame" div. Everything works again. My first thought was some other javascript or css in the homepage might affect this. I tried to comment out part then all of other javascript or css. It was still not working on the homepage while working fine with the .load function. Any idea why? Thanks in advance Milo A: I turned out to be an easing conflict between different js files. Just make sure to use only one version of easing function. A: I know you have your answer, but for others, I had a similar issue with the same weird behavior when I was adding new sections via a clone. I cloned the first (only) section of the accordion, appended it to the end, then changed the title and contents to suit my need. After that, I destroyed and re-added the accordion to ensure it worked with the new contents. After that, multiple (all new) sections showed as the active one (due to the clone) and when I clicked them, they would initially work but suddenly stop working at some point. To resolve this issue, I did the following: * *Moved the destroy prior to the clone/append *cloned/appended my new sections *modified my section content as needed *Added back the accordion functionality. Hope this helps someone along the line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: about android linkify for maps I am using linkify in my android app to auto recognize addresses. It works with some addresses but not others. One of the things that I noticed was that capitalization is an important thing for the address to be recognized. Spelling is also important. However, even with these, I have not being able to auto recognize all addresses. Can anyone kindly provide more insight as to what should an address look like to be auto recognized by linkify ? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to put span content on top of all other elements without wrapping? I have a span next to each form element on a page that shows an error if there is one. There are basically two columns on the page, a left and a right. I'm trying to get the span to display from the left column all the way across the page (not getting wrapped to a 2nd line at the boundries of the left column). I've been playing around with positioning and z-indexes for a while and can't get it working, so I thought I'd post a jsfiddle to see if someone could help shed some light: http://jsfiddle.net/zZ7MN/3/ A: .one_third, .two_third { float:left; margin-bottom:10px; margin-right:40px; } .formerror { position: absolute; width: auto; left: 320px; top: 45px; border: 1px solid #FF7878; background-color: #FFBABA; padding:4px 6px 4px 6px; color: #D8000C; } A: .formerror { position: absolute; width: 560px; overflow: visible; border: 1px solid #FF7878; background-color: #FFBABA; padding:4px 6px 4px 6px; color: #D8000C; z-index: 999; } Dmitriy was close, his problem was that he was specifying a left attribute. When the position is changed to absolute this causes the span to move N amount of pixels from the left of the screen. Remove the left and give your span a set width and it will no longer wrap!! Here is the solution in jsfiddle http://jsfiddle.net/zZ7MN/8/
{ "language": "en", "url": "https://stackoverflow.com/questions/7621959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to generate a temporary class (result=1) any idea? All of a sudden, out of nowhere, I get this response from my web service hosted locally Unable to generate a temporary class (result=1). error CS0009: Metadata file 'c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll' could not be opened -- 'Unknown error (8013141e)' Everything has been fine and then I get that error without having made any changes to any configuration or anything. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Unable to generate a temporary class (result=1). error CS0009: Metadata file 'c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll' could not be opened -- 'Unknown error (8013141e)' A: The usual suspects: * *Clear c:\windows\temp *Clear C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files *Ditto asp.net 4 / Framework64 etc *Run chkdsk/f *Check anti virus software / host intrusion detection systems for rule updates (rules preventing executing code from temp folders will break .Net serialization for starters) * *if running any security software, disable it temporarily and go from there *Conversely, if you're not running any security software, run one of the free virus scanners (I like Nod32) to see if anything crept in. *Was any windows update applied around the time of the break? Check the update history. Also, check for system restore points. If you just want to get it working and not worry about what happened, you might be able to restore to a point in time before it broke. I'd call that a last resort though!
{ "language": "en", "url": "https://stackoverflow.com/questions/7621960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A python web framework for google app engine (Please note that this question and some of the answers are old) I want to use an existing python framework to develop an application on google appengine. It should be quick and easy to start and support test driven development practices in an easy way. Can you recommend a stack? What about django? Additional Information: There are several django ports, but the stackoverflow questions are already old. There were several django/appengine solutions, I do not know which one is currently leading. (This is now outdated, see accepted answer and also the other answers). But also other frameworks are interesting, not only django. What also sounds good but is not a condition is the possibility to run the app on the framework and the appengine and maybe later run it on a self hosted (noSql-) version of this framework (which maybe could be django, or maybe somehting else). A: UPDATE: This answer is now out of date. For me the choice is djangoappengine. It's a fork of the django project made specifically for no-sql databases like Google App Engine and MongoDB. The main benefit of it is that you get to piggy-back on all the cool stuff coming out of the django project, while also running on GAE's scalable architecture. Another benefit is that with djangoappengine, you can more easily move off of App Engine than if you used their API directly (although that is probably easier said than done). There were rumors that Django would merge the changes into the mainline Django project, but it has not happened yet (as of May 2014). Some relevant links: * *Docs *GitHub *Discussion group A: (Note that this answer is old and no longer valid.) After reading Tom Willis' comment on the question and also this SO question's accepted answer I noticed that webapp/webapp2 looks promising. * *There's some level of commitment from google *It is not necessary to create and maintain own versions for existing SDK handlers *There are libraries that were created with App Engine in mind which are based on webapp and would need a port or adapter to work with other frameworks *It can be used outside appengine *Unit testing is easy to setup and documented here A: I personally have enjoyed using Flask on App Engine using this template: https://github.com/kamalgill/flask-appengine-template The code is organized pretty well in this template and it includes many of the nice development features like profiling and app stats. A: If you want to build large scale application and need a more flexible framework, then you can take a look at Pyramid Python Framework Previously it was called Pylons. There are lot of good companies using this framework. You can find instructions for the process of deploying it to appengine on their website: http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/deployment/gae_buildout.html The process uses buildout and also includes a local testing environment. A: I'm very happy with this boilerplate: https://github.com/coto/gae-boilerplate Take a look at its functions and features, it's very complete! A: I am enjoying http://ferris-framework.appspot.com/ which was written specifically for GAE. I love Django in general, but not for gae, I felt using django-nonrel still requires too many caveats that it is not worth it. A: I wrote GAEStarterKit, which aims to get you up to speed as quickly as possible. It's in a similar vain to projects like GAE-Boilerplate or gae-init, but a few key differences: * *First and most obvious, I used UIKit over HTML5 Boilerplate. Boilerplate is a great choice, and obviously is popularity comes with perks, but for the purposes of getting started quickly, I find uikit a bit more "complete." *I put a lot of work into making sure the user login/registration system is as well-thought-out as possible. Users can have multiple email addresses, multiple authentication methods, and be associated with multiple tenants, if applicable. The social login side for non-Google users is done via Authomatic, which is a great project and very well-supported. *Although it's a little rough around the edges, I did something pretty similar to Django's GenericViews, but in Flask and with GAE Models. I used WTForms integration for that, so it all works pretty well out of the box. It's certainly not perfect, but it's pretty good. *I really took seriously the idea of not repeating myself. For example in gae-init, you'll find a lot of CRUD code. For the admin side, you can add a model to your admin GUI in GAEStarterKit with one import, and one function all. Might be worth considering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Google Translate style select menus I want to style an HTML select menu with CSS in a similar style to how Google does it on Google Translate (translate.google.com). I have looked for tutorials online but everything used jQuery. How can I make something similar to this but using CSS to style it? I hope you can understand my question and what I am trying to describe. A: What google does is have js build a completely different, and style-able html structure from normal dropdown box, which is then styled with css. Using click events on each of the languages a few hidden form elemnt values are edited as you choose new languages to translate between. You can do the same with jQuery and some work. I hope this clarifies how it works. A: If you want to make similar thing just with CSS then forget it - plain impossible. Google utilizes javascript for certain functions like when user picks language it gets selected and will have border and different background when user will try translation next time. If you just want similar dropdown function, then check here
{ "language": "en", "url": "https://stackoverflow.com/questions/7621997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }